blob: 2c27654826b584edc9bd56f1417b4c863fdaf2da [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 Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
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;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100247import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.server.LocalServices;
249import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700250import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800251import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700253import com.android.server.am.ActivityManagerService;
254import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
255import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
256import com.android.server.am.AppTimeTracker;
257import com.android.server.am.BaseErrorDialog;
258import com.android.server.am.EventLogTags;
259import com.android.server.am.PendingIntentController;
260import com.android.server.am.PendingIntentRecord;
261import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900262import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700263import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700264import com.android.server.pm.UserManagerService;
265import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267
Wale Ogunwale31913b52018-10-13 08:29:31 -0700268import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700271import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700274import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700275import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800276import java.lang.annotation.ElementType;
277import java.lang.annotation.Retention;
278import java.lang.annotation.RetentionPolicy;
279import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700280import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700283import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400285import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700288import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Map;
290import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291
292/**
293 * System service for managing activities and their containers (task, stacks, displays,... ).
294 *
295 * {@hide}
296 */
297public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700298 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700300 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
301 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
302 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
303 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
304 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700305 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700306
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700308 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311
Wale Ogunwale98875612018-10-12 07:53:02 -0700312 /** Used to indicate that an app transition should be animated. */
313 static final boolean ANIMATE = true;
314
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700315 /** Hardware-reported OpenGLES version. */
316 final int GL_ES_VERSION;
317
Wale Ogunwale31913b52018-10-13 08:29:31 -0700318 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
319 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
320 public static final String DUMP_LASTANR_CMD = "lastanr" ;
321 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
322 public static final String DUMP_STARTER_CMD = "starter" ;
323 public static final String DUMP_CONTAINERS_CMD = "containers" ;
324 public static final String DUMP_RECENTS_CMD = "recents" ;
325 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
326
Wale Ogunwale64258362018-10-16 15:13:37 -0700327 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
328 public static final int RELAUNCH_REASON_NONE = 0;
329 /** This activity is being relaunched due to windowing mode change. */
330 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
331 /** This activity is being relaunched due to a free-resize operation. */
332 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
333
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700334 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700335
Wale Ogunwalef6733932018-06-27 05:14:34 -0700336 /**
337 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
338 * change at runtime. Use mContext for non-UI purposes.
339 */
340 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700341 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700342 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700343 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700344 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700345 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700346 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800347 @VisibleForTesting
348 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 PowerManagerInternal mPowerManagerInternal;
350 private UsageStatsManagerInternal mUsageStatsInternal;
351
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700352 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 IntentFirewall mIntentFirewall;
354
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700355 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800356 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800357 /**
358 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
359 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
360 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
361 *
362 * @see WindowManagerThreadPriorityBooster
363 */
364 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700365 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800366 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700367 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700368 private UserManagerService mUserManager;
369 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700370 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800371 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700372 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700373 /** All processes currently running that might have a window organized by name. */
374 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700375 /** All processes we currently have running mapped by pid */
376 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /** This is the process holding what we currently consider to be the "home" activity. */
378 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700379 /** The currently running heavy-weight process, if any. */
380 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700381 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /**
383 * This is the process holding the activity the user last visited that is in a different process
384 * from the one they are currently in.
385 */
386 WindowProcessController mPreviousProcess;
387 /** The time at which the previous process was last visible. */
388 long mPreviousProcessVisibleTime;
389
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700390 /** List of intents that were used to start the most recent tasks. */
391 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700392 /** State of external calls telling us if the device is awake or asleep. */
393 private boolean mKeyguardShown = false;
394
395 // Wrapper around VoiceInteractionServiceManager
396 private AssistUtils mAssistUtils;
397
398 // VoiceInteraction session ID that changes for each new request except when
399 // being called for multi-window assist in a single session.
400 private int mViSessionId = 1000;
401
402 // How long to wait in getAssistContextExtras for the activity and foreground services
403 // to respond with the result.
404 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
405
406 // How long top wait when going through the modern assist (which doesn't need to block
407 // on getting this result before starting to launch its UI).
408 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
409
410 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
411 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
412
Alison Cichowlas3e340502018-08-07 17:15:01 -0400413 // Permission tokens are used to temporarily granted a trusted app the ability to call
414 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
415 // showing any appropriate error messages to the user.
416 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
417 10 * MINUTE_IN_MILLIS;
418
419 // How long before the service actually expires a token. This is slightly longer than
420 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
421 // expiration exception.
422 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
423 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
424
425 // How long the service will remember expired tokens, for the purpose of providing error
426 // messaging when a client uses an expired token.
427 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
428 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
429
Marvin Ramin830d4e32019-03-12 13:16:58 +0100430 // How long to whitelist the Services for when requested.
431 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
432
Alison Cichowlas3e340502018-08-07 17:15:01 -0400433 // Activity tokens of system activities that are delegating their call to
434 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
435 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
436
437 // Permission tokens that have expired, but we remember for error reporting.
438 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700440 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
441
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700442 // Keeps track of the active voice interaction service component, notified from
443 // VoiceInteractionManagerService
444 ComponentName mActiveVoiceInteractionServiceComponent;
445
Michal Karpinskida34cd42019-04-02 19:46:52 +0100446 // A map userId and all its companion app uids
447 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000448
Wale Ogunwalee2172292018-10-25 10:11:10 -0700449 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 KeyguardController mKeyguardController;
451 private final ClientLifecycleManager mLifecycleManager;
452 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700453 /** The controller for all operations related to locktask. */
454 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700455 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700456
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700457 boolean mSuppressResizeConfigChanges;
458
459 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
460 new UpdateConfigurationResult();
461
462 static final class UpdateConfigurationResult {
463 // Configuration changes that were updated.
464 int changes;
465 // If the activity was relaunched to match the new configuration.
466 boolean activityRelaunched;
467
468 void reset() {
469 changes = 0;
470 activityRelaunched = false;
471 }
472 }
473
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700474 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700475 private int mConfigurationSeq;
476 // To cache the list of supported system locales
477 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700478
479 /**
480 * Temp object used when global and/or display override configuration is updated. It is also
481 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
482 * anyone...
483 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private Configuration mTempConfig = new Configuration();
485
Wale Ogunwalef6733932018-06-27 05:14:34 -0700486 /** Temporary to avoid allocations. */
487 final StringBuilder mStringBuilder = new StringBuilder(256);
488
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 // Amount of time after a call to stopAppSwitches() during which we will
490 // prevent further untrusted switches from happening.
491 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
492
493 /**
494 * The time at which we will allow normal application switches again,
495 * after a call to {@link #stopAppSwitches()}.
496 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700497 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 /**
499 * This is set to true after the first switch after mAppSwitchesAllowedTime
500 * is set; any switches after that will clear the time.
501 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700502 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503
504 IActivityController mController = null;
505 boolean mControllerIsAMonkey = false;
506
Wale Ogunwale214f3482018-10-04 11:00:47 -0700507 final int mFactoryTest;
508
509 /** Used to control how we initialize the service. */
510 ComponentName mTopComponent;
511 String mTopAction = Intent.ACTION_MAIN;
512 String mTopData;
513
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800514 /** Profiling app information. */
515 String mProfileApp = null;
516 WindowProcessController mProfileProc = null;
517 ProfilerInfo mProfilerInfo = null;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700520 * Dump of the activity state at the time of the last ANR. Cleared after
521 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
522 */
523 String mLastANRState;
524
525 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700526 * Used to retain an update lock when the foreground activity is in
527 * immersive mode.
528 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700529 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530
531 /**
532 * Packages that are being allowed to perform unrestricted app switches. Mapping is
533 * User -> Type -> uid.
534 */
535 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
536
537 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700538 private int mThumbnailWidth;
539 private int mThumbnailHeight;
540 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541
542 /**
543 * Flag that indicates if multi-window is enabled.
544 *
545 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
546 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
547 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
548 * At least one of the forms of multi-window must be enabled in order for this flag to be
549 * initialized to 'true'.
550 *
551 * @see #mSupportsSplitScreenMultiWindow
552 * @see #mSupportsFreeformWindowManagement
553 * @see #mSupportsPictureInPicture
554 * @see #mSupportsMultiDisplay
555 */
556 boolean mSupportsMultiWindow;
557 boolean mSupportsSplitScreenMultiWindow;
558 boolean mSupportsFreeformWindowManagement;
559 boolean mSupportsPictureInPicture;
560 boolean mSupportsMultiDisplay;
561 boolean mForceResizableActivities;
562
563 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
564
565 // VR Vr2d Display Id.
566 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700567
Wale Ogunwalef6733932018-06-27 05:14:34 -0700568 /**
569 * Set while we are wanting to sleep, to prevent any
570 * activities from being started/resumed.
571 *
572 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
573 *
574 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
575 * while in the sleep state until there is a pending transition out of sleep, in which case
576 * mSleeping is set to false, and remains false while awake.
577 *
578 * Whether mSleeping can quickly toggled between true/false without the device actually
579 * display changing states is undefined.
580 */
581 private boolean mSleeping = false;
582
583 /**
584 * The process state used for processes that are running the top activities.
585 * This changes between TOP and TOP_SLEEPING to following mSleeping.
586 */
587 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
588
589 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
590 // automatically. Important for devices without direct input devices.
591 private boolean mShowDialogs = true;
592
593 /** Set if we are shutting down the system, similar to sleeping. */
594 boolean mShuttingDown = false;
595
596 /**
597 * We want to hold a wake lock while running a voice interaction session, since
598 * this may happen with the screen off and we need to keep the CPU running to
599 * be able to continue to interact with the user.
600 */
601 PowerManager.WakeLock mVoiceWakeLock;
602
603 /**
604 * Set while we are running a voice interaction. This overrides sleeping while it is active.
605 */
606 IVoiceInteractionSession mRunningVoice;
607
608 /**
609 * The last resumed activity. This is identical to the current resumed activity most
610 * of the time but could be different when we're pausing one activity before we resume
611 * another activity.
612 */
613 ActivityRecord mLastResumedActivity;
614
615 /**
616 * The activity that is currently being traced as the active resumed activity.
617 *
618 * @see #updateResumedAppTrace
619 */
620 private @Nullable ActivityRecord mTracedResumedActivity;
621
622 /** If non-null, we are tracking the time the user spends in the currently focused app. */
623 AppTimeTracker mCurAppTimeTracker;
624
Wale Ogunwale008163e2018-07-23 23:11:08 -0700625 private AppWarnings mAppWarnings;
626
Wale Ogunwale53783742018-09-16 10:21:51 -0700627 /**
628 * Packages that the user has asked to have run in screen size
629 * compatibility mode instead of filling the screen.
630 */
631 CompatModePackages mCompatModePackages;
632
Wale Ogunwalef6733932018-06-27 05:14:34 -0700633 private FontScaleSettingObserver mFontScaleSettingObserver;
634
Michal Karpinski4026cae2019-02-12 11:51:47 +0000635 private String mDeviceOwnerPackageName;
636
Wale Ogunwalef6733932018-06-27 05:14:34 -0700637 private final class FontScaleSettingObserver extends ContentObserver {
638 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
639 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
640
641 public FontScaleSettingObserver() {
642 super(mH);
643 final ContentResolver resolver = mContext.getContentResolver();
644 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
645 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
646 UserHandle.USER_ALL);
647 }
648
649 @Override
650 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
651 if (mFontScaleUri.equals(uri)) {
652 updateFontScaleIfNeeded(userId);
653 } else if (mHideErrorDialogsUri.equals(uri)) {
654 synchronized (mGlobalLock) {
655 updateShouldShowDialogsLocked(getGlobalConfiguration());
656 }
657 }
658 }
659 }
660
Riddle Hsua0536432019-02-16 00:38:59 +0800661 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
662 @Target(ElementType.METHOD)
663 @Retention(RetentionPolicy.SOURCE)
664 @interface HotPath {
665 int NONE = 0;
666 int OOM_ADJUSTMENT = 1;
667 int LRU_UPDATE = 2;
668 int PROCESS_CHANGE = 3;
669 int caller() default NONE;
670 }
671
Charles Chen8d98dd22018-12-26 17:36:54 +0800672 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
673 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700674 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700675 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700676 mSystemThread = ActivityThread.currentActivityThread();
677 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700678 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800679 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700680 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700681 }
682
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700683 public void onSystemReady() {
684 synchronized (mGlobalLock) {
685 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
686 PackageManager.FEATURE_CANT_SAVE_STATE);
687 mAssistUtils = new AssistUtils(mContext);
688 mVrController.onSystemReady();
689 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700690 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700691 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700692 }
693
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700694 public void onInitPowerManagement() {
695 synchronized (mGlobalLock) {
696 mStackSupervisor.initPowerManagement();
697 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
698 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
699 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
700 mVoiceWakeLock.setReferenceCounted(false);
701 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700702 }
703
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700704 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700705 mFontScaleSettingObserver = new FontScaleSettingObserver();
706 }
707
Wale Ogunwale59507092018-10-29 09:00:30 -0700708 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700709 final boolean freeformWindowManagement =
710 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
711 || Settings.Global.getInt(
712 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
713
714 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
715 final boolean supportsPictureInPicture = supportsMultiWindow &&
716 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
717 final boolean supportsSplitScreenMultiWindow =
718 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
719 final boolean supportsMultiDisplay = mContext.getPackageManager()
720 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700721 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
722 final boolean forceResizable = Settings.Global.getInt(
723 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700724 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725
726 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900727 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728
729 final Configuration configuration = new Configuration();
730 Settings.System.getConfiguration(resolver, configuration);
731 if (forceRtl) {
732 // This will take care of setting the correct layout direction flags
733 configuration.setLayoutDirection(configuration.locale);
734 }
735
736 synchronized (mGlobalLock) {
737 mForceResizableActivities = forceResizable;
738 final boolean multiWindowFormEnabled = freeformWindowManagement
739 || supportsSplitScreenMultiWindow
740 || supportsPictureInPicture
741 || supportsMultiDisplay;
742 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
743 mSupportsMultiWindow = true;
744 mSupportsFreeformWindowManagement = freeformWindowManagement;
745 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
746 mSupportsPictureInPicture = supportsPictureInPicture;
747 mSupportsMultiDisplay = supportsMultiDisplay;
748 } else {
749 mSupportsMultiWindow = false;
750 mSupportsFreeformWindowManagement = false;
751 mSupportsSplitScreenMultiWindow = false;
752 mSupportsPictureInPicture = false;
753 mSupportsMultiDisplay = false;
754 }
755 mWindowManager.setForceResizableTasks(mForceResizableActivities);
756 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700757 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
758 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700759 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700760 // This happens before any activities are started, so we can change global configuration
761 // in-place.
762 updateConfigurationLocked(configuration, null, true);
763 final Configuration globalConfig = getGlobalConfiguration();
764 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
765
766 // Load resources only after the current configuration has been set.
767 final Resources res = mContext.getResources();
768 mThumbnailWidth = res.getDimensionPixelSize(
769 com.android.internal.R.dimen.thumbnail_width);
770 mThumbnailHeight = res.getDimensionPixelSize(
771 com.android.internal.R.dimen.thumbnail_height);
772
773 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
774 mFullscreenThumbnailScale = (float) res
775 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
776 (float) globalConfig.screenWidthDp;
777 } else {
778 mFullscreenThumbnailScale = res.getFraction(
779 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
780 }
781 }
782 }
783
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800784 public WindowManagerGlobalLock getGlobalLock() {
785 return mGlobalLock;
786 }
787
Yunfan Chen585f2932019-01-29 16:04:45 +0900788 /** For test purpose only. */
789 @VisibleForTesting
790 public ActivityTaskManagerInternal getAtmInternal() {
791 return mInternal;
792 }
793
Riddle Hsud93a6c42018-11-29 21:50:06 +0800794 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
795 Looper looper) {
796 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700798 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700799 final File systemDir = SystemServiceManager.ensureSystemDir();
800 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
801 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700802 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700803
804 mTempConfig.setToDefaults();
805 mTempConfig.setLocales(LocaleList.getDefault());
806 mConfigurationSeq = mTempConfig.seq = 1;
807 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800808 mRootActivityContainer = new RootActivityContainer(this);
809 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700810
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700811 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700812 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700813 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700814 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700815 mRecentTasks = createRecentTasks();
816 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700818 mKeyguardController = mStackSupervisor.getKeyguardController();
819 }
820
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700821 public void onActivityManagerInternalAdded() {
822 synchronized (mGlobalLock) {
823 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
824 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
825 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700826 }
827
Yunfan Chen75157d72018-07-27 14:47:21 +0900828 int increaseConfigurationSeqLocked() {
829 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
830 return mConfigurationSeq;
831 }
832
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833 protected ActivityStackSupervisor createStackSupervisor() {
834 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
835 supervisor.initialize();
836 return supervisor;
837 }
838
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700839 public void setWindowManager(WindowManagerService wm) {
840 synchronized (mGlobalLock) {
841 mWindowManager = wm;
842 mLockTaskController.setWindowManager(wm);
843 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800844 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700845 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700846 }
847
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
849 synchronized (mGlobalLock) {
850 mUsageStatsInternal = usageStatsManager;
851 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700852 }
853
Wale Ogunwalef6733932018-06-27 05:14:34 -0700854 UserManagerService getUserManager() {
855 if (mUserManager == null) {
856 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
857 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
858 }
859 return mUserManager;
860 }
861
862 AppOpsService getAppOpsService() {
863 if (mAppOpsService == null) {
864 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
865 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
866 }
867 return mAppOpsService;
868 }
869
870 boolean hasUserRestriction(String restriction, int userId) {
871 return getUserManager().hasUserRestriction(restriction, userId);
872 }
873
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700874 protected RecentTasks createRecentTasks() {
875 return new RecentTasks(this, mStackSupervisor);
876 }
877
878 RecentTasks getRecentTasks() {
879 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700880 }
881
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700882 ClientLifecycleManager getLifecycleManager() {
883 return mLifecycleManager;
884 }
885
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700886 ActivityStartController getActivityStartController() {
887 return mActivityStartController;
888 }
889
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700890 TaskChangeNotificationController getTaskChangeNotificationController() {
891 return mTaskChangeNotificationController;
892 }
893
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700894 LockTaskController getLockTaskController() {
895 return mLockTaskController;
896 }
897
Yunfan Chen75157d72018-07-27 14:47:21 +0900898 /**
899 * Return the global configuration used by the process corresponding to the input pid. This is
900 * usually the global configuration with some overrides specific to that process.
901 */
902 Configuration getGlobalConfigurationForCallingPid() {
903 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800904 return getGlobalConfigurationForPid(pid);
905 }
906
907 /**
908 * Return the global configuration used by the process corresponding to the given pid.
909 */
910 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900911 if (pid == MY_PID || pid < 0) {
912 return getGlobalConfiguration();
913 }
914 synchronized (mGlobalLock) {
915 final WindowProcessController app = mPidMap.get(pid);
916 return app != null ? app.getConfiguration() : getGlobalConfiguration();
917 }
918 }
919
920 /**
921 * Return the device configuration info used by the process corresponding to the input pid.
922 * The value is consistent with the global configuration for the process.
923 */
924 @Override
925 public ConfigurationInfo getDeviceConfigurationInfo() {
926 ConfigurationInfo config = new ConfigurationInfo();
927 synchronized (mGlobalLock) {
928 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
929 config.reqTouchScreen = globalConfig.touchscreen;
930 config.reqKeyboardType = globalConfig.keyboard;
931 config.reqNavigation = globalConfig.navigation;
932 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
933 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
934 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
935 }
936 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
937 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
938 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
939 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700940 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900941 }
942 return config;
943 }
944
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700945 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700946 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700947 }
948
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700949 public static final class Lifecycle extends SystemService {
950 private final ActivityTaskManagerService mService;
951
952 public Lifecycle(Context context) {
953 super(context);
954 mService = new ActivityTaskManagerService(context);
955 }
956
957 @Override
958 public void onStart() {
959 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700961 }
962
Garfield Tan891146c2018-10-09 12:14:00 -0700963 @Override
964 public void onUnlockUser(int userId) {
965 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800966 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700967 }
968 }
969
970 @Override
971 public void onCleanupUser(int userId) {
972 synchronized (mService.getGlobalLock()) {
973 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
974 }
975 }
976
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700977 public ActivityTaskManagerService getService() {
978 return mService;
979 }
980 }
981
982 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700983 public final int startActivity(IApplicationThread caller, String callingPackage,
984 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
985 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
986 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
987 resultWho, requestCode, startFlags, profilerInfo, bOptions,
988 UserHandle.getCallingUserId());
989 }
990
991 @Override
992 public final int startActivities(IApplicationThread caller, String callingPackage,
993 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
994 int userId) {
995 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700996 enforceNotIsolatedCaller(reason);
997 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000999 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1000 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1001 reason, null /* originatingPendingIntent */,
1002 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001003 }
1004
1005 @Override
1006 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1007 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1008 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1009 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1010 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1011 true /*validateIncomingUser*/);
1012 }
1013
1014 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1015 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1016 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1017 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001018 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001020 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1022
1023 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001024 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001025 .setCaller(caller)
1026 .setCallingPackage(callingPackage)
1027 .setResolvedType(resolvedType)
1028 .setResultTo(resultTo)
1029 .setResultWho(resultWho)
1030 .setRequestCode(requestCode)
1031 .setStartFlags(startFlags)
1032 .setProfilerInfo(profilerInfo)
1033 .setActivityOptions(bOptions)
1034 .setMayWait(userId)
1035 .execute();
1036
1037 }
1038
1039 @Override
1040 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1041 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001042 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1043 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 // Refuse possible leaked file descriptors
1045 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1046 throw new IllegalArgumentException("File descriptors passed in Intent");
1047 }
1048
1049 if (!(target instanceof PendingIntentRecord)) {
1050 throw new IllegalArgumentException("Bad PendingIntent object");
1051 }
1052
1053 PendingIntentRecord pir = (PendingIntentRecord)target;
1054
1055 synchronized (mGlobalLock) {
1056 // If this is coming from the currently resumed activity, it is
1057 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001058 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059 if (stack.mResumedActivity != null &&
1060 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001061 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 }
1063 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 }
1067
1068 @Override
1069 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1070 Bundle bOptions) {
1071 // Refuse possible leaked file descriptors
1072 if (intent != null && intent.hasFileDescriptors()) {
1073 throw new IllegalArgumentException("File descriptors passed in Intent");
1074 }
1075 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1076
1077 synchronized (mGlobalLock) {
1078 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1079 if (r == null) {
1080 SafeActivityOptions.abort(options);
1081 return false;
1082 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001083 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 // The caller is not running... d'oh!
1085 SafeActivityOptions.abort(options);
1086 return false;
1087 }
1088 intent = new Intent(intent);
1089 // The caller is not allowed to change the data.
1090 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1091 // And we are resetting to find the next component...
1092 intent.setComponent(null);
1093
1094 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1095
1096 ActivityInfo aInfo = null;
1097 try {
1098 List<ResolveInfo> resolves =
1099 AppGlobals.getPackageManager().queryIntentActivities(
1100 intent, r.resolvedType,
1101 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1102 UserHandle.getCallingUserId()).getList();
1103
1104 // Look for the original activity in the list...
1105 final int N = resolves != null ? resolves.size() : 0;
1106 for (int i=0; i<N; i++) {
1107 ResolveInfo rInfo = resolves.get(i);
1108 if (rInfo.activityInfo.packageName.equals(r.packageName)
1109 && rInfo.activityInfo.name.equals(r.info.name)) {
1110 // We found the current one... the next matching is
1111 // after it.
1112 i++;
1113 if (i<N) {
1114 aInfo = resolves.get(i).activityInfo;
1115 }
1116 if (debug) {
1117 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1118 + "/" + r.info.name);
1119 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1120 ? "null" : aInfo.packageName + "/" + aInfo.name));
1121 }
1122 break;
1123 }
1124 }
1125 } catch (RemoteException e) {
1126 }
1127
1128 if (aInfo == null) {
1129 // Nobody who is next!
1130 SafeActivityOptions.abort(options);
1131 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1132 return false;
1133 }
1134
1135 intent.setComponent(new ComponentName(
1136 aInfo.applicationInfo.packageName, aInfo.name));
1137 intent.setFlags(intent.getFlags()&~(
1138 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1139 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1140 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1141 FLAG_ACTIVITY_NEW_TASK));
1142
1143 // Okay now we need to start the new activity, replacing the currently running activity.
1144 // This is a little tricky because we want to start the new one as if the current one is
1145 // finished, but not finish the current one first so that there is no flicker.
1146 // And thus...
1147 final boolean wasFinishing = r.finishing;
1148 r.finishing = true;
1149
1150 // Propagate reply information over to the new activity.
1151 final ActivityRecord resultTo = r.resultTo;
1152 final String resultWho = r.resultWho;
1153 final int requestCode = r.requestCode;
1154 r.resultTo = null;
1155 if (resultTo != null) {
1156 resultTo.removeResultsLocked(r, resultWho, requestCode);
1157 }
1158
1159 final long origId = Binder.clearCallingIdentity();
1160 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001161 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001162 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001163 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001164 .setResolvedType(r.resolvedType)
1165 .setActivityInfo(aInfo)
1166 .setResultTo(resultTo != null ? resultTo.appToken : null)
1167 .setResultWho(resultWho)
1168 .setRequestCode(requestCode)
1169 .setCallingPid(-1)
1170 .setCallingUid(r.launchedFromUid)
1171 .setCallingPackage(r.launchedFromPackage)
1172 .setRealCallingPid(-1)
1173 .setRealCallingUid(r.launchedFromUid)
1174 .setActivityOptions(options)
1175 .execute();
1176 Binder.restoreCallingIdentity(origId);
1177
1178 r.finishing = wasFinishing;
1179 if (res != ActivityManager.START_SUCCESS) {
1180 return false;
1181 }
1182 return true;
1183 }
1184 }
1185
1186 @Override
1187 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1188 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1189 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1190 final WaitResult res = new WaitResult();
1191 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001192 enforceNotIsolatedCaller("startActivityAndWait");
1193 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1194 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001195 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001196 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001197 .setCaller(caller)
1198 .setCallingPackage(callingPackage)
1199 .setResolvedType(resolvedType)
1200 .setResultTo(resultTo)
1201 .setResultWho(resultWho)
1202 .setRequestCode(requestCode)
1203 .setStartFlags(startFlags)
1204 .setActivityOptions(bOptions)
1205 .setMayWait(userId)
1206 .setProfilerInfo(profilerInfo)
1207 .setWaitResult(res)
1208 .execute();
1209 }
1210 return res;
1211 }
1212
1213 @Override
1214 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1215 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1216 int startFlags, Configuration config, Bundle bOptions, int userId) {
1217 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001218 enforceNotIsolatedCaller("startActivityWithConfig");
1219 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1220 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001222 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001223 .setCaller(caller)
1224 .setCallingPackage(callingPackage)
1225 .setResolvedType(resolvedType)
1226 .setResultTo(resultTo)
1227 .setResultWho(resultWho)
1228 .setRequestCode(requestCode)
1229 .setStartFlags(startFlags)
1230 .setGlobalConfiguration(config)
1231 .setActivityOptions(bOptions)
1232 .setMayWait(userId)
1233 .execute();
1234 }
1235 }
1236
Alison Cichowlas3e340502018-08-07 17:15:01 -04001237
1238 @Override
1239 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1240 int callingUid = Binder.getCallingUid();
1241 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1242 throw new SecurityException("Only the system process can request a permission token, "
1243 + "received request from uid: " + callingUid);
1244 }
1245 IBinder permissionToken = new Binder();
1246 synchronized (mGlobalLock) {
1247 mStartActivitySources.put(permissionToken, delegatorToken);
1248 }
1249
1250 Message expireMsg = PooledLambda.obtainMessage(
1251 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1252 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1253
1254 Message forgetMsg = PooledLambda.obtainMessage(
1255 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1256 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1257
1258 return permissionToken;
1259 }
1260
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001261 @Override
1262 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1263 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001264 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1265 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267 // permission grants) as any app that may launch one of your own activities. So we only
1268 // allow this in two cases:
1269 // 1) The caller is an activity that is part of the core framework, and then only when it
1270 // is running as the system.
1271 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1272 // can only be requested by a system activity, which may then delegate this call to
1273 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 final ActivityRecord sourceRecord;
1275 final int targetUid;
1276 final String targetPackage;
1277 final boolean isResolver;
1278 synchronized (mGlobalLock) {
1279 if (resultTo == null) {
1280 throw new SecurityException("Must be called from an activity");
1281 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 final IBinder sourceToken;
1283 if (permissionToken != null) {
1284 // To even attempt to use a permissionToken, an app must also have this signature
1285 // permission.
1286 mAmInternal.enforceCallingPermission(
1287 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1288 "startActivityAsCaller");
1289 // If called with a permissionToken, we want the sourceRecord from the delegator
1290 // activity that requested this token.
1291 sourceToken = mStartActivitySources.remove(permissionToken);
1292 if (sourceToken == null) {
1293 // Invalid permissionToken, check if it recently expired.
1294 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1295 throw new SecurityException("Called with expired permission token: "
1296 + permissionToken);
1297 } else {
1298 throw new SecurityException("Called with invalid permission token: "
1299 + permissionToken);
1300 }
1301 }
1302 } else {
1303 // This method was called directly by the source.
1304 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001306
Wale Ogunwaled32da472018-11-16 07:19:28 -08001307 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001308 if (sourceRecord == null) {
1309 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 }
1311 if (sourceRecord.app == null) {
1312 throw new SecurityException("Called without a process attached to activity");
1313 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001314
1315 // Whether called directly or from a delegate, the source activity must be from the
1316 // android package.
1317 if (!sourceRecord.info.packageName.equals("android")) {
1318 throw new SecurityException("Must be called from an activity that is "
1319 + "declared in the android package");
1320 }
1321
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001322 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 // This is still okay, as long as this activity is running under the
1324 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001325 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001327 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001328 + " must be system uid or original calling uid "
1329 + sourceRecord.launchedFromUid);
1330 }
1331 }
1332 if (ignoreTargetSecurity) {
1333 if (intent.getComponent() == null) {
1334 throw new SecurityException(
1335 "Component must be specified with ignoreTargetSecurity");
1336 }
1337 if (intent.getSelector() != null) {
1338 throw new SecurityException(
1339 "Selector not allowed with ignoreTargetSecurity");
1340 }
1341 }
1342 targetUid = sourceRecord.launchedFromUid;
1343 targetPackage = sourceRecord.launchedFromPackage;
1344 isResolver = sourceRecord.isResolverOrChildActivity();
1345 }
1346
1347 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001348 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 }
1350
1351 // TODO: Switch to user app stacks here.
1352 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001353 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 .setCallingUid(targetUid)
1355 .setCallingPackage(targetPackage)
1356 .setResolvedType(resolvedType)
1357 .setResultTo(resultTo)
1358 .setResultWho(resultWho)
1359 .setRequestCode(requestCode)
1360 .setStartFlags(startFlags)
1361 .setActivityOptions(bOptions)
1362 .setMayWait(userId)
1363 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1364 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1365 .execute();
1366 } catch (SecurityException e) {
1367 // XXX need to figure out how to propagate to original app.
1368 // A SecurityException here is generally actually a fault of the original
1369 // calling activity (such as a fairly granting permissions), so propagate it
1370 // back to them.
1371 /*
1372 StringBuilder msg = new StringBuilder();
1373 msg.append("While launching");
1374 msg.append(intent.toString());
1375 msg.append(": ");
1376 msg.append(e.getMessage());
1377 */
1378 throw e;
1379 }
1380 }
1381
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001382 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1383 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1384 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1385 }
1386
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 @Override
1388 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1389 Intent intent, String resolvedType, IVoiceInteractionSession session,
1390 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1391 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001393 if (session == null || interactor == null) {
1394 throw new NullPointerException("null session or interactor");
1395 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001396 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001398 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 .setCallingUid(callingUid)
1400 .setCallingPackage(callingPackage)
1401 .setResolvedType(resolvedType)
1402 .setVoiceSession(session)
1403 .setVoiceInteractor(interactor)
1404 .setStartFlags(startFlags)
1405 .setProfilerInfo(profilerInfo)
1406 .setActivityOptions(bOptions)
1407 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001408 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 .execute();
1410 }
1411
1412 @Override
1413 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1414 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001415 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1416 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001418 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 .setCallingUid(callingUid)
1420 .setCallingPackage(callingPackage)
1421 .setResolvedType(resolvedType)
1422 .setActivityOptions(bOptions)
1423 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001424 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 .execute();
1426 }
1427
1428 @Override
1429 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1430 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 final int callingPid = Binder.getCallingPid();
1433 final long origId = Binder.clearCallingIdentity();
1434 try {
1435 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001436 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1437 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438
1439 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001440 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1441 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1443 recentsUid, assistDataReceiver);
1444 }
1445 } finally {
1446 Binder.restoreCallingIdentity(origId);
1447 }
1448 }
1449
1450 @Override
1451 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001452 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 "startActivityFromRecents()");
1454
1455 final int callingPid = Binder.getCallingPid();
1456 final int callingUid = Binder.getCallingUid();
1457 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1458 final long origId = Binder.clearCallingIdentity();
1459 try {
1460 synchronized (mGlobalLock) {
1461 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1462 safeOptions);
1463 }
1464 } finally {
1465 Binder.restoreCallingIdentity(origId);
1466 }
1467 }
1468
1469 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001470 * Public API to check if the client is allowed to start an activity on specified display.
1471 *
1472 * If the target display is private or virtual, some restrictions will apply.
1473 *
1474 * @param displayId Target display id.
1475 * @param intent Intent used to launch the activity.
1476 * @param resolvedType The MIME type of the intent.
1477 * @param userId The id of the user for whom the call is made.
1478 * @return {@code true} if a call to start an activity on the target display should succeed and
1479 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1480 */
1481 @Override
1482 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1483 String resolvedType, int userId) {
1484 final int callingUid = Binder.getCallingUid();
1485 final int callingPid = Binder.getCallingPid();
1486 final long origId = Binder.clearCallingIdentity();
1487
1488 try {
1489 // Collect information about the target of the Intent.
1490 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1491 0 /* startFlags */, null /* profilerInfo */, userId,
1492 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1493 UserHandle.USER_NULL));
1494 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1495
1496 synchronized (mGlobalLock) {
1497 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1498 aInfo);
1499 }
1500 } finally {
1501 Binder.restoreCallingIdentity(origId);
1502 }
1503 }
1504
1505 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506 * This is the internal entry point for handling Activity.finish().
1507 *
1508 * @param token The Binder token referencing the Activity we want to finish.
1509 * @param resultCode Result code, if any, from this Activity.
1510 * @param resultData Result data (Intent), if any, from this Activity.
1511 * @param finishTask Whether to finish the task associated with this Activity.
1512 *
1513 * @return Returns true if the activity successfully finished, or false if it is still running.
1514 */
1515 @Override
1516 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1517 int finishTask) {
1518 // Refuse possible leaked file descriptors
1519 if (resultData != null && resultData.hasFileDescriptors()) {
1520 throw new IllegalArgumentException("File descriptors passed in Intent");
1521 }
1522
1523 synchronized (mGlobalLock) {
1524 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1525 if (r == null) {
1526 return true;
1527 }
1528 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001529 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530 ActivityRecord rootR = tr.getRootActivity();
1531 if (rootR == null) {
1532 Slog.w(TAG, "Finishing task with all activities already finished");
1533 }
1534 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1535 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001536 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001537 return false;
1538 }
1539
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001540 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1541 // We should consolidate.
1542 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001543 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001544 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001545 if (next != null) {
1546 // ask watcher if this is allowed
1547 boolean resumeOK = true;
1548 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001549 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001551 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 Watchdog.getInstance().setActivityController(null);
1553 }
1554
1555 if (!resumeOK) {
1556 Slog.i(TAG, "Not finishing activity because controller resumed");
1557 return false;
1558 }
1559 }
1560 }
1561 final long origId = Binder.clearCallingIdentity();
1562 try {
1563 boolean res;
1564 final boolean finishWithRootActivity =
1565 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1566 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1567 || (finishWithRootActivity && r == rootR)) {
1568 // If requested, remove the task that is associated to this activity only if it
1569 // was the root activity in the task. The result code and data is ignored
1570 // because we don't support returning them across task boundaries. Also, to
1571 // keep backwards compatibility we remove the task from recents when finishing
1572 // task with root activity.
1573 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1574 finishWithRootActivity, "finish-activity");
1575 if (!res) {
1576 Slog.i(TAG, "Removing task failed to finish activity");
1577 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001578 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001579 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 } else {
1581 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1582 resultData, "app-request", true);
1583 if (!res) {
1584 Slog.i(TAG, "Failed to finish by app-request");
1585 }
1586 }
1587 return res;
1588 } finally {
1589 Binder.restoreCallingIdentity(origId);
1590 }
1591 }
1592 }
1593
1594 @Override
1595 public boolean finishActivityAffinity(IBinder token) {
1596 synchronized (mGlobalLock) {
1597 final long origId = Binder.clearCallingIdentity();
1598 try {
1599 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1600 if (r == null) {
1601 return false;
1602 }
1603
1604 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1605 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001606 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001607 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001608 return false;
1609 }
1610 return task.getStack().finishActivityAffinityLocked(r);
1611 } finally {
1612 Binder.restoreCallingIdentity(origId);
1613 }
1614 }
1615 }
1616
1617 @Override
1618 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1619 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001620 try {
1621 WindowProcessController proc = null;
1622 synchronized (mGlobalLock) {
1623 ActivityStack stack = ActivityRecord.getStackLocked(token);
1624 if (stack == null) {
1625 return;
1626 }
1627 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1628 false /* fromTimeout */, false /* processPausingActivities */, config);
1629 if (r != null) {
1630 proc = r.app;
1631 }
1632 if (stopProfiling && proc != null) {
1633 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 }
1635 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001636 } finally {
1637 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 }
1640
1641 @Override
1642 public final void activityResumed(IBinder token) {
1643 final long origId = Binder.clearCallingIdentity();
1644 synchronized (mGlobalLock) {
1645 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001646 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 }
1648 Binder.restoreCallingIdentity(origId);
1649 }
1650
1651 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001652 public final void activityTopResumedStateLost() {
1653 final long origId = Binder.clearCallingIdentity();
1654 synchronized (mGlobalLock) {
1655 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1656 }
1657 Binder.restoreCallingIdentity(origId);
1658 }
1659
1660 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 public final void activityPaused(IBinder token) {
1662 final long origId = Binder.clearCallingIdentity();
1663 synchronized (mGlobalLock) {
1664 ActivityStack stack = ActivityRecord.getStackLocked(token);
1665 if (stack != null) {
1666 stack.activityPausedLocked(token, false);
1667 }
1668 }
1669 Binder.restoreCallingIdentity(origId);
1670 }
1671
1672 @Override
1673 public final void activityStopped(IBinder token, Bundle icicle,
1674 PersistableBundle persistentState, CharSequence description) {
1675 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1676
1677 // Refuse possible leaked file descriptors
1678 if (icicle != null && icicle.hasFileDescriptors()) {
1679 throw new IllegalArgumentException("File descriptors passed in Bundle");
1680 }
1681
1682 final long origId = Binder.clearCallingIdentity();
1683
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001684 String restartingName = null;
1685 int restartingUid = 0;
1686 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001687 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001688 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001690 if (r.attachedToProcess()
1691 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1692 // The activity was requested to restart from
1693 // {@link #restartActivityProcessIfVisible}.
1694 restartingName = r.app.mName;
1695 restartingUid = r.app.mUid;
1696 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 r.activityStoppedLocked(icicle, persistentState, description);
1698 }
1699 }
1700
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001701 if (restartingName != null) {
1702 // In order to let the foreground activity can be restarted with its saved state from
1703 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1704 // until the activity reports stopped with the state. And the activity record will be
1705 // kept because the record state is restarting, then the activity will be restarted
1706 // immediately if it is still the top one.
1707 mStackSupervisor.removeRestartTimeouts(r);
1708 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1709 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001710 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711
1712 Binder.restoreCallingIdentity(origId);
1713 }
1714
1715 @Override
1716 public final void activityDestroyed(IBinder token) {
1717 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1718 synchronized (mGlobalLock) {
1719 ActivityStack stack = ActivityRecord.getStackLocked(token);
1720 if (stack != null) {
1721 stack.activityDestroyedLocked(token, "activityDestroyed");
1722 }
1723 }
1724 }
1725
1726 @Override
1727 public final void activityRelaunched(IBinder token) {
1728 final long origId = Binder.clearCallingIdentity();
1729 synchronized (mGlobalLock) {
1730 mStackSupervisor.activityRelaunchedLocked(token);
1731 }
1732 Binder.restoreCallingIdentity(origId);
1733 }
1734
1735 public final void activitySlept(IBinder token) {
1736 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1737
1738 final long origId = Binder.clearCallingIdentity();
1739
1740 synchronized (mGlobalLock) {
1741 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1742 if (r != null) {
1743 mStackSupervisor.activitySleptLocked(r);
1744 }
1745 }
1746
1747 Binder.restoreCallingIdentity(origId);
1748 }
1749
1750 @Override
1751 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1752 synchronized (mGlobalLock) {
1753 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1754 if (r == null) {
1755 return;
1756 }
1757 final long origId = Binder.clearCallingIdentity();
1758 try {
1759 r.setRequestedOrientation(requestedOrientation);
1760 } finally {
1761 Binder.restoreCallingIdentity(origId);
1762 }
1763 }
1764 }
1765
1766 @Override
1767 public int getRequestedOrientation(IBinder token) {
1768 synchronized (mGlobalLock) {
1769 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1770 if (r == null) {
1771 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1772 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001773 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 }
1775 }
1776
1777 @Override
1778 public void setImmersive(IBinder token, boolean immersive) {
1779 synchronized (mGlobalLock) {
1780 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1781 if (r == null) {
1782 throw new IllegalArgumentException();
1783 }
1784 r.immersive = immersive;
1785
1786 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001787 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001789 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 }
1791 }
1792 }
1793
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001794 void applyUpdateLockStateLocked(ActivityRecord r) {
1795 // Modifications to the UpdateLock state are done on our handler, outside
1796 // the activity manager's locks. The new state is determined based on the
1797 // state *now* of the relevant activity record. The object is passed to
1798 // the handler solely for logging detail, not to be consulted/modified.
1799 final boolean nextState = r != null && r.immersive;
1800 mH.post(() -> {
1801 if (mUpdateLock.isHeld() != nextState) {
1802 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1803 "Applying new update lock state '" + nextState + "' for " + r);
1804 if (nextState) {
1805 mUpdateLock.acquire();
1806 } else {
1807 mUpdateLock.release();
1808 }
1809 }
1810 });
1811 }
1812
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 @Override
1814 public boolean isImmersive(IBinder token) {
1815 synchronized (mGlobalLock) {
1816 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1817 if (r == null) {
1818 throw new IllegalArgumentException();
1819 }
1820 return r.immersive;
1821 }
1822 }
1823
1824 @Override
1825 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001826 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001827 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001828 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001829 return (r != null) ? r.immersive : false;
1830 }
1831 }
1832
1833 @Override
1834 public void overridePendingTransition(IBinder token, String packageName,
1835 int enterAnim, int exitAnim) {
1836 synchronized (mGlobalLock) {
1837 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1838 if (self == null) {
1839 return;
1840 }
1841
1842 final long origId = Binder.clearCallingIdentity();
1843
1844 if (self.isState(
1845 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001846 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001847 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001848 }
1849
1850 Binder.restoreCallingIdentity(origId);
1851 }
1852 }
1853
1854 @Override
1855 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001856 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001857 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001858 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 if (r == null) {
1860 return ActivityManager.COMPAT_MODE_UNKNOWN;
1861 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001862 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 }
1864 }
1865
1866 @Override
1867 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001872 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001873 if (r == null) {
1874 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1875 return;
1876 }
1877 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001878 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 }
1880 }
1881
1882 @Override
1883 public int getLaunchedFromUid(IBinder activityToken) {
1884 ActivityRecord srec;
1885 synchronized (mGlobalLock) {
1886 srec = ActivityRecord.forTokenLocked(activityToken);
1887 }
1888 if (srec == null) {
1889 return -1;
1890 }
1891 return srec.launchedFromUid;
1892 }
1893
1894 @Override
1895 public String getLaunchedFromPackage(IBinder activityToken) {
1896 ActivityRecord srec;
1897 synchronized (mGlobalLock) {
1898 srec = ActivityRecord.forTokenLocked(activityToken);
1899 }
1900 if (srec == null) {
1901 return null;
1902 }
1903 return srec.launchedFromPackage;
1904 }
1905
1906 @Override
1907 public boolean convertFromTranslucent(IBinder token) {
1908 final long origId = Binder.clearCallingIdentity();
1909 try {
1910 synchronized (mGlobalLock) {
1911 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1912 if (r == null) {
1913 return false;
1914 }
1915 final boolean translucentChanged = r.changeWindowTranslucency(true);
1916 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001917 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001919 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 return translucentChanged;
1921 }
1922 } finally {
1923 Binder.restoreCallingIdentity(origId);
1924 }
1925 }
1926
1927 @Override
1928 public boolean convertToTranslucent(IBinder token, Bundle options) {
1929 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1930 final long origId = Binder.clearCallingIdentity();
1931 try {
1932 synchronized (mGlobalLock) {
1933 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1934 if (r == null) {
1935 return false;
1936 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001937 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 int index = task.mActivities.lastIndexOf(r);
1939 if (index > 0) {
1940 ActivityRecord under = task.mActivities.get(index - 1);
1941 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1942 }
1943 final boolean translucentChanged = r.changeWindowTranslucency(false);
1944 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001945 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001947 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 return translucentChanged;
1950 }
1951 } finally {
1952 Binder.restoreCallingIdentity(origId);
1953 }
1954 }
1955
1956 @Override
1957 public void notifyActivityDrawn(IBinder token) {
1958 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1959 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001960 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001962 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 }
1964 }
1965 }
1966
1967 @Override
1968 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1969 synchronized (mGlobalLock) {
1970 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 return;
1973 }
1974 r.reportFullyDrawnLocked(restoredFromBundle);
1975 }
1976 }
1977
1978 @Override
1979 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1980 synchronized (mGlobalLock) {
1981 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1982 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1983 return stack.mDisplayId;
1984 }
1985 return DEFAULT_DISPLAY;
1986 }
1987 }
1988
1989 @Override
1990 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001991 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 long ident = Binder.clearCallingIdentity();
1993 try {
1994 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001995 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001997 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 }
1999 return null;
2000 }
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 }
2005
2006 @Override
2007 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002008 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2010 final long callingId = Binder.clearCallingIdentity();
2011 try {
2012 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002013 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 if (stack == null) {
2015 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2016 return;
2017 }
2018 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002019 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002020 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 }
2022 }
2023 } finally {
2024 Binder.restoreCallingIdentity(callingId);
2025 }
2026 }
2027
2028 @Override
2029 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002030 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2032 final long callingId = Binder.clearCallingIdentity();
2033 try {
2034 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002035 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002036 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 if (task == null) {
2038 return;
2039 }
2040 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002041 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002042 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 }
2044 }
2045 } finally {
2046 Binder.restoreCallingIdentity(callingId);
2047 }
2048 }
2049
2050 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002051 public void restartActivityProcessIfVisible(IBinder activityToken) {
2052 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2053 final long callingId = Binder.clearCallingIdentity();
2054 try {
2055 synchronized (mGlobalLock) {
2056 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2057 if (r == null) {
2058 return;
2059 }
2060 r.restartProcessIfVisible();
2061 }
2062 } finally {
2063 Binder.restoreCallingIdentity(callingId);
2064 }
2065 }
2066
2067 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002069 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 synchronized (mGlobalLock) {
2071 final long ident = Binder.clearCallingIdentity();
2072 try {
2073 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2074 "remove-task");
2075 } finally {
2076 Binder.restoreCallingIdentity(ident);
2077 }
2078 }
2079 }
2080
2081 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002082 public void removeAllVisibleRecentTasks() {
2083 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2084 synchronized (mGlobalLock) {
2085 final long ident = Binder.clearCallingIdentity();
2086 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002087 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002088 } finally {
2089 Binder.restoreCallingIdentity(ident);
2090 }
2091 }
2092 }
2093
2094 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2096 synchronized (mGlobalLock) {
2097 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2098 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002099 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002100 }
2101 }
2102 return false;
2103 }
2104
2105 @Override
2106 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2107 Intent resultData) {
2108
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2111 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002112 return r.getActivityStack().navigateUpToLocked(
2113 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002114 }
2115 return false;
2116 }
2117 }
2118
2119 /**
2120 * Attempts to move a task backwards in z-order (the order of activities within the task is
2121 * unchanged).
2122 *
2123 * There are several possible results of this call:
2124 * - if the task is locked, then we will show the lock toast
2125 * - if there is a task behind the provided task, then that task is made visible and resumed as
2126 * this task is moved to the back
2127 * - otherwise, if there are no other tasks in the stack:
2128 * - if this task is in the pinned stack, then we remove the stack completely, which will
2129 * have the effect of moving the task to the top or bottom of the fullscreen stack
2130 * (depending on whether it is visible)
2131 * - otherwise, we simply return home and hide this task
2132 *
2133 * @param token A reference to the activity we wish to move
2134 * @param nonRoot If false then this only works if the activity is the root
2135 * of a task; if true it will work for any activity in a task.
2136 * @return Returns true if the move completed, false if not.
2137 */
2138 @Override
2139 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002140 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002141 synchronized (mGlobalLock) {
2142 final long origId = Binder.clearCallingIdentity();
2143 try {
2144 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002145 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002146 if (task != null) {
2147 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2148 }
2149 } finally {
2150 Binder.restoreCallingIdentity(origId);
2151 }
2152 }
2153 return false;
2154 }
2155
2156 @Override
2157 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002158 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 long ident = Binder.clearCallingIdentity();
2160 Rect rect = new Rect();
2161 try {
2162 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002163 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2165 if (task == null) {
2166 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2167 return rect;
2168 }
2169 if (task.getStack() != null) {
2170 // Return the bounds from window manager since it will be adjusted for various
2171 // things like the presense of a docked stack for tasks that aren't resizeable.
2172 task.getWindowContainerBounds(rect);
2173 } else {
2174 // Task isn't in window manager yet since it isn't associated with a stack.
2175 // Return the persist value from activity manager
2176 if (!task.matchParentBounds()) {
2177 rect.set(task.getBounds());
2178 } else if (task.mLastNonFullscreenBounds != null) {
2179 rect.set(task.mLastNonFullscreenBounds);
2180 }
2181 }
2182 }
2183 } finally {
2184 Binder.restoreCallingIdentity(ident);
2185 }
2186 return rect;
2187 }
2188
2189 @Override
2190 public ActivityManager.TaskDescription getTaskDescription(int id) {
2191 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002192 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002193 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002194 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2196 if (tr != null) {
2197 return tr.lastTaskDescription;
2198 }
2199 }
2200 return null;
2201 }
2202
2203 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002204 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2205 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2206 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2207 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2208 return;
2209 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002211 synchronized (mGlobalLock) {
2212 final long ident = Binder.clearCallingIdentity();
2213 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002214 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002215 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002216 if (task == null) {
2217 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2218 return;
2219 }
2220
2221 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2222 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2223
2224 if (!task.isActivityTypeStandardOrUndefined()) {
2225 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2226 + " non-standard task " + taskId + " to windowing mode="
2227 + windowingMode);
2228 }
2229
2230 final ActivityStack stack = task.getStack();
2231 if (toTop) {
2232 stack.moveToFront("setTaskWindowingMode", task);
2233 }
2234 stack.setWindowingMode(windowingMode);
2235 } finally {
2236 Binder.restoreCallingIdentity(ident);
2237 }
2238 }
2239 }
2240
2241 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002242 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 ActivityRecord r = getCallingRecordLocked(token);
2245 return r != null ? r.info.packageName : null;
2246 }
2247 }
2248
2249 @Override
2250 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002251 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002252 ActivityRecord r = getCallingRecordLocked(token);
2253 return r != null ? r.intent.getComponent() : null;
2254 }
2255 }
2256
2257 private ActivityRecord getCallingRecordLocked(IBinder token) {
2258 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2259 if (r == null) {
2260 return null;
2261 }
2262 return r.resultTo;
2263 }
2264
2265 @Override
2266 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002267 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002268
2269 synchronized (mGlobalLock) {
2270 final long origId = Binder.clearCallingIdentity();
2271 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002272 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 } finally {
2274 Binder.restoreCallingIdentity(origId);
2275 }
2276 }
2277 }
2278
2279 /**
2280 * TODO: Add mController hook
2281 */
2282 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002283 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2284 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286
2287 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2288 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002289 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2290 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 }
2292 }
2293
Ricky Waiaca8a772019-04-04 16:01:06 +01002294 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2295 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002296 boolean fromRecents) {
2297
Ricky Waiaca8a772019-04-04 16:01:06 +01002298 final int callingPid = Binder.getCallingPid();
2299 final int callingUid = Binder.getCallingUid();
2300 if (!isSameApp(callingUid, callingPackage)) {
2301 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2302 + Binder.getCallingPid() + " as package " + callingPackage;
2303 Slog.w(TAG, msg);
2304 throw new SecurityException(msg);
2305 }
2306 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 SafeActivityOptions.abort(options);
2308 return;
2309 }
2310 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002311 WindowProcessController callerApp = null;
2312 if (appThread != null) {
2313 callerApp = getProcessController(appThread);
2314 }
2315 final ActivityStarter starter = getActivityStartController().obtainStarter(
2316 null /* intent */, "moveTaskToFront");
2317 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2318 -1, callerApp, null, false, null)) {
2319 boolean abort = !isBackgroundActivityStartsEnabled();
2320 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2321 if (abort) {
2322 return;
2323 }
2324 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002325 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002326 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002327 if (task == null) {
2328 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002329 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002330 return;
2331 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002332 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002333 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002334 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335 return;
2336 }
2337 ActivityOptions realOptions = options != null
2338 ? options.getOptions(mStackSupervisor)
2339 : null;
2340 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2341 false /* forceNonResizable */);
2342
2343 final ActivityRecord topActivity = task.getTopActivity();
2344 if (topActivity != null) {
2345
2346 // We are reshowing a task, use a starting window to hide the initial draw delay
2347 // so the transition can start earlier.
2348 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2349 true /* taskSwitch */, fromRecents);
2350 }
2351 } finally {
2352 Binder.restoreCallingIdentity(origId);
2353 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 }
2355
Ricky Waiaca8a772019-04-04 16:01:06 +01002356 /**
2357 * Return true if callingUid is system, or packageName belongs to that callingUid.
2358 */
2359 boolean isSameApp(int callingUid, @Nullable String packageName) {
2360 try {
2361 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2362 if (packageName == null) {
2363 return false;
2364 }
2365 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2366 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2367 UserHandle.getUserId(callingUid));
2368 return UserHandle.isSameApp(callingUid, uid);
2369 }
2370 } catch (RemoteException e) {
2371 // Should not happen
2372 }
2373 return true;
2374 }
2375
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002376 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2377 int callingPid, int callingUid, String name) {
2378 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2379 return true;
2380 }
2381
2382 if (getRecentTasks().isCallerRecents(sourceUid)) {
2383 return true;
2384 }
2385
2386 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2387 if (perm == PackageManager.PERMISSION_GRANTED) {
2388 return true;
2389 }
2390 if (checkAllowAppSwitchUid(sourceUid)) {
2391 return true;
2392 }
2393
2394 // If the actual IPC caller is different from the logical source, then
2395 // also see if they are allowed to control app switches.
2396 if (callingUid != -1 && callingUid != sourceUid) {
2397 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2398 if (perm == PackageManager.PERMISSION_GRANTED) {
2399 return true;
2400 }
2401 if (checkAllowAppSwitchUid(callingUid)) {
2402 return true;
2403 }
2404 }
2405
2406 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2407 return false;
2408 }
2409
2410 private boolean checkAllowAppSwitchUid(int uid) {
2411 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2412 if (types != null) {
2413 for (int i = types.size() - 1; i >= 0; i--) {
2414 if (types.valueAt(i).intValue() == uid) {
2415 return true;
2416 }
2417 }
2418 }
2419 return false;
2420 }
2421
2422 @Override
2423 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2424 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2425 "setActivityController()");
2426 synchronized (mGlobalLock) {
2427 mController = controller;
2428 mControllerIsAMonkey = imAMonkey;
2429 Watchdog.getInstance().setActivityController(controller);
2430 }
2431 }
2432
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002433 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002434 synchronized (mGlobalLock) {
2435 return mController != null && mControllerIsAMonkey;
2436 }
2437 }
2438
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002439 @Override
2440 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2441 synchronized (mGlobalLock) {
2442 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2443 }
2444 }
2445
2446 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002447 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2448 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2449 }
2450
2451 @Override
2452 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2453 @WindowConfiguration.ActivityType int ignoreActivityType,
2454 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2455 final int callingUid = Binder.getCallingUid();
2456 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2457
2458 synchronized (mGlobalLock) {
2459 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2460
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002461 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002462 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002463 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002464 ignoreWindowingMode, callingUid, allowed);
2465 }
2466
2467 return list;
2468 }
2469
2470 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002471 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2472 synchronized (mGlobalLock) {
2473 final long origId = Binder.clearCallingIdentity();
2474 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2475 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002476 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002477 }
2478 Binder.restoreCallingIdentity(origId);
2479 }
2480 }
2481
2482 @Override
2483 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002484 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002485 ActivityStack stack = ActivityRecord.getStackLocked(token);
2486 if (stack != null) {
2487 return stack.willActivityBeVisibleLocked(token);
2488 }
2489 return false;
2490 }
2491 }
2492
2493 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002494 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002495 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002496 synchronized (mGlobalLock) {
2497 final long ident = Binder.clearCallingIdentity();
2498 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002499 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002500 if (task == null) {
2501 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2502 return;
2503 }
2504
2505 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2506 + " to stackId=" + stackId + " toTop=" + toTop);
2507
Wale Ogunwaled32da472018-11-16 07:19:28 -08002508 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002509 if (stack == null) {
2510 throw new IllegalStateException(
2511 "moveTaskToStack: No stack for stackId=" + stackId);
2512 }
2513 if (!stack.isActivityTypeStandardOrUndefined()) {
2514 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2515 + taskId + " to stack " + stackId);
2516 }
2517 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002518 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2520 }
2521 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2522 "moveTaskToStack");
2523 } finally {
2524 Binder.restoreCallingIdentity(ident);
2525 }
2526 }
2527 }
2528
2529 @Override
2530 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2531 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002532 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002533
2534 final long ident = Binder.clearCallingIdentity();
2535 try {
2536 synchronized (mGlobalLock) {
2537 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002538 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 if (stack == null) {
2540 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2541 return;
2542 }
2543 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2544 throw new IllegalArgumentException("Stack: " + stackId
2545 + " doesn't support animated resize.");
2546 }
2547 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2548 animationDuration, false /* fromFullscreen */);
2549 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002550 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 if (stack == null) {
2552 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2553 return;
2554 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002555 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002556 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2557 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2558 }
2559 }
2560 } finally {
2561 Binder.restoreCallingIdentity(ident);
2562 }
2563 }
2564
wilsonshih5c4cf522019-01-25 09:03:47 +08002565 @Override
2566 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2567 int animationDuration) {
2568 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2569
2570 final long ident = Binder.clearCallingIdentity();
2571 try {
2572 synchronized (mGlobalLock) {
2573 if (xOffset == 0 && yOffset == 0) {
2574 return;
2575 }
2576 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2577 if (stack == null) {
2578 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2579 return;
2580 }
2581 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2582 throw new IllegalArgumentException("Stack: " + stackId
2583 + " doesn't support animated resize.");
2584 }
2585 final Rect destBounds = new Rect();
2586 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002587 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002588 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2589 return;
2590 }
2591 destBounds.offset(xOffset, yOffset);
2592 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2593 animationDuration, false /* fromFullscreen */);
2594 }
2595 } finally {
2596 Binder.restoreCallingIdentity(ident);
2597 }
2598 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599 /**
2600 * Moves the specified task to the primary-split-screen stack.
2601 *
2602 * @param taskId Id of task to move.
2603 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2604 * exist already. See
2605 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2606 * and
2607 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2608 * @param toTop If the task and stack should be moved to the top.
2609 * @param animate Whether we should play an animation for the moving the task.
2610 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2611 * stack. Pass {@code null} to use default bounds.
2612 * @param showRecents If the recents activity should be shown on the other side of the task
2613 * going into split-screen mode.
2614 */
2615 @Override
2616 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2617 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002618 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 "setTaskWindowingModeSplitScreenPrimary()");
2620 synchronized (mGlobalLock) {
2621 final long ident = Binder.clearCallingIdentity();
2622 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002623 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002624 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002625 if (task == null) {
2626 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2627 return false;
2628 }
2629 if (DEBUG_STACK) Slog.d(TAG_STACK,
2630 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2631 + " to createMode=" + createMode + " toTop=" + toTop);
2632 if (!task.isActivityTypeStandardOrUndefined()) {
2633 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2634 + " non-standard task " + taskId + " to split-screen windowing mode");
2635 }
2636
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002637 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 final int windowingMode = task.getWindowingMode();
2639 final ActivityStack stack = task.getStack();
2640 if (toTop) {
2641 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2642 }
2643 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002644 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2645 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002646 return windowingMode != task.getWindowingMode();
2647 } finally {
2648 Binder.restoreCallingIdentity(ident);
2649 }
2650 }
2651 }
2652
2653 /**
2654 * Removes stacks in the input windowing modes from the system if they are of activity type
2655 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2656 */
2657 @Override
2658 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002659 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002660 "removeStacksInWindowingModes()");
2661
2662 synchronized (mGlobalLock) {
2663 final long ident = Binder.clearCallingIdentity();
2664 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002665 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002666 } finally {
2667 Binder.restoreCallingIdentity(ident);
2668 }
2669 }
2670 }
2671
2672 @Override
2673 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002674 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002675 "removeStacksWithActivityTypes()");
2676
2677 synchronized (mGlobalLock) {
2678 final long ident = Binder.clearCallingIdentity();
2679 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002680 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
2685 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002686
2687 @Override
2688 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2689 int userId) {
2690 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002691 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2692 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002693 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002694 final boolean detailed = checkGetTasksPermission(
2695 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2696 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002697 == PackageManager.PERMISSION_GRANTED;
2698
2699 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002700 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 callingUid);
2702 }
2703 }
2704
2705 @Override
2706 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002707 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002708 long ident = Binder.clearCallingIdentity();
2709 try {
2710 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002711 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002712 }
2713 } finally {
2714 Binder.restoreCallingIdentity(ident);
2715 }
2716 }
2717
2718 @Override
2719 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002720 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 long ident = Binder.clearCallingIdentity();
2722 try {
2723 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002724 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002725 }
2726 } finally {
2727 Binder.restoreCallingIdentity(ident);
2728 }
2729 }
2730
2731 @Override
2732 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734 final long callingUid = Binder.getCallingUid();
2735 final long origId = Binder.clearCallingIdentity();
2736 try {
2737 synchronized (mGlobalLock) {
2738 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002739 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2741 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2742 }
2743 } finally {
2744 Binder.restoreCallingIdentity(origId);
2745 }
2746 }
2747
2748 @Override
2749 public void startLockTaskModeByToken(IBinder token) {
2750 synchronized (mGlobalLock) {
2751 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2752 if (r == null) {
2753 return;
2754 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002755 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 }
2757 }
2758
2759 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002760 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002761 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 // This makes inner call to look as if it was initiated by system.
2763 long ident = Binder.clearCallingIdentity();
2764 try {
2765 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002767 MATCH_TASK_IN_STACKS_ONLY);
2768 if (task == null) {
2769 return;
2770 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771
2772 // When starting lock task mode the stack must be in front and focused
2773 task.getStack().moveToFront("startSystemLockTaskMode");
2774 startLockTaskModeLocked(task, true /* isSystemCaller */);
2775 }
2776 } finally {
2777 Binder.restoreCallingIdentity(ident);
2778 }
2779 }
2780
2781 @Override
2782 public void stopLockTaskModeByToken(IBinder token) {
2783 synchronized (mGlobalLock) {
2784 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2785 if (r == null) {
2786 return;
2787 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002788 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 }
2790 }
2791
2792 /**
2793 * This API should be called by SystemUI only when user perform certain action to dismiss
2794 * lock task mode. We should only dismiss pinned lock task mode in this case.
2795 */
2796 @Override
2797 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002798 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2800 }
2801
2802 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2803 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2804 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2805 return;
2806 }
2807
Wale Ogunwaled32da472018-11-16 07:19:28 -08002808 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 if (stack == null || task != stack.topTask()) {
2810 throw new IllegalArgumentException("Invalid task, not in foreground");
2811 }
2812
2813 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2814 // system or a specific app.
2815 // * System-initiated requests will only start the pinned mode (screen pinning)
2816 // * App-initiated requests
2817 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2818 // - will start the pinned mode, otherwise
2819 final int callingUid = Binder.getCallingUid();
2820 long ident = Binder.clearCallingIdentity();
2821 try {
2822 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002823 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002825 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 } finally {
2827 Binder.restoreCallingIdentity(ident);
2828 }
2829 }
2830
2831 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2832 final int callingUid = Binder.getCallingUid();
2833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002836 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 }
2838 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2839 // task and jumping straight into a call in the case of emergency call back.
2840 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2841 if (tm != null) {
2842 tm.showInCallScreen(false);
2843 }
2844 } finally {
2845 Binder.restoreCallingIdentity(ident);
2846 }
2847 }
2848
2849 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002850 public void updateLockTaskPackages(int userId, String[] packages) {
2851 final int callingUid = Binder.getCallingUid();
2852 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2853 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2854 "updateLockTaskPackages()");
2855 }
2856 synchronized (this) {
2857 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2858 + Arrays.toString(packages));
2859 getLockTaskController().updateLockTaskPackages(userId, packages);
2860 }
2861 }
2862
2863 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 public boolean isInLockTaskMode() {
2865 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2866 }
2867
2868 @Override
2869 public int getLockTaskModeState() {
2870 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002871 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002872 }
2873 }
2874
2875 @Override
2876 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2877 synchronized (mGlobalLock) {
2878 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2879 if (r != null) {
2880 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002881 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002883 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 }
2885 }
2886 }
2887
2888 @Override
2889 public Bundle getActivityOptions(IBinder token) {
2890 final long origId = Binder.clearCallingIdentity();
2891 try {
2892 synchronized (mGlobalLock) {
2893 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2894 if (r != null) {
2895 final ActivityOptions activityOptions = r.takeOptionsLocked();
2896 return activityOptions == null ? null : activityOptions.toBundle();
2897 }
2898 return null;
2899 }
2900 } finally {
2901 Binder.restoreCallingIdentity(origId);
2902 }
2903 }
2904
2905 @Override
2906 public List<IBinder> getAppTasks(String callingPackage) {
2907 int callingUid = Binder.getCallingUid();
2908 long ident = Binder.clearCallingIdentity();
2909 try {
2910 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002911 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 }
2913 } finally {
2914 Binder.restoreCallingIdentity(ident);
2915 }
2916 }
2917
2918 @Override
2919 public void finishVoiceTask(IVoiceInteractionSession session) {
2920 synchronized (mGlobalLock) {
2921 final long origId = Binder.clearCallingIdentity();
2922 try {
2923 // TODO: VI Consider treating local voice interactions and voice tasks
2924 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002925 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 } finally {
2927 Binder.restoreCallingIdentity(origId);
2928 }
2929 }
2930
2931 }
2932
2933 @Override
2934 public boolean isTopOfTask(IBinder token) {
2935 synchronized (mGlobalLock) {
2936 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002937 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 }
2939 }
2940
2941 @Override
2942 public void notifyLaunchTaskBehindComplete(IBinder token) {
2943 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2944 }
2945
2946 @Override
2947 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002948 mH.post(() -> {
2949 synchronized (mGlobalLock) {
2950 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002951 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002952 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002953 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002954 } catch (RemoteException e) {
2955 }
2956 }
2957 }
2958
2959 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 }
2961
2962 /** Called from an app when assist data is ready. */
2963 @Override
2964 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2965 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002966 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002967 synchronized (pae) {
2968 pae.result = extras;
2969 pae.structure = structure;
2970 pae.content = content;
2971 if (referrer != null) {
2972 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2973 }
2974 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002975 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002976 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2977 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 structure.setHomeActivity(pae.isHome);
2979 }
2980 pae.haveResult = true;
2981 pae.notifyAll();
2982 if (pae.intent == null && pae.receiver == null) {
2983 // Caller is just waiting for the result.
2984 return;
2985 }
2986 }
2987 // We are now ready to launch the assist activity.
2988 IAssistDataReceiver sendReceiver = null;
2989 Bundle sendBundle = null;
2990 synchronized (mGlobalLock) {
2991 buildAssistBundleLocked(pae, extras);
2992 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002993 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 if (!exists) {
2995 // Timed out.
2996 return;
2997 }
2998
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002999 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 // Caller wants result sent back to them.
3001 sendBundle = new Bundle();
3002 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3003 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3004 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3005 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3006 }
3007 }
3008 if (sendReceiver != null) {
3009 try {
3010 sendReceiver.onHandleAssistData(sendBundle);
3011 } catch (RemoteException e) {
3012 }
3013 return;
3014 }
3015
3016 final long ident = Binder.clearCallingIdentity();
3017 try {
3018 if (TextUtils.equals(pae.intent.getAction(),
3019 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3020 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003021
3022 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 } else {
3024 pae.intent.replaceExtras(pae.extras);
3025 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3026 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3027 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003028 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029
3030 try {
3031 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3032 } catch (ActivityNotFoundException e) {
3033 Slog.w(TAG, "No activity to handle assist action.", e);
3034 }
3035 }
3036 } finally {
3037 Binder.restoreCallingIdentity(ident);
3038 }
3039 }
3040
Marvin Ramin830d4e32019-03-12 13:16:58 +01003041 /**
3042 * Workaround for historical API which starts the Assist service with a non-foreground
3043 * {@code startService()} call.
3044 */
3045 private void startVoiceInteractionServiceAsUser(
3046 Intent intent, int userHandle, String reason) {
3047 // Resolve the intent to find out which package we need to whitelist.
3048 ResolveInfo resolveInfo =
3049 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3050 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3051 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3052 return;
3053 }
3054 intent.setPackage(resolveInfo.serviceInfo.packageName);
3055
3056 // Whitelist background services temporarily.
3057 LocalServices.getService(DeviceIdleController.LocalService.class)
3058 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3059 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3060
3061 // Finally, try to start the service.
3062 try {
3063 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3064 } catch (RuntimeException e) {
3065 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3066 }
3067 }
3068
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 @Override
3070 public int addAppTask(IBinder activityToken, Intent intent,
3071 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3072 final int callingUid = Binder.getCallingUid();
3073 final long callingIdent = Binder.clearCallingIdentity();
3074
3075 try {
3076 synchronized (mGlobalLock) {
3077 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3078 if (r == null) {
3079 throw new IllegalArgumentException("Activity does not exist; token="
3080 + activityToken);
3081 }
3082 ComponentName comp = intent.getComponent();
3083 if (comp == null) {
3084 throw new IllegalArgumentException("Intent " + intent
3085 + " must specify explicit component");
3086 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003087 if (thumbnail.getWidth() != mThumbnailWidth
3088 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 throw new IllegalArgumentException("Bad thumbnail size: got "
3090 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003091 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 }
3093 if (intent.getSelector() != null) {
3094 intent.setSelector(null);
3095 }
3096 if (intent.getSourceBounds() != null) {
3097 intent.setSourceBounds(null);
3098 }
3099 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3100 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3101 // The caller has added this as an auto-remove task... that makes no
3102 // sense, so turn off auto-remove.
3103 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3104 }
3105 }
3106 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3107 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3108 if (ainfo.applicationInfo.uid != callingUid) {
3109 throw new SecurityException(
3110 "Can't add task for another application: target uid="
3111 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3112 }
3113
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003114 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003116 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003118 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 // The app has too many tasks already and we can't add any more
3120 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3121 return INVALID_TASK_ID;
3122 }
3123 task.lastTaskDescription.copyFrom(description);
3124
3125 // TODO: Send the thumbnail to WM to store it.
3126
3127 return task.taskId;
3128 }
3129 } finally {
3130 Binder.restoreCallingIdentity(callingIdent);
3131 }
3132 }
3133
3134 @Override
3135 public Point getAppTaskThumbnailSize() {
3136 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003137 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 }
3139 }
3140
3141 @Override
3142 public void setTaskResizeable(int taskId, int resizeableMode) {
3143 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003144 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3146 if (task == null) {
3147 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3148 return;
3149 }
3150 task.setResizeMode(resizeableMode);
3151 }
3152 }
3153
3154 @Override
3155 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003156 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 long ident = Binder.clearCallingIdentity();
3158 try {
3159 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003160 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003161 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 if (task == null) {
3163 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3164 return;
3165 }
3166 // Place the task in the right stack if it isn't there already based on
3167 // the requested bounds.
3168 // The stack transition logic is:
3169 // - a null bounds on a freeform task moves that task to fullscreen
3170 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3171 // that task to freeform
3172 // - otherwise the task is not moved
3173 ActivityStack stack = task.getStack();
3174 if (!task.getWindowConfiguration().canResizeTask()) {
3175 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3176 }
3177 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3178 stack = stack.getDisplay().getOrCreateStack(
3179 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3180 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3181 stack = stack.getDisplay().getOrCreateStack(
3182 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3183 }
3184
3185 // Reparent the task to the right stack if necessary
3186 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3187 if (stack != task.getStack()) {
3188 // Defer resume until the task is resized below
3189 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3190 DEFER_RESUME, "resizeTask");
3191 preserveWindow = false;
3192 }
3193
3194 // After reparenting (which only resizes the task to the stack bounds), resize the
3195 // task to the actual bounds provided
3196 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3197 }
3198 } finally {
3199 Binder.restoreCallingIdentity(ident);
3200 }
3201 }
3202
3203 @Override
3204 public boolean releaseActivityInstance(IBinder token) {
3205 synchronized (mGlobalLock) {
3206 final long origId = Binder.clearCallingIdentity();
3207 try {
3208 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3209 if (r == null) {
3210 return false;
3211 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003212 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 } finally {
3214 Binder.restoreCallingIdentity(origId);
3215 }
3216 }
3217 }
3218
3219 @Override
3220 public void releaseSomeActivities(IApplicationThread appInt) {
3221 synchronized (mGlobalLock) {
3222 final long origId = Binder.clearCallingIdentity();
3223 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003224 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003225 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 } finally {
3227 Binder.restoreCallingIdentity(origId);
3228 }
3229 }
3230 }
3231
3232 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003233 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003234 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003235 != PackageManager.PERMISSION_GRANTED) {
3236 throw new SecurityException("Requires permission "
3237 + android.Manifest.permission.DEVICE_POWER);
3238 }
3239
3240 synchronized (mGlobalLock) {
3241 long ident = Binder.clearCallingIdentity();
3242 if (mKeyguardShown != keyguardShowing) {
3243 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003244 final Message msg = PooledLambda.obtainMessage(
3245 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3246 keyguardShowing);
3247 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003248 }
3249 try {
wilsonshih177261f2019-02-22 12:02:18 +08003250 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 } finally {
3252 Binder.restoreCallingIdentity(ident);
3253 }
3254 }
3255
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003256 mH.post(() -> {
3257 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3258 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3259 }
3260 });
3261 }
3262
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003263 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003264 mH.post(() -> {
3265 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3266 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3267 }
3268 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 }
3270
3271 @Override
3272 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003273 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3274 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275
3276 final File passedIconFile = new File(filePath);
3277 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3278 passedIconFile.getName());
3279 if (!legitIconFile.getPath().equals(filePath)
3280 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3281 throw new IllegalArgumentException("Bad file path: " + filePath
3282 + " passed for userId " + userId);
3283 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003284 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 }
3286
3287 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003288 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3290 final ActivityOptions activityOptions = safeOptions != null
3291 ? safeOptions.getOptions(mStackSupervisor)
3292 : null;
3293 if (activityOptions == null
3294 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3295 || activityOptions.getCustomInPlaceResId() == 0) {
3296 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3297 "with valid animation");
3298 }
lumark588a3e82018-07-20 18:53:54 +08003299 // Get top display of front most application.
3300 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3301 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003302 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3303 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3304 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003305 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003306 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003307 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 }
3309
3310 @Override
3311 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003312 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 synchronized (mGlobalLock) {
3314 final long ident = Binder.clearCallingIdentity();
3315 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003316 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 if (stack == null) {
3318 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3319 return;
3320 }
3321 if (!stack.isActivityTypeStandardOrUndefined()) {
3322 throw new IllegalArgumentException(
3323 "Removing non-standard stack is not allowed.");
3324 }
3325 mStackSupervisor.removeStack(stack);
3326 } finally {
3327 Binder.restoreCallingIdentity(ident);
3328 }
3329 }
3330 }
3331
3332 @Override
3333 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003334 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335
3336 synchronized (mGlobalLock) {
3337 final long ident = Binder.clearCallingIdentity();
3338 try {
3339 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3340 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003341 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003342 } finally {
3343 Binder.restoreCallingIdentity(ident);
3344 }
3345 }
3346 }
3347
3348 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003349 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 synchronized (mGlobalLock) {
3351 long ident = Binder.clearCallingIdentity();
3352 try {
3353 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3354 if (r == null) {
3355 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003356 "toggleFreeformWindowingMode: No activity record matching token="
3357 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
3359
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003360 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003361 if (stack == null) {
3362 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3363 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003364 }
3365
Yunfan Chend967af82019-01-17 18:30:18 +09003366 if (!stack.inFreeformWindowingMode()
3367 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3368 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3369 + "toggle between fullscreen and freeform.");
3370 }
3371
3372 if (stack.inFreeformWindowingMode()) {
3373 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3374 } else {
3375 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3376 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 } finally {
3378 Binder.restoreCallingIdentity(ident);
3379 }
3380 }
3381 }
3382
3383 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3384 @Override
3385 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003386 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003388 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 }
3390
3391 /** Unregister a task stack listener so that it stops receiving callbacks. */
3392 @Override
3393 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003394 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003396 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 }
3398
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 @Override
3400 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3401 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3402 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3403 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3404 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3405 }
3406
3407 @Override
3408 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3409 IBinder activityToken, int flags) {
3410 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3411 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3412 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3413 }
3414
3415 @Override
3416 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3417 Bundle args) {
3418 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3419 true /* focused */, true /* newSessionId */, userHandle, args,
3420 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3421 }
3422
3423 @Override
3424 public Bundle getAssistContextExtras(int requestType) {
3425 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3426 null, null, true /* focused */, true /* newSessionId */,
3427 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3428 if (pae == null) {
3429 return null;
3430 }
3431 synchronized (pae) {
3432 while (!pae.haveResult) {
3433 try {
3434 pae.wait();
3435 } catch (InterruptedException e) {
3436 }
3437 }
3438 }
3439 synchronized (mGlobalLock) {
3440 buildAssistBundleLocked(pae, pae.result);
3441 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003442 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 }
3444 return pae.extras;
3445 }
3446
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003447 /**
3448 * Binder IPC calls go through the public entry point.
3449 * This can be called with or without the global lock held.
3450 */
3451 private static int checkCallingPermission(String permission) {
3452 return checkPermission(
3453 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3454 }
3455
3456 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003457 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003458 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3459 mAmInternal.enforceCallingPermission(permission, func);
3460 }
3461 }
3462
3463 @VisibleForTesting
3464 int checkGetTasksPermission(String permission, int pid, int uid) {
3465 return checkPermission(permission, pid, uid);
3466 }
3467
3468 static int checkPermission(String permission, int pid, int uid) {
3469 if (permission == null) {
3470 return PackageManager.PERMISSION_DENIED;
3471 }
3472 return checkComponentPermission(permission, pid, uid, -1, true);
3473 }
3474
Wale Ogunwale214f3482018-10-04 11:00:47 -07003475 public static int checkComponentPermission(String permission, int pid, int uid,
3476 int owningUid, boolean exported) {
3477 return ActivityManagerService.checkComponentPermission(
3478 permission, pid, uid, owningUid, exported);
3479 }
3480
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3482 if (getRecentTasks().isCallerRecents(callingUid)) {
3483 // Always allow the recents component to get tasks
3484 return true;
3485 }
3486
3487 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3488 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3489 if (!allowed) {
3490 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3491 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3492 // Temporary compatibility: some existing apps on the system image may
3493 // still be requesting the old permission and not switched to the new
3494 // one; if so, we'll still allow them full access. This means we need
3495 // to see if they are holding the old permission and are a system app.
3496 try {
3497 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3498 allowed = true;
3499 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3500 + " is using old GET_TASKS but privileged; allowing");
3501 }
3502 } catch (RemoteException e) {
3503 }
3504 }
3505 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3506 + " does not hold REAL_GET_TASKS; limiting output");
3507 }
3508 return allowed;
3509 }
3510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3512 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3513 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3514 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003515 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003516 "enqueueAssistContext()");
3517
3518 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003519 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003520 if (activity == null) {
3521 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3522 return null;
3523 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003524 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3526 return null;
3527 }
3528 if (focused) {
3529 if (activityToken != null) {
3530 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3531 if (activity != caller) {
3532 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3533 + " is not current top " + activity);
3534 return null;
3535 }
3536 }
3537 } else {
3538 activity = ActivityRecord.forTokenLocked(activityToken);
3539 if (activity == null) {
3540 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3541 + " couldn't be found");
3542 return null;
3543 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003544 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3546 return null;
3547 }
3548 }
3549
3550 PendingAssistExtras pae;
3551 Bundle extras = new Bundle();
3552 if (args != null) {
3553 extras.putAll(args);
3554 }
3555 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003556 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557
3558 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3559 userHandle);
3560 pae.isHome = activity.isActivityTypeHome();
3561
3562 // Increment the sessionId if necessary
3563 if (newSessionId) {
3564 mViSessionId++;
3565 }
3566 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003567 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3568 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003569 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003570 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 } catch (RemoteException e) {
3572 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3573 return null;
3574 }
3575 return pae;
3576 }
3577 }
3578
3579 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3580 if (result != null) {
3581 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3582 }
3583 if (pae.hint != null) {
3584 pae.extras.putBoolean(pae.hint, true);
3585 }
3586 }
3587
3588 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3589 IAssistDataReceiver receiver;
3590 synchronized (mGlobalLock) {
3591 mPendingAssistExtras.remove(pae);
3592 receiver = pae.receiver;
3593 }
3594 if (receiver != null) {
3595 // Caller wants result sent back to them.
3596 Bundle sendBundle = new Bundle();
3597 // At least return the receiver extras
3598 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3599 try {
3600 pae.receiver.onHandleAssistData(sendBundle);
3601 } catch (RemoteException e) {
3602 }
3603 }
3604 }
3605
3606 public class PendingAssistExtras extends Binder implements Runnable {
3607 public final ActivityRecord activity;
3608 public boolean isHome;
3609 public final Bundle extras;
3610 public final Intent intent;
3611 public final String hint;
3612 public final IAssistDataReceiver receiver;
3613 public final int userHandle;
3614 public boolean haveResult = false;
3615 public Bundle result = null;
3616 public AssistStructure structure = null;
3617 public AssistContent content = null;
3618 public Bundle receiverExtras;
3619
3620 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3621 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3622 int _userHandle) {
3623 activity = _activity;
3624 extras = _extras;
3625 intent = _intent;
3626 hint = _hint;
3627 receiver = _receiver;
3628 receiverExtras = _receiverExtras;
3629 userHandle = _userHandle;
3630 }
3631
3632 @Override
3633 public void run() {
3634 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3635 synchronized (this) {
3636 haveResult = true;
3637 notifyAll();
3638 }
3639 pendingAssistExtrasTimedOut(this);
3640 }
3641 }
3642
3643 @Override
3644 public boolean isAssistDataAllowedOnCurrentActivity() {
3645 int userId;
3646 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003647 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3649 return false;
3650 }
3651
3652 final ActivityRecord activity = focusedStack.getTopActivity();
3653 if (activity == null) {
3654 return false;
3655 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003656 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003657 }
3658 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3659 }
3660
3661 @Override
3662 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3663 long ident = Binder.clearCallingIdentity();
3664 try {
3665 synchronized (mGlobalLock) {
3666 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003667 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 if (top != caller) {
3669 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3670 + " is not current top " + top);
3671 return false;
3672 }
3673 if (!top.nowVisible) {
3674 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3675 + " is not visible");
3676 return false;
3677 }
3678 }
3679 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3680 token);
3681 } finally {
3682 Binder.restoreCallingIdentity(ident);
3683 }
3684 }
3685
3686 @Override
3687 public boolean isRootVoiceInteraction(IBinder token) {
3688 synchronized (mGlobalLock) {
3689 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3690 if (r == null) {
3691 return false;
3692 }
3693 return r.rootVoiceInteraction;
3694 }
3695 }
3696
Wale Ogunwalef6733932018-06-27 05:14:34 -07003697 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3698 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3699 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3700 if (activityToCallback == null) return;
3701 activityToCallback.setVoiceSessionLocked(voiceSession);
3702
3703 // Inform the activity
3704 try {
3705 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3706 voiceInteractor);
3707 long token = Binder.clearCallingIdentity();
3708 try {
3709 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3710 } finally {
3711 Binder.restoreCallingIdentity(token);
3712 }
3713 // TODO: VI Should we cache the activity so that it's easier to find later
3714 // rather than scan through all the stacks and activities?
3715 } catch (RemoteException re) {
3716 activityToCallback.clearVoiceSessionLocked();
3717 // TODO: VI Should this terminate the voice session?
3718 }
3719 }
3720
3721 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3722 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3723 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3724 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3725 boolean wasRunningVoice = mRunningVoice != null;
3726 mRunningVoice = session;
3727 if (!wasRunningVoice) {
3728 mVoiceWakeLock.acquire();
3729 updateSleepIfNeededLocked();
3730 }
3731 }
3732 }
3733
3734 void finishRunningVoiceLocked() {
3735 if (mRunningVoice != null) {
3736 mRunningVoice = null;
3737 mVoiceWakeLock.release();
3738 updateSleepIfNeededLocked();
3739 }
3740 }
3741
3742 @Override
3743 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3744 synchronized (mGlobalLock) {
3745 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3746 if (keepAwake) {
3747 mVoiceWakeLock.acquire();
3748 } else {
3749 mVoiceWakeLock.release();
3750 }
3751 }
3752 }
3753 }
3754
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 @Override
3756 public ComponentName getActivityClassForToken(IBinder token) {
3757 synchronized (mGlobalLock) {
3758 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3759 if (r == null) {
3760 return null;
3761 }
3762 return r.intent.getComponent();
3763 }
3764 }
3765
3766 @Override
3767 public String getPackageForToken(IBinder token) {
3768 synchronized (mGlobalLock) {
3769 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3770 if (r == null) {
3771 return null;
3772 }
3773 return r.packageName;
3774 }
3775 }
3776
3777 @Override
3778 public void showLockTaskEscapeMessage(IBinder token) {
3779 synchronized (mGlobalLock) {
3780 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3781 if (r == null) {
3782 return;
3783 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003784 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 }
3786 }
3787
3788 @Override
3789 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003790 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 final long token = Binder.clearCallingIdentity();
3792 try {
3793 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003794 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 }
3796 } finally {
3797 Binder.restoreCallingIdentity(token);
3798 }
3799 }
3800
3801 /**
3802 * Try to place task to provided position. The final position might be different depending on
3803 * current user and stacks state. The task will be moved to target stack if it's currently in
3804 * different stack.
3805 */
3806 @Override
3807 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003808 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003809 synchronized (mGlobalLock) {
3810 long ident = Binder.clearCallingIdentity();
3811 try {
3812 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3813 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003814 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003815 if (task == null) {
3816 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3817 + taskId);
3818 }
3819
Wale Ogunwaled32da472018-11-16 07:19:28 -08003820 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821
3822 if (stack == null) {
3823 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3824 + stackId);
3825 }
3826 if (!stack.isActivityTypeStandardOrUndefined()) {
3827 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3828 + " the position of task " + taskId + " in/to non-standard stack");
3829 }
3830
3831 // TODO: Have the callers of this API call a separate reparent method if that is
3832 // what they intended to do vs. having this method also do reparenting.
3833 if (task.getStack() == stack) {
3834 // Change position in current stack.
3835 stack.positionChildAt(task, position);
3836 } else {
3837 // Reparent to new stack.
3838 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3839 !DEFER_RESUME, "positionTaskInStack");
3840 }
3841 } finally {
3842 Binder.restoreCallingIdentity(ident);
3843 }
3844 }
3845 }
3846
3847 @Override
3848 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3849 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3850 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3851 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3852 synchronized (mGlobalLock) {
3853 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3854 if (record == null) {
3855 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3856 + "found for: " + token);
3857 }
3858 record.setSizeConfigurations(horizontalSizeConfiguration,
3859 verticalSizeConfigurations, smallestSizeConfigurations);
3860 }
3861 }
3862
3863 /**
3864 * Dismisses split-screen multi-window mode.
3865 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3866 */
3867 @Override
3868 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003869 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3871 final long ident = Binder.clearCallingIdentity();
3872 try {
3873 synchronized (mGlobalLock) {
3874 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003875 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 if (stack == null) {
3877 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3878 return;
3879 }
3880
3881 if (toTop) {
3882 // Caller wants the current split-screen primary stack to be the top stack after
3883 // it goes fullscreen, so move it to the front.
3884 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003885 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003886 // In this case the current split-screen primary stack shouldn't be the top
3887 // stack after it goes fullscreen, but it current has focus, so we move the
3888 // focus to the top-most split-screen secondary stack next to it.
3889 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3890 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3891 if (otherStack != null) {
3892 otherStack.moveToFront("dismissSplitScreenMode_other");
3893 }
3894 }
3895
Evan Rosky10475742018-09-05 19:02:48 -07003896 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003897 }
3898 } finally {
3899 Binder.restoreCallingIdentity(ident);
3900 }
3901 }
3902
3903 /**
3904 * Dismisses Pip
3905 * @param animate True if the dismissal should be animated.
3906 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3907 * default animation duration should be used.
3908 */
3909 @Override
3910 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003911 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 final long ident = Binder.clearCallingIdentity();
3913 try {
3914 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003915 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003916 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 if (stack == null) {
3918 Slog.w(TAG, "dismissPip: pinned stack not found.");
3919 return;
3920 }
3921 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3922 throw new IllegalArgumentException("Stack: " + stack
3923 + " doesn't support animated resize.");
3924 }
3925 if (animate) {
3926 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3927 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3928 } else {
3929 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3930 }
3931 }
3932 } finally {
3933 Binder.restoreCallingIdentity(ident);
3934 }
3935 }
3936
3937 @Override
3938 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003939 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 synchronized (mGlobalLock) {
3941 mSuppressResizeConfigChanges = suppress;
3942 }
3943 }
3944
3945 /**
3946 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3947 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3948 * activity and clearing the task at the same time.
3949 */
3950 @Override
3951 // TODO: API should just be about changing windowing modes...
3952 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003953 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 "moveTasksToFullscreenStack()");
3955 synchronized (mGlobalLock) {
3956 final long origId = Binder.clearCallingIdentity();
3957 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003958 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 if (stack != null){
3960 if (!stack.isActivityTypeStandardOrUndefined()) {
3961 throw new IllegalArgumentException(
3962 "You can't move tasks from non-standard stacks.");
3963 }
3964 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(origId);
3968 }
3969 }
3970 }
3971
3972 /**
3973 * Moves the top activity in the input stackId to the pinned stack.
3974 *
3975 * @param stackId Id of stack to move the top activity to pinned stack.
3976 * @param bounds Bounds to use for pinned stack.
3977 *
3978 * @return True if the top activity of the input stack was successfully moved to the pinned
3979 * stack.
3980 */
3981 @Override
3982 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003983 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 "moveTopActivityToPinnedStack()");
3985 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3988 + "Device doesn't support picture-in-picture mode");
3989 }
3990
3991 long ident = Binder.clearCallingIdentity();
3992 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003993 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003994 } finally {
3995 Binder.restoreCallingIdentity(ident);
3996 }
3997 }
3998 }
3999
4000 @Override
4001 public boolean isInMultiWindowMode(IBinder token) {
4002 final long origId = Binder.clearCallingIdentity();
4003 try {
4004 synchronized (mGlobalLock) {
4005 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4006 if (r == null) {
4007 return false;
4008 }
4009 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4010 return r.inMultiWindowMode();
4011 }
4012 } finally {
4013 Binder.restoreCallingIdentity(origId);
4014 }
4015 }
4016
4017 @Override
4018 public boolean isInPictureInPictureMode(IBinder token) {
4019 final long origId = Binder.clearCallingIdentity();
4020 try {
4021 synchronized (mGlobalLock) {
4022 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4023 }
4024 } finally {
4025 Binder.restoreCallingIdentity(origId);
4026 }
4027 }
4028
4029 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004030 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4031 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 return false;
4033 }
4034
4035 // If we are animating to fullscreen then we have already dispatched the PIP mode
4036 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004037 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4038 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004039 }
4040
4041 @Override
4042 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4043 final long origId = Binder.clearCallingIdentity();
4044 try {
4045 synchronized (mGlobalLock) {
4046 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4047 "enterPictureInPictureMode", token, params);
4048
4049 // If the activity is already in picture in picture mode, then just return early
4050 if (isInPictureInPictureMode(r)) {
4051 return true;
4052 }
4053
4054 // Activity supports picture-in-picture, now check that we can enter PiP at this
4055 // point, if it is
4056 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4057 false /* beforeStopping */)) {
4058 return false;
4059 }
4060
4061 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004062 synchronized (mGlobalLock) {
4063 // Only update the saved args from the args that are set
4064 r.pictureInPictureArgs.copyOnlySet(params);
4065 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4066 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4067 // Adjust the source bounds by the insets for the transition down
4068 final Rect sourceBounds = new Rect(
4069 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004070 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004071 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004072 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004073 stack.setPictureInPictureAspectRatio(aspectRatio);
4074 stack.setPictureInPictureActions(actions);
4075 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4076 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4077 logPictureInPictureArgs(params);
4078 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 };
4080
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004081 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 // If the keyguard is showing or occluded, then try and dismiss it before
4083 // entering picture-in-picture (this will prompt the user to authenticate if the
4084 // device is currently locked).
4085 dismissKeyguard(token, new KeyguardDismissCallback() {
4086 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004087 public void onDismissSucceeded() {
4088 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 }
4090 }, null /* message */);
4091 } else {
4092 // Enter picture in picture immediately otherwise
4093 enterPipRunnable.run();
4094 }
4095 return true;
4096 }
4097 } finally {
4098 Binder.restoreCallingIdentity(origId);
4099 }
4100 }
4101
4102 @Override
4103 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4104 final long origId = Binder.clearCallingIdentity();
4105 try {
4106 synchronized (mGlobalLock) {
4107 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4108 "setPictureInPictureParams", token, params);
4109
4110 // Only update the saved args from the args that are set
4111 r.pictureInPictureArgs.copyOnlySet(params);
4112 if (r.inPinnedWindowingMode()) {
4113 // If the activity is already in picture-in-picture, update the pinned stack now
4114 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4115 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004116 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 if (!stack.isAnimatingBoundsToFullscreen()) {
4118 stack.setPictureInPictureAspectRatio(
4119 r.pictureInPictureArgs.getAspectRatio());
4120 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4121 }
4122 }
4123 logPictureInPictureArgs(params);
4124 }
4125 } finally {
4126 Binder.restoreCallingIdentity(origId);
4127 }
4128 }
4129
4130 @Override
4131 public int getMaxNumPictureInPictureActions(IBinder token) {
4132 // Currently, this is a static constant, but later, we may change this to be dependent on
4133 // the context of the activity
4134 return 3;
4135 }
4136
4137 private void logPictureInPictureArgs(PictureInPictureParams params) {
4138 if (params.hasSetActions()) {
4139 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4140 params.getActions().size());
4141 }
4142 if (params.hasSetAspectRatio()) {
4143 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4144 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4145 MetricsLogger.action(lm);
4146 }
4147 }
4148
4149 /**
4150 * Checks the state of the system and the activity associated with the given {@param token} to
4151 * verify that picture-in-picture is supported for that activity.
4152 *
4153 * @return the activity record for the given {@param token} if all the checks pass.
4154 */
4155 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4156 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004157 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 throw new IllegalStateException(caller
4159 + ": Device doesn't support picture-in-picture mode.");
4160 }
4161
4162 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4163 if (r == null) {
4164 throw new IllegalStateException(caller
4165 + ": Can't find activity for token=" + token);
4166 }
4167
4168 if (!r.supportsPictureInPicture()) {
4169 throw new IllegalStateException(caller
4170 + ": Current activity does not support picture-in-picture.");
4171 }
4172
4173 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004174 && !mWindowManager.isValidPictureInPictureAspectRatio(
4175 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 final float minAspectRatio = mContext.getResources().getFloat(
4177 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4178 final float maxAspectRatio = mContext.getResources().getFloat(
4179 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4180 throw new IllegalArgumentException(String.format(caller
4181 + ": Aspect ratio is too extreme (must be between %f and %f).",
4182 minAspectRatio, maxAspectRatio));
4183 }
4184
4185 // Truncate the number of actions if necessary
4186 params.truncateActions(getMaxNumPictureInPictureActions(token));
4187
4188 return r;
4189 }
4190
4191 @Override
4192 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004193 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004194 synchronized (mGlobalLock) {
4195 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4196 if (r == null) {
4197 throw new IllegalArgumentException("Activity does not exist; token="
4198 + activityToken);
4199 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004200 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 }
4202 }
4203
4204 @Override
4205 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4206 Rect tempDockedTaskInsetBounds,
4207 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 long ident = Binder.clearCallingIdentity();
4210 try {
4211 synchronized (mGlobalLock) {
4212 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4213 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4214 PRESERVE_WINDOWS);
4215 }
4216 } finally {
4217 Binder.restoreCallingIdentity(ident);
4218 }
4219 }
4220
4221 @Override
4222 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004223 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 final long ident = Binder.clearCallingIdentity();
4225 try {
4226 synchronized (mGlobalLock) {
4227 mStackSupervisor.setSplitScreenResizing(resizing);
4228 }
4229 } finally {
4230 Binder.restoreCallingIdentity(ident);
4231 }
4232 }
4233
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004234 /**
4235 * Check that we have the features required for VR-related API calls, and throw an exception if
4236 * not.
4237 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004238 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004239 if (!mContext.getPackageManager().hasSystemFeature(
4240 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4241 throw new UnsupportedOperationException("VR mode not supported on this device!");
4242 }
4243 }
4244
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 @Override
4246 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248
4249 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4250
4251 ActivityRecord r;
4252 synchronized (mGlobalLock) {
4253 r = ActivityRecord.isInStackLocked(token);
4254 }
4255
4256 if (r == null) {
4257 throw new IllegalArgumentException();
4258 }
4259
4260 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004261 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 VrManagerInternal.NO_ERROR) {
4263 return err;
4264 }
4265
4266 // Clear the binder calling uid since this path may call moveToTask().
4267 final long callingId = Binder.clearCallingIdentity();
4268 try {
4269 synchronized (mGlobalLock) {
4270 r.requestedVrComponent = (enabled) ? packageName : null;
4271
4272 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004273 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004274 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 }
4276 return 0;
4277 }
4278 } finally {
4279 Binder.restoreCallingIdentity(callingId);
4280 }
4281 }
4282
4283 @Override
4284 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4285 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4286 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004287 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4289 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4290 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004291 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 || activity.voiceSession != null) {
4293 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4294 return;
4295 }
4296 if (activity.pendingVoiceInteractionStart) {
4297 Slog.w(TAG, "Pending start of voice interaction already.");
4298 return;
4299 }
4300 activity.pendingVoiceInteractionStart = true;
4301 }
4302 LocalServices.getService(VoiceInteractionManagerInternal.class)
4303 .startLocalVoiceInteraction(callingActivity, options);
4304 }
4305
4306 @Override
4307 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4308 LocalServices.getService(VoiceInteractionManagerInternal.class)
4309 .stopLocalVoiceInteraction(callingActivity);
4310 }
4311
4312 @Override
4313 public boolean supportsLocalVoiceInteraction() {
4314 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4315 .supportsLocalVoiceInteraction();
4316 }
4317
4318 /** Notifies all listeners when the pinned stack animation starts. */
4319 @Override
4320 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004321 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 }
4323
4324 /** Notifies all listeners when the pinned stack animation ends. */
4325 @Override
4326 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004327 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 }
4329
4330 @Override
4331 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 final long ident = Binder.clearCallingIdentity();
4334 try {
4335 synchronized (mGlobalLock) {
4336 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4337 }
4338 } finally {
4339 Binder.restoreCallingIdentity(ident);
4340 }
4341 }
4342
4343 @Override
4344 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346
4347 synchronized (mGlobalLock) {
4348 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004349 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004350 // Call might come when display is not yet added or has already been removed.
4351 if (DEBUG_CONFIGURATION) {
4352 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4353 + displayId);
4354 }
4355 return false;
4356 }
4357
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004358 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004360 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 }
4362
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004363 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004364 final Message msg = PooledLambda.obtainMessage(
4365 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4366 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368
4369 final long origId = Binder.clearCallingIdentity();
4370 try {
4371 if (values != null) {
4372 Settings.System.clearConfiguration(values);
4373 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4376 return mTmpUpdateConfigurationResult.changes != 0;
4377 } finally {
4378 Binder.restoreCallingIdentity(origId);
4379 }
4380 }
4381 }
4382
4383 @Override
4384 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386
4387 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 }
4392
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004394 final Message msg = PooledLambda.obtainMessage(
4395 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4396 DEFAULT_DISPLAY);
4397 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399
4400 final long origId = Binder.clearCallingIdentity();
4401 try {
4402 if (values != null) {
4403 Settings.System.clearConfiguration(values);
4404 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004405 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 UserHandle.USER_NULL, false /* deferResume */,
4407 mTmpUpdateConfigurationResult);
4408 return mTmpUpdateConfigurationResult.changes != 0;
4409 } finally {
4410 Binder.restoreCallingIdentity(origId);
4411 }
4412 }
4413 }
4414
4415 @Override
4416 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4417 CharSequence message) {
4418 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004419 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4421 }
4422 final long callingId = Binder.clearCallingIdentity();
4423 try {
4424 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004425 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 }
4427 } finally {
4428 Binder.restoreCallingIdentity(callingId);
4429 }
4430 }
4431
4432 @Override
4433 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 "cancelTaskWindowTransition()");
4436 final long ident = Binder.clearCallingIdentity();
4437 try {
4438 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004439 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 MATCH_TASK_IN_STACKS_ONLY);
4441 if (task == null) {
4442 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4443 return;
4444 }
4445 task.cancelWindowTransition();
4446 }
4447 } finally {
4448 Binder.restoreCallingIdentity(ident);
4449 }
4450 }
4451
4452 @Override
4453 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 final long ident = Binder.clearCallingIdentity();
4456 try {
4457 final TaskRecord task;
4458 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004459 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4461 if (task == null) {
4462 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4463 return null;
4464 }
4465 }
4466 // Don't call this while holding the lock as this operation might hit the disk.
4467 return task.getSnapshot(reducedResolution);
4468 } finally {
4469 Binder.restoreCallingIdentity(ident);
4470 }
4471 }
4472
4473 @Override
4474 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4475 synchronized (mGlobalLock) {
4476 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4477 if (r == null) {
4478 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4479 + token);
4480 return;
4481 }
4482 final long origId = Binder.clearCallingIdentity();
4483 try {
4484 r.setDisablePreviewScreenshots(disable);
4485 } finally {
4486 Binder.restoreCallingIdentity(origId);
4487 }
4488 }
4489 }
4490
4491 /** Return the user id of the last resumed activity. */
4492 @Override
4493 public @UserIdInt
4494 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4497 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004498 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004501 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 }
4503 }
4504
4505 @Override
4506 public void updateLockTaskFeatures(int userId, int flags) {
4507 final int callingUid = Binder.getCallingUid();
4508 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004509 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 "updateLockTaskFeatures()");
4511 }
4512 synchronized (mGlobalLock) {
4513 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4514 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004515 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 }
4517 }
4518
4519 @Override
4520 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4521 synchronized (mGlobalLock) {
4522 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4523 if (r == null) {
4524 return;
4525 }
4526 final long origId = Binder.clearCallingIdentity();
4527 try {
4528 r.setShowWhenLocked(showWhenLocked);
4529 } finally {
4530 Binder.restoreCallingIdentity(origId);
4531 }
4532 }
4533 }
4534
4535 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004536 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4537 synchronized (mGlobalLock) {
4538 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4539 if (r == null) {
4540 return;
4541 }
4542 final long origId = Binder.clearCallingIdentity();
4543 try {
4544 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4545 } finally {
4546 Binder.restoreCallingIdentity(origId);
4547 }
4548 }
4549 }
4550
4551 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4553 synchronized (mGlobalLock) {
4554 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4555 if (r == null) {
4556 return;
4557 }
4558 final long origId = Binder.clearCallingIdentity();
4559 try {
4560 r.setTurnScreenOn(turnScreenOn);
4561 } finally {
4562 Binder.restoreCallingIdentity(origId);
4563 }
4564 }
4565 }
4566
4567 @Override
4568 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004569 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004570 "registerRemoteAnimations");
4571 definition.setCallingPid(Binder.getCallingPid());
4572 synchronized (mGlobalLock) {
4573 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4574 if (r == null) {
4575 return;
4576 }
4577 final long origId = Binder.clearCallingIdentity();
4578 try {
4579 r.registerRemoteAnimations(definition);
4580 } finally {
4581 Binder.restoreCallingIdentity(origId);
4582 }
4583 }
4584 }
4585
4586 @Override
4587 public void registerRemoteAnimationForNextActivityStart(String packageName,
4588 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004589 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590 "registerRemoteAnimationForNextActivityStart");
4591 adapter.setCallingPid(Binder.getCallingPid());
4592 synchronized (mGlobalLock) {
4593 final long origId = Binder.clearCallingIdentity();
4594 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004595 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004596 packageName, adapter);
4597 } finally {
4598 Binder.restoreCallingIdentity(origId);
4599 }
4600 }
4601 }
4602
Evan Rosky966759f2019-01-15 10:33:58 -08004603 @Override
4604 public void registerRemoteAnimationsForDisplay(int displayId,
4605 RemoteAnimationDefinition definition) {
4606 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4607 "registerRemoteAnimations");
4608 definition.setCallingPid(Binder.getCallingPid());
4609 synchronized (mGlobalLock) {
4610 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4611 if (display == null) {
4612 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 display.mDisplayContent.registerRemoteAnimations(definition);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004624 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4625 @Override
4626 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4627 synchronized (mGlobalLock) {
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004630 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004636
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004637 @Override
4638 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004639 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004640 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004641 final int pid = Binder.getCallingPid();
4642 final WindowProcessController wpc = mPidMap.get(pid);
4643 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 }
4645 }
4646
4647 @Override
4648 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004649 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 != PERMISSION_GRANTED) {
4651 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4652 + Binder.getCallingPid()
4653 + ", uid=" + Binder.getCallingUid()
4654 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4655 Slog.w(TAG, msg);
4656 throw new SecurityException(msg);
4657 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004658 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004660 final int pid = Binder.getCallingPid();
4661 final WindowProcessController proc = mPidMap.get(pid);
4662 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 }
4664 }
4665
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004666 @Override
4667 public void stopAppSwitches() {
4668 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4669 synchronized (mGlobalLock) {
4670 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4671 mDidAppSwitch = false;
4672 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4673 }
4674 }
4675
4676 @Override
4677 public void resumeAppSwitches() {
4678 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4679 synchronized (mGlobalLock) {
4680 // Note that we don't execute any pending app switches... we will
4681 // let those wait until either the timeout, or the next start
4682 // activity request.
4683 mAppSwitchesAllowedTime = 0;
4684 }
4685 }
4686
4687 void onStartActivitySetDidAppSwitch() {
4688 if (mDidAppSwitch) {
4689 // This is the second allowed switch since we stopped switches, so now just generally
4690 // allow switches. Use case:
4691 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4692 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4693 // anyone to switch again).
4694 mAppSwitchesAllowedTime = 0;
4695 } else {
4696 mDidAppSwitch = true;
4697 }
4698 }
4699
4700 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004701 boolean shouldDisableNonVrUiLocked() {
4702 return mVrController.shouldDisableNonVrUiLocked();
4703 }
4704
Wale Ogunwale53783742018-09-16 10:21:51 -07004705 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004706 // VR apps are expected to run in a main display. If an app is turning on VR for
4707 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4708 // fullscreen stack before enabling VR Mode.
4709 // TODO: The goal of this code is to keep the VR app on the main display. When the
4710 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4711 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4712 // option would be a better choice here.
4713 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4714 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4715 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004716 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004717 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004718 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 }
4720 mH.post(() -> {
4721 if (!mVrController.onVrModeChanged(r)) {
4722 return;
4723 }
4724 synchronized (mGlobalLock) {
4725 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4726 mWindowManager.disableNonVrUi(disableNonVrUi);
4727 if (disableNonVrUi) {
4728 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4729 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004730 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732 }
4733 });
4734 }
4735
Wale Ogunwale53783742018-09-16 10:21:51 -07004736 @Override
4737 public int getPackageScreenCompatMode(String packageName) {
4738 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4739 synchronized (mGlobalLock) {
4740 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4741 }
4742 }
4743
4744 @Override
4745 public void setPackageScreenCompatMode(String packageName, int mode) {
4746 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4747 "setPackageScreenCompatMode");
4748 synchronized (mGlobalLock) {
4749 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4750 }
4751 }
4752
4753 @Override
4754 public boolean getPackageAskScreenCompat(String packageName) {
4755 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4756 synchronized (mGlobalLock) {
4757 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4758 }
4759 }
4760
4761 @Override
4762 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4763 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4764 "setPackageAskScreenCompat");
4765 synchronized (mGlobalLock) {
4766 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4767 }
4768 }
4769
Wale Ogunwale64258362018-10-16 15:13:37 -07004770 public static String relaunchReasonToString(int relaunchReason) {
4771 switch (relaunchReason) {
4772 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4773 return "window_resize";
4774 case RELAUNCH_REASON_FREE_RESIZE:
4775 return "free_resize";
4776 default:
4777 return null;
4778 }
4779 }
4780
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004781 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004782 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004783 }
4784
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 /** Pokes the task persister. */
4786 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4787 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4788 }
4789
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 boolean isKeyguardLocked() {
4791 return mKeyguardController.isKeyguardLocked();
4792 }
4793
Garfield Tan01548632018-11-27 10:15:48 -08004794 /**
4795 * Clears launch params for the given package.
4796 * @param packageNames the names of the packages of which the launch params are to be cleared
4797 */
4798 @Override
4799 public void clearLaunchParamsForPackages(List<String> packageNames) {
4800 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4801 "clearLaunchParamsForPackages");
4802 synchronized (mGlobalLock) {
4803 for (int i = 0; i < packageNames.size(); ++i) {
4804 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4805 }
4806 }
4807 }
4808
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004809 /**
4810 * Makes the display with the given id a single task instance display. I.e the display can only
4811 * contain one task.
4812 */
4813 @Override
4814 public void setDisplayToSingleTaskInstance(int displayId) {
4815 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4816 "setDisplayToSingleTaskInstance");
4817 final long origId = Binder.clearCallingIdentity();
4818 try {
4819 final ActivityDisplay display =
4820 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4821 if (display != null) {
4822 display.setDisplayToSingleTaskInstance();
4823 }
4824 } finally {
4825 Binder.restoreCallingIdentity(origId);
4826 }
4827 }
4828
Wale Ogunwale31913b52018-10-13 08:29:31 -07004829 void dumpLastANRLocked(PrintWriter pw) {
4830 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4831 if (mLastANRState == null) {
4832 pw.println(" <no ANR has occurred since boot>");
4833 } else {
4834 pw.println(mLastANRState);
4835 }
4836 }
4837
4838 void dumpLastANRTracesLocked(PrintWriter pw) {
4839 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4840
4841 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4842 if (ArrayUtils.isEmpty(files)) {
4843 pw.println(" <no ANR has occurred since boot>");
4844 return;
4845 }
4846 // Find the latest file.
4847 File latest = null;
4848 for (File f : files) {
4849 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4850 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004851 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004852 }
4853 pw.print("File: ");
4854 pw.print(latest.getName());
4855 pw.println();
4856 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4857 String line;
4858 while ((line = in.readLine()) != null) {
4859 pw.println(line);
4860 }
4861 } catch (IOException e) {
4862 pw.print("Unable to read: ");
4863 pw.print(e);
4864 pw.println();
4865 }
4866 }
4867
4868 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4869 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4870 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4871 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4872 }
4873
4874 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4875 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4876 pw.println(header);
4877
Wale Ogunwaled32da472018-11-16 07:19:28 -08004878 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004879 dumpPackage);
4880 boolean needSep = printedAnything;
4881
4882 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004883 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004884 " ResumedActivity: ");
4885 if (printed) {
4886 printedAnything = true;
4887 needSep = false;
4888 }
4889
4890 if (dumpPackage == null) {
4891 if (needSep) {
4892 pw.println();
4893 }
4894 printedAnything = true;
4895 mStackSupervisor.dump(pw, " ");
4896 }
4897
4898 if (!printedAnything) {
4899 pw.println(" (nothing)");
4900 }
4901 }
4902
4903 void dumpActivityContainersLocked(PrintWriter pw) {
4904 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004905 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004906 pw.println(" ");
4907 }
4908
4909 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4910 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4911 getActivityStartController().dump(pw, "", dumpPackage);
4912 }
4913
4914 /**
4915 * There are three things that cmd can be:
4916 * - a flattened component name that matches an existing activity
4917 * - the cmd arg isn't the flattened component name of an existing activity:
4918 * dump all activity whose component contains the cmd as a substring
4919 * - A hex number of the ActivityRecord object instance.
4920 *
4921 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4922 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4923 */
4924 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4925 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4926 ArrayList<ActivityRecord> activities;
4927
4928 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004929 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004930 dumpFocusedStackOnly);
4931 }
4932
4933 if (activities.size() <= 0) {
4934 return false;
4935 }
4936
4937 String[] newArgs = new String[args.length - opti];
4938 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4939
4940 TaskRecord lastTask = null;
4941 boolean needSep = false;
4942 for (int i = activities.size() - 1; i >= 0; i--) {
4943 ActivityRecord r = activities.get(i);
4944 if (needSep) {
4945 pw.println();
4946 }
4947 needSep = true;
4948 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004949 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004950 if (lastTask != task) {
4951 lastTask = task;
4952 pw.print("TASK "); pw.print(lastTask.affinity);
4953 pw.print(" id="); pw.print(lastTask.taskId);
4954 pw.print(" userId="); pw.println(lastTask.userId);
4955 if (dumpAll) {
4956 lastTask.dump(pw, " ");
4957 }
4958 }
4959 }
4960 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4961 }
4962 return true;
4963 }
4964
4965 /**
4966 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4967 * there is a thread associated with the activity.
4968 */
4969 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4970 final ActivityRecord r, String[] args, boolean dumpAll) {
4971 String innerPrefix = prefix + " ";
4972 synchronized (mGlobalLock) {
4973 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4974 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4975 pw.print(" pid=");
4976 if (r.hasProcess()) pw.println(r.app.getPid());
4977 else pw.println("(not running)");
4978 if (dumpAll) {
4979 r.dump(pw, innerPrefix);
4980 }
4981 }
4982 if (r.attachedToProcess()) {
4983 // flush anything that is already in the PrintWriter since the thread is going
4984 // to write to the file descriptor directly
4985 pw.flush();
4986 try {
4987 TransferPipe tp = new TransferPipe();
4988 try {
4989 r.app.getThread().dumpActivity(tp.getWriteFd(),
4990 r.appToken, innerPrefix, args);
4991 tp.go(fd);
4992 } finally {
4993 tp.kill();
4994 }
4995 } catch (IOException e) {
4996 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4997 } catch (RemoteException e) {
4998 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4999 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005000 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005001 }
5002
sanryhuang498e77e2018-12-06 14:57:01 +08005003 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5004 boolean testPssMode) {
5005 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5006 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5007 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005008 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005009 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5010 st.toString());
5011 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005012 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5013 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5014 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5016 testPssMode);
5017 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005018 }
5019
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005020 int getCurrentUserId() {
5021 return mAmInternal.getCurrentUserId();
5022 }
5023
5024 private void enforceNotIsolatedCaller(String caller) {
5025 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5026 throw new SecurityException("Isolated process not allowed to call " + caller);
5027 }
5028 }
5029
Wale Ogunwalef6733932018-06-27 05:14:34 -07005030 public Configuration getConfiguration() {
5031 Configuration ci;
5032 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005033 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005034 ci.userSetLocale = false;
5035 }
5036 return ci;
5037 }
5038
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005039 /**
5040 * Current global configuration information. Contains general settings for the entire system,
5041 * also corresponds to the merged configuration of the default display.
5042 */
5043 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005044 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005045 }
5046
5047 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5048 boolean initLocale) {
5049 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5050 }
5051
5052 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5053 boolean initLocale, boolean deferResume) {
5054 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5055 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5056 UserHandle.USER_NULL, deferResume);
5057 }
5058
Wale Ogunwale59507092018-10-29 09:00:30 -07005059 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005060 final long origId = Binder.clearCallingIdentity();
5061 try {
5062 synchronized (mGlobalLock) {
5063 updateConfigurationLocked(values, null, false, true, userId,
5064 false /* deferResume */);
5065 }
5066 } finally {
5067 Binder.restoreCallingIdentity(origId);
5068 }
5069 }
5070
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5072 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5073 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5074 deferResume, null /* result */);
5075 }
5076
5077 /**
5078 * Do either or both things: (1) change the current configuration, and (2)
5079 * make sure the given activity is running with the (now) current
5080 * configuration. Returns true if the activity has been left running, or
5081 * false if <var>starting</var> is being destroyed to match the new
5082 * configuration.
5083 *
5084 * @param userId is only used when persistent parameter is set to true to persist configuration
5085 * for that particular user
5086 */
5087 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5088 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5089 ActivityTaskManagerService.UpdateConfigurationResult result) {
5090 int changes = 0;
5091 boolean kept = true;
5092
5093 if (mWindowManager != null) {
5094 mWindowManager.deferSurfaceLayout();
5095 }
5096 try {
5097 if (values != null) {
5098 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5099 deferResume);
5100 }
5101
5102 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5103 } finally {
5104 if (mWindowManager != null) {
5105 mWindowManager.continueSurfaceLayout();
5106 }
5107 }
5108
5109 if (result != null) {
5110 result.changes = changes;
5111 result.activityRelaunched = !kept;
5112 }
5113 return kept;
5114 }
5115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005116 /** Update default (global) configuration and notify listeners about changes. */
5117 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5118 boolean persistent, int userId, boolean deferResume) {
5119 mTempConfig.setTo(getGlobalConfiguration());
5120 final int changes = mTempConfig.updateFrom(values);
5121 if (changes == 0) {
5122 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5123 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5124 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5125 // (even if there are no actual changes) to unfreeze the window.
5126 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5127 return 0;
5128 }
5129
5130 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5131 "Updating global configuration to: " + values);
5132
5133 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5134 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5135 values.colorMode,
5136 values.densityDpi,
5137 values.fontScale,
5138 values.hardKeyboardHidden,
5139 values.keyboard,
5140 values.keyboardHidden,
5141 values.mcc,
5142 values.mnc,
5143 values.navigation,
5144 values.navigationHidden,
5145 values.orientation,
5146 values.screenHeightDp,
5147 values.screenLayout,
5148 values.screenWidthDp,
5149 values.smallestScreenWidthDp,
5150 values.touchscreen,
5151 values.uiMode);
5152
5153
5154 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5155 final LocaleList locales = values.getLocales();
5156 int bestLocaleIndex = 0;
5157 if (locales.size() > 1) {
5158 if (mSupportedSystemLocales == null) {
5159 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5160 }
5161 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5162 }
5163 SystemProperties.set("persist.sys.locale",
5164 locales.get(bestLocaleIndex).toLanguageTag());
5165 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005166
5167 final Message m = PooledLambda.obtainMessage(
5168 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5169 locales.get(bestLocaleIndex));
5170 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 }
5172
Yunfan Chen75157d72018-07-27 14:47:21 +09005173 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005174
5175 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005176 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177
5178 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5179 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005180 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005181
5182 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005183 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184
5185 AttributeCache ac = AttributeCache.instance();
5186 if (ac != null) {
5187 ac.updateConfiguration(mTempConfig);
5188 }
5189
5190 // Make sure all resources in our process are updated right now, so that anyone who is going
5191 // to retrieve resource values after we return will be sure to get the new ones. This is
5192 // especially important during boot, where the first config change needs to guarantee all
5193 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005194 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005195
5196 // We need another copy of global config because we're scheduling some calls instead of
5197 // running them in place. We need to be sure that object we send will be handled unchanged.
5198 final Configuration configCopy = new Configuration(mTempConfig);
5199 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005200 final Message msg = PooledLambda.obtainMessage(
5201 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5202 this, userId, configCopy);
5203 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005204 }
5205
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005206 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005207 final int pid = mPidMap.keyAt(i);
5208 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005209 if (DEBUG_CONFIGURATION) {
5210 Slog.v(TAG_CONFIGURATION, "Update process config of "
5211 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005212 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005213 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005214 }
5215
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005216 final Message msg = PooledLambda.obtainMessage(
5217 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5218 mAmInternal, changes, initLocale);
5219 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220
5221 // Override configuration of the default display duplicates global config, so we need to
5222 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005223 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 DEFAULT_DISPLAY);
5225
5226 return changes;
5227 }
5228
5229 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5230 boolean deferResume, int displayId) {
5231 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5232 displayId, null /* result */);
5233 }
5234
5235 /**
5236 * Updates override configuration specific for the selected display. If no config is provided,
5237 * new one will be computed in WM based on current display info.
5238 */
5239 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5240 ActivityRecord starting, boolean deferResume, int displayId,
5241 ActivityTaskManagerService.UpdateConfigurationResult result) {
5242 int changes = 0;
5243 boolean kept = true;
5244
5245 if (mWindowManager != null) {
5246 mWindowManager.deferSurfaceLayout();
5247 }
5248 try {
5249 if (values != null) {
5250 if (displayId == DEFAULT_DISPLAY) {
5251 // Override configuration of the default display duplicates global config, so
5252 // we're calling global config update instead for default display. It will also
5253 // apply the correct override config.
5254 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5255 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5256 } else {
5257 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5258 }
5259 }
5260
5261 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5262 } finally {
5263 if (mWindowManager != null) {
5264 mWindowManager.continueSurfaceLayout();
5265 }
5266 }
5267
5268 if (result != null) {
5269 result.changes = changes;
5270 result.activityRelaunched = !kept;
5271 }
5272 return kept;
5273 }
5274
5275 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5276 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005277 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 final int changes = mTempConfig.updateFrom(values);
5279 if (changes != 0) {
5280 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5281 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005282 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005283
5284 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5285 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005286 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287
Wale Ogunwale5c918702018-10-18 11:06:33 -07005288 // Post message to start process to avoid possible deadlock of calling into AMS with
5289 // the ATMS lock held.
5290 final Message msg = PooledLambda.obtainMessage(
5291 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005292 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005293 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 }
5295 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005296 return changes;
5297 }
5298
Wale Ogunwalef6733932018-06-27 05:14:34 -07005299 private void updateEventDispatchingLocked(boolean booted) {
5300 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5301 }
5302
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005303 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5304 final ContentResolver resolver = mContext.getContentResolver();
5305 Settings.System.putConfigurationForUser(resolver, config, userId);
5306 }
5307
5308 private void sendLocaleToMountDaemonMsg(Locale l) {
5309 try {
5310 IBinder service = ServiceManager.getService("mount");
5311 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5312 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5313 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5314 } catch (RemoteException e) {
5315 Log.e(TAG, "Error storing locale for decryption UI", e);
5316 }
5317 }
5318
Alison Cichowlas3e340502018-08-07 17:15:01 -04005319 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5320 mStartActivitySources.remove(permissionToken);
5321 mExpiredStartAsCallerTokens.add(permissionToken);
5322 }
5323
5324 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5325 mExpiredStartAsCallerTokens.remove(permissionToken);
5326 }
5327
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005328 boolean isActivityStartsLoggingEnabled() {
5329 return mAmInternal.isActivityStartsLoggingEnabled();
5330 }
5331
Michal Karpinski8596ded2018-11-14 14:43:48 +00005332 boolean isBackgroundActivityStartsEnabled() {
5333 return mAmInternal.isBackgroundActivityStartsEnabled();
5334 }
5335
Ricky Waiaca8a772019-04-04 16:01:06 +01005336 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5337 if (packageName == null) {
5338 return false;
5339 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005340 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5341 }
5342
Wale Ogunwalef6733932018-06-27 05:14:34 -07005343 void enableScreenAfterBoot(boolean booted) {
5344 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5345 SystemClock.uptimeMillis());
5346 mWindowManager.enableScreenAfterBoot();
5347
5348 synchronized (mGlobalLock) {
5349 updateEventDispatchingLocked(booted);
5350 }
5351 }
5352
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005353 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5354 if (r == null || !r.hasProcess()) {
5355 return KEY_DISPATCHING_TIMEOUT_MS;
5356 }
5357 return getInputDispatchingTimeoutLocked(r.app);
5358 }
5359
5360 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005361 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005362 }
5363
Wale Ogunwalef6733932018-06-27 05:14:34 -07005364 /**
5365 * Decide based on the configuration whether we should show the ANR,
5366 * crash, etc dialogs. The idea is that if there is no affordance to
5367 * press the on-screen buttons, or the user experience would be more
5368 * greatly impacted than the crash itself, we shouldn't show the dialog.
5369 *
5370 * A thought: SystemUI might also want to get told about this, the Power
5371 * dialog / global actions also might want different behaviors.
5372 */
5373 private void updateShouldShowDialogsLocked(Configuration config) {
5374 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5375 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5376 && config.navigation == Configuration.NAVIGATION_NONAV);
5377 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5378 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5379 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5380 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5381 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5382 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5383 HIDE_ERROR_DIALOGS, 0) != 0;
5384 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5385 }
5386
5387 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5388 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5389 FONT_SCALE, 1.0f, userId);
5390
5391 synchronized (this) {
5392 if (getGlobalConfiguration().fontScale == scaleFactor) {
5393 return;
5394 }
5395
5396 final Configuration configuration
5397 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5398 configuration.fontScale = scaleFactor;
5399 updatePersistentConfiguration(configuration, userId);
5400 }
5401 }
5402
5403 // Actually is sleeping or shutting down or whatever else in the future
5404 // is an inactive state.
5405 boolean isSleepingOrShuttingDownLocked() {
5406 return isSleepingLocked() || mShuttingDown;
5407 }
5408
5409 boolean isSleepingLocked() {
5410 return mSleeping;
5411 }
5412
Riddle Hsu16567132018-08-16 21:37:47 +08005413 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005415 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 if (task.isActivityTypeStandard()) {
5417 if (mCurAppTimeTracker != r.appTimeTracker) {
5418 // We are switching app tracking. Complete the current one.
5419 if (mCurAppTimeTracker != null) {
5420 mCurAppTimeTracker.stop();
5421 mH.obtainMessage(
5422 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005423 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005424 mCurAppTimeTracker = null;
5425 }
5426 if (r.appTimeTracker != null) {
5427 mCurAppTimeTracker = r.appTimeTracker;
5428 startTimeTrackingFocusedActivityLocked();
5429 }
5430 } else {
5431 startTimeTrackingFocusedActivityLocked();
5432 }
5433 } else {
5434 r.appTimeTracker = null;
5435 }
5436 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5437 // TODO: Probably not, because we don't want to resume voice on switching
5438 // back to this activity
5439 if (task.voiceInteractor != null) {
5440 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5441 } else {
5442 finishRunningVoiceLocked();
5443
5444 if (mLastResumedActivity != null) {
5445 final IVoiceInteractionSession session;
5446
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005447 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 if (lastResumedActivityTask != null
5449 && lastResumedActivityTask.voiceSession != null) {
5450 session = lastResumedActivityTask.voiceSession;
5451 } else {
5452 session = mLastResumedActivity.voiceSession;
5453 }
5454
5455 if (session != null) {
5456 // We had been in a voice interaction session, but now focused has
5457 // move to something different. Just finish the session, we can't
5458 // return to it and retain the proper state and synchronization with
5459 // the voice interaction service.
5460 finishVoiceTask(session);
5461 }
5462 }
5463 }
5464
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005465 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5466 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005467 }
5468 updateResumedAppTrace(r);
5469 mLastResumedActivity = r;
5470
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005471 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472
5473 applyUpdateLockStateLocked(r);
5474 applyUpdateVrModeLocked(r);
5475
5476 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005477 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 r == null ? "NULL" : r.shortComponentName,
5479 reason);
5480 }
5481
5482 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5483 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005484 final ActivityTaskManagerInternal.SleepToken token =
5485 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486 updateSleepIfNeededLocked();
5487 return token;
5488 }
5489 }
5490
5491 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005492 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 final boolean wasSleeping = mSleeping;
5494 boolean updateOomAdj = false;
5495
5496 if (!shouldSleep) {
5497 // If wasSleeping is true, we need to wake up activity manager state from when
5498 // we started sleeping. In either case, we need to apply the sleep tokens, which
5499 // will wake up stacks or put them to sleep as appropriate.
5500 if (wasSleeping) {
5501 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005502 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5503 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005504 startTimeTrackingFocusedActivityLocked();
5505 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5506 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5507 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005508 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 if (wasSleeping) {
5510 updateOomAdj = true;
5511 }
5512 } else if (!mSleeping && shouldSleep) {
5513 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005514 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5515 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005516 if (mCurAppTimeTracker != null) {
5517 mCurAppTimeTracker.stop();
5518 }
5519 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5520 mStackSupervisor.goingToSleepLocked();
5521 updateResumedAppTrace(null /* resumed */);
5522 updateOomAdj = true;
5523 }
5524 if (updateOomAdj) {
5525 mH.post(mAmInternal::updateOomAdj);
5526 }
5527 }
5528
5529 void updateOomAdj() {
5530 mH.post(mAmInternal::updateOomAdj);
5531 }
5532
Wale Ogunwale53783742018-09-16 10:21:51 -07005533 void updateCpuStats() {
5534 mH.post(mAmInternal::updateCpuStats);
5535 }
5536
Hui Yu03d12402018-12-06 18:00:37 -08005537 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5538 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005539 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5540 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005541 mH.sendMessage(m);
5542 }
5543
Hui Yu03d12402018-12-06 18:00:37 -08005544 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005545 ComponentName taskRoot = null;
5546 final TaskRecord task = activity.getTaskRecord();
5547 if (task != null) {
5548 final ActivityRecord rootActivity = task.getRootActivity();
5549 if (rootActivity != null) {
5550 taskRoot = rootActivity.mActivityComponent;
5551 }
5552 }
5553
Hui Yu03d12402018-12-06 18:00:37 -08005554 final Message m = PooledLambda.obtainMessage(
5555 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005556 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005557 mH.sendMessage(m);
5558 }
5559
Wale Ogunwale53783742018-09-16 10:21:51 -07005560 void setBooting(boolean booting) {
5561 mAmInternal.setBooting(booting);
5562 }
5563
5564 boolean isBooting() {
5565 return mAmInternal.isBooting();
5566 }
5567
5568 void setBooted(boolean booted) {
5569 mAmInternal.setBooted(booted);
5570 }
5571
5572 boolean isBooted() {
5573 return mAmInternal.isBooted();
5574 }
5575
5576 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5577 mH.post(() -> {
5578 if (finishBooting) {
5579 mAmInternal.finishBooting();
5580 }
5581 if (enableScreen) {
5582 mInternal.enableScreenAfterBoot(isBooted());
5583 }
5584 });
5585 }
5586
5587 void setHeavyWeightProcess(ActivityRecord root) {
5588 mHeavyWeightProcess = root.app;
5589 final Message m = PooledLambda.obtainMessage(
5590 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005591 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005592 mH.sendMessage(m);
5593 }
5594
5595 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5596 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5597 return;
5598 }
5599
5600 mHeavyWeightProcess = null;
5601 final Message m = PooledLambda.obtainMessage(
5602 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5603 proc.mUserId);
5604 mH.sendMessage(m);
5605 }
5606
5607 private void cancelHeavyWeightProcessNotification(int userId) {
5608 final INotificationManager inm = NotificationManager.getService();
5609 if (inm == null) {
5610 return;
5611 }
5612 try {
5613 inm.cancelNotificationWithTag("android", null,
5614 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5615 } catch (RuntimeException e) {
5616 Slog.w(TAG, "Error canceling notification for service", e);
5617 } catch (RemoteException e) {
5618 }
5619
5620 }
5621
5622 private void postHeavyWeightProcessNotification(
5623 WindowProcessController proc, Intent intent, int userId) {
5624 if (proc == null) {
5625 return;
5626 }
5627
5628 final INotificationManager inm = NotificationManager.getService();
5629 if (inm == null) {
5630 return;
5631 }
5632
5633 try {
5634 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5635 String text = mContext.getString(R.string.heavy_weight_notification,
5636 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5637 Notification notification =
5638 new Notification.Builder(context,
5639 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5640 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5641 .setWhen(0)
5642 .setOngoing(true)
5643 .setTicker(text)
5644 .setColor(mContext.getColor(
5645 com.android.internal.R.color.system_notification_accent_color))
5646 .setContentTitle(text)
5647 .setContentText(
5648 mContext.getText(R.string.heavy_weight_notification_detail))
5649 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5650 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5651 new UserHandle(userId)))
5652 .build();
5653 try {
5654 inm.enqueueNotificationWithTag("android", "android", null,
5655 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5656 } catch (RuntimeException e) {
5657 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5658 } catch (RemoteException e) {
5659 }
5660 } catch (PackageManager.NameNotFoundException e) {
5661 Slog.w(TAG, "Unable to create context for heavy notification", e);
5662 }
5663
5664 }
5665
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005666 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5667 IBinder token, String resultWho, int requestCode, Intent[] intents,
5668 String[] resolvedTypes, int flags, Bundle bOptions) {
5669
5670 ActivityRecord activity = null;
5671 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5672 activity = ActivityRecord.isInStackLocked(token);
5673 if (activity == null) {
5674 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5675 return null;
5676 }
5677 if (activity.finishing) {
5678 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5679 return null;
5680 }
5681 }
5682
5683 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5684 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5685 bOptions);
5686 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5687 if (noCreate) {
5688 return rec;
5689 }
5690 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5691 if (activity.pendingResults == null) {
5692 activity.pendingResults = new HashSet<>();
5693 }
5694 activity.pendingResults.add(rec.ref);
5695 }
5696 return rec;
5697 }
5698
Andrii Kulian52d255c2018-07-13 11:32:19 -07005699 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005700 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005701 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005702 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5703 mCurAppTimeTracker.start(resumedActivity.packageName);
5704 }
5705 }
5706
5707 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5708 if (mTracedResumedActivity != null) {
5709 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5710 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5711 }
5712 if (resumed != null) {
5713 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5714 constructResumedTraceName(resumed.packageName), 0);
5715 }
5716 mTracedResumedActivity = resumed;
5717 }
5718
5719 private String constructResumedTraceName(String packageName) {
5720 return "focused app: " + packageName;
5721 }
5722
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005723 /** Applies latest configuration and/or visibility updates if needed. */
5724 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5725 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005726 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005727 // mainStack is null during startup.
5728 if (mainStack != null) {
5729 if (changes != 0 && starting == null) {
5730 // If the configuration changed, and the caller is not already
5731 // in the process of starting an activity, then find the top
5732 // activity to check if its configuration needs to change.
5733 starting = mainStack.topRunningActivityLocked();
5734 }
5735
5736 if (starting != null) {
5737 kept = starting.ensureActivityConfiguration(changes,
5738 false /* preserveWindow */);
5739 // And we need to make sure at this point that all other activities
5740 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005741 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005742 !PRESERVE_WINDOWS);
5743 }
5744 }
5745
5746 return kept;
5747 }
5748
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005749 void scheduleAppGcsLocked() {
5750 mH.post(() -> mAmInternal.scheduleAppGcs());
5751 }
5752
Wale Ogunwale53783742018-09-16 10:21:51 -07005753 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5754 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5755 }
5756
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005757 /**
5758 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5759 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5760 * on demand.
5761 */
5762 IPackageManager getPackageManager() {
5763 return AppGlobals.getPackageManager();
5764 }
5765
5766 PackageManagerInternal getPackageManagerInternalLocked() {
5767 if (mPmInternal == null) {
5768 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5769 }
5770 return mPmInternal;
5771 }
5772
Wale Ogunwale008163e2018-07-23 23:11:08 -07005773 AppWarnings getAppWarningsLocked() {
5774 return mAppWarnings;
5775 }
5776
Wale Ogunwale214f3482018-10-04 11:00:47 -07005777 Intent getHomeIntent() {
5778 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5779 intent.setComponent(mTopComponent);
5780 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5781 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5782 intent.addCategory(Intent.CATEGORY_HOME);
5783 }
5784 return intent;
5785 }
5786
Chilun2ef71f72018-11-16 17:57:15 +08005787 /**
5788 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5789 * activities.
5790 *
5791 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5792 * component defined in config_secondaryHomeComponent.
5793 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5794 */
5795 Intent getSecondaryHomeIntent(String preferredPackage) {
5796 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5797 if (preferredPackage == null) {
5798 // Using the component stored in config if no package name.
5799 final String secondaryHomeComponent = mContext.getResources().getString(
5800 com.android.internal.R.string.config_secondaryHomeComponent);
5801 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5802 } else {
5803 intent.setPackage(preferredPackage);
5804 }
5805 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5806 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5807 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5808 }
5809 return intent;
5810 }
5811
Wale Ogunwale214f3482018-10-04 11:00:47 -07005812 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5813 if (info == null) return null;
5814 ApplicationInfo newInfo = new ApplicationInfo(info);
5815 newInfo.initForUser(userId);
5816 return newInfo;
5817 }
5818
Wale Ogunwale9c103022018-10-18 07:44:54 -07005819 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005820 if (uid == SYSTEM_UID) {
5821 // The system gets to run in any process. If there are multiple processes with the same
5822 // uid, just pick the first (this should never happen).
5823 final SparseArray<WindowProcessController> procs =
5824 mProcessNames.getMap().get(processName);
5825 if (procs == null) return null;
5826 final int procCount = procs.size();
5827 for (int i = 0; i < procCount; i++) {
5828 final int procUid = procs.keyAt(i);
5829 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5830 // Don't use an app process or different user process for system component.
5831 continue;
5832 }
5833 return procs.valueAt(i);
5834 }
5835 }
5836
5837 return mProcessNames.get(processName, uid);
5838 }
5839
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005840 WindowProcessController getProcessController(IApplicationThread thread) {
5841 if (thread == null) {
5842 return null;
5843 }
5844
5845 final IBinder threadBinder = thread.asBinder();
5846 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5847 for (int i = pmap.size()-1; i >= 0; i--) {
5848 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5849 for (int j = procs.size() - 1; j >= 0; j--) {
5850 final WindowProcessController proc = procs.valueAt(j);
5851 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5852 return proc;
5853 }
5854 }
5855 }
5856
5857 return null;
5858 }
5859
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005860 WindowProcessController getProcessController(int pid, int uid) {
Yunfan Chen8546b212019-04-01 15:34:44 +09005861 final WindowProcessController proc = mPidMap.get(pid);
5862 if (proc == null) return null;
5863 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5864 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005865 }
5866 return null;
5867 }
5868
Riddle Hsua0536432019-02-16 00:38:59 +08005869 int getUidState(int uid) {
5870 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005871 }
5872
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005873 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005874 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005875 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5876 }
5877
Michal Karpinski4026cae2019-02-12 11:51:47 +00005878 boolean isDeviceOwner(String packageName) {
5879 if (packageName == null) {
5880 return false;
5881 }
5882 return packageName.equals(mDeviceOwnerPackageName);
5883 }
5884
5885 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5886 mDeviceOwnerPackageName = deviceOwnerPkg;
5887 }
5888
Wale Ogunwale9de19442018-10-18 19:05:03 -07005889 /**
5890 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5891 * the whitelist
5892 */
5893 String getPendingTempWhitelistTagForUidLocked(int uid) {
5894 return mPendingTempWhitelist.get(uid);
5895 }
5896
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005897 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5898 if (true || Build.IS_USER) {
5899 return;
5900 }
5901
5902 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5903 StrictMode.allowThreadDiskWrites();
5904 try {
5905 File tracesDir = new File("/data/anr");
5906 File tracesFile = null;
5907 try {
5908 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5909
5910 StringBuilder sb = new StringBuilder();
5911 Time tobj = new Time();
5912 tobj.set(System.currentTimeMillis());
5913 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5914 sb.append(": ");
5915 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5916 sb.append(" since ");
5917 sb.append(msg);
5918 FileOutputStream fos = new FileOutputStream(tracesFile);
5919 fos.write(sb.toString().getBytes());
5920 if (app == null) {
5921 fos.write("\n*** No application process!".getBytes());
5922 }
5923 fos.close();
5924 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5925 } catch (IOException e) {
5926 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5927 return;
5928 }
5929
5930 if (app != null && app.getPid() > 0) {
5931 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5932 firstPids.add(app.getPid());
5933 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5934 }
5935
5936 File lastTracesFile = null;
5937 File curTracesFile = null;
5938 for (int i=9; i>=0; i--) {
5939 String name = String.format(Locale.US, "slow%02d.txt", i);
5940 curTracesFile = new File(tracesDir, name);
5941 if (curTracesFile.exists()) {
5942 if (lastTracesFile != null) {
5943 curTracesFile.renameTo(lastTracesFile);
5944 } else {
5945 curTracesFile.delete();
5946 }
5947 }
5948 lastTracesFile = curTracesFile;
5949 }
5950 tracesFile.renameTo(curTracesFile);
5951 } finally {
5952 StrictMode.setThreadPolicy(oldPolicy);
5953 }
5954 }
5955
Michal Karpinskida34cd42019-04-02 19:46:52 +01005956 boolean isAssociatedCompanionApp(int userId, int uid) {
5957 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5958 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005959 return false;
5960 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005961 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005962 }
5963
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005964 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005965 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005966
5967
Wale Ogunwale98875612018-10-12 07:53:02 -07005968 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5969 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005970
Riddle Hsud93a6c42018-11-29 21:50:06 +08005971 H(Looper looper) {
5972 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005973 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005974
5975 @Override
5976 public void handleMessage(Message msg) {
5977 switch (msg.what) {
5978 case REPORT_TIME_TRACKER_MSG: {
5979 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5980 tracker.deliverResult(mContext);
5981 } break;
5982 }
5983 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005984 }
5985
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005986 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005987 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005988
5989 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005990 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005991 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005992
5993 @Override
5994 public void handleMessage(Message msg) {
5995 switch (msg.what) {
5996 case DISMISS_DIALOG_UI_MSG: {
5997 final Dialog d = (Dialog) msg.obj;
5998 d.dismiss();
5999 break;
6000 }
6001 }
6002 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006003 }
6004
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006005 final class LocalService extends ActivityTaskManagerInternal {
6006 @Override
6007 public SleepToken acquireSleepToken(String tag, int displayId) {
6008 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006009 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006010 }
6011
6012 @Override
6013 public ComponentName getHomeActivityForUser(int userId) {
6014 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006015 final ActivityRecord homeActivity =
6016 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006017 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006018 }
6019 }
6020
6021 @Override
6022 public void onLocalVoiceInteractionStarted(IBinder activity,
6023 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6024 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006025 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006026 }
6027 }
6028
6029 @Override
6030 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6031 synchronized (mGlobalLock) {
6032 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6033 reasons, timestamp);
6034 }
6035 }
6036
6037 @Override
6038 public void notifyAppTransitionFinished() {
6039 synchronized (mGlobalLock) {
6040 mStackSupervisor.notifyAppTransitionDone();
6041 }
6042 }
6043
6044 @Override
6045 public void notifyAppTransitionCancelled() {
6046 synchronized (mGlobalLock) {
6047 mStackSupervisor.notifyAppTransitionDone();
6048 }
6049 }
6050
6051 @Override
6052 public List<IBinder> getTopVisibleActivities() {
6053 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006054 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006055 }
6056 }
6057
6058 @Override
6059 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6060 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006061 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006062 }
6063 }
6064
6065 @Override
6066 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6067 Bundle bOptions) {
6068 Preconditions.checkNotNull(intents, "intents");
6069 final String[] resolvedTypes = new String[intents.length];
6070
6071 // UID of the package on user userId.
6072 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6073 // packageUid may not be initialized.
6074 int packageUid = 0;
6075 final long ident = Binder.clearCallingIdentity();
6076
6077 try {
6078 for (int i = 0; i < intents.length; i++) {
6079 resolvedTypes[i] =
6080 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6081 }
6082
6083 packageUid = AppGlobals.getPackageManager().getPackageUid(
6084 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6085 } catch (RemoteException e) {
6086 // Shouldn't happen.
6087 } finally {
6088 Binder.restoreCallingIdentity(ident);
6089 }
6090
Riddle Hsu591bf612019-02-14 17:55:31 +08006091 return getActivityStartController().startActivitiesInPackage(
6092 packageUid, packageName,
6093 intents, resolvedTypes, null /* resultTo */,
6094 SafeActivityOptions.fromBundle(bOptions), userId,
6095 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6096 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006097 }
6098
6099 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006100 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6101 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6102 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6103 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006104 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006105 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006106 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6107 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6108 userId, validateIncomingUser, originatingPendingIntent,
6109 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006110 }
6111 }
6112
6113 @Override
6114 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6115 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6116 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6117 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006118 PendingIntentRecord originatingPendingIntent,
6119 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006120 synchronized (mGlobalLock) {
6121 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6122 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6123 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006124 validateIncomingUser, originatingPendingIntent,
6125 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006126 }
6127 }
6128
6129 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006130 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6131 Intent intent, Bundle options, int userId) {
6132 return ActivityTaskManagerService.this.startActivityAsUser(
6133 caller, callerPacakge, intent,
6134 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6135 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6136 false /*validateIncomingUser*/);
6137 }
6138
6139 @Override
lumark588a3e82018-07-20 18:53:54 +08006140 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006141 synchronized (mGlobalLock) {
6142
6143 // We might change the visibilities here, so prepare an empty app transition which
6144 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006145 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006146 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006147 if (activityDisplay == null) {
6148 return;
6149 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006150 final DisplayContent dc = activityDisplay.mDisplayContent;
6151 final boolean wasTransitionSet =
6152 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006154 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006156 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157
6158 // If there was a transition set already we don't want to interfere with it as we
6159 // might be starting it too early.
6160 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006161 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 }
6163 }
6164 if (callback != null) {
6165 callback.run();
6166 }
6167 }
6168
6169 @Override
6170 public void notifyKeyguardTrustedChanged() {
6171 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006172 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006173 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175 }
6176 }
6177
6178 /**
6179 * Called after virtual display Id is updated by
6180 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6181 * {@param vrVr2dDisplayId}.
6182 */
6183 @Override
6184 public void setVr2dDisplayId(int vr2dDisplayId) {
6185 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6186 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006187 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 }
6189 }
6190
6191 @Override
6192 public void setFocusedActivity(IBinder token) {
6193 synchronized (mGlobalLock) {
6194 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6195 if (r == null) {
6196 throw new IllegalArgumentException(
6197 "setFocusedActivity: No activity record matching token=" + token);
6198 }
Louis Chang19443452018-10-09 12:10:21 +08006199 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006200 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 }
6202 }
6203 }
6204
6205 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006207 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 }
6209
6210 @Override
6211 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006212 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006213 }
6214
6215 @Override
6216 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006217 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218 }
6219
6220 @Override
6221 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6222 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6223 }
6224
6225 @Override
6226 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006227 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006228 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006229
6230 @Override
6231 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6232 synchronized (mGlobalLock) {
6233 mActiveVoiceInteractionServiceComponent = component;
6234 }
6235 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006236
6237 @Override
6238 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6239 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6240 return;
6241 }
6242 synchronized (mGlobalLock) {
6243 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6244 if (types == null) {
6245 if (uid < 0) {
6246 return;
6247 }
6248 types = new ArrayMap<>();
6249 mAllowAppSwitchUids.put(userId, types);
6250 }
6251 if (uid < 0) {
6252 types.remove(type);
6253 } else {
6254 types.put(type, uid);
6255 }
6256 }
6257 }
6258
6259 @Override
6260 public void onUserStopped(int userId) {
6261 synchronized (mGlobalLock) {
6262 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6263 mAllowAppSwitchUids.remove(userId);
6264 }
6265 }
6266
6267 @Override
6268 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6269 synchronized (mGlobalLock) {
6270 return ActivityTaskManagerService.this.isGetTasksAllowed(
6271 caller, callingPid, callingUid);
6272 }
6273 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006274
Riddle Hsua0536432019-02-16 00:38:59 +08006275 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006276 @Override
6277 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006278 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006279 mProcessNames.put(proc.mName, proc.mUid, proc);
6280 }
6281 }
6282
Riddle Hsua0536432019-02-16 00:38:59 +08006283 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006284 @Override
6285 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006286 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006287 mProcessNames.remove(name, uid);
6288 }
6289 }
6290
Riddle Hsua0536432019-02-16 00:38:59 +08006291 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006292 @Override
6293 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006294 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006295 if (proc == mHomeProcess) {
6296 mHomeProcess = null;
6297 }
6298 if (proc == mPreviousProcess) {
6299 mPreviousProcess = null;
6300 }
6301 }
6302 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006303
Riddle Hsua0536432019-02-16 00:38:59 +08006304 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006305 @Override
6306 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006308 return mTopProcessState;
6309 }
6310 }
6311
Riddle Hsua0536432019-02-16 00:38:59 +08006312 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006313 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006315 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006316 return proc == mHeavyWeightProcess;
6317 }
6318 }
6319
Riddle Hsua0536432019-02-16 00:38:59 +08006320 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006321 @Override
6322 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006323 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006324 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6325 }
6326 }
6327
6328 @Override
6329 public void finishHeavyWeightApp() {
6330 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006331 if (mHeavyWeightProcess != null) {
6332 mHeavyWeightProcess.finishActivities();
6333 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006334 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6335 mHeavyWeightProcess);
6336 }
6337 }
6338
Riddle Hsua0536432019-02-16 00:38:59 +08006339 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006340 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006341 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006343 return isSleepingLocked();
6344 }
6345 }
6346
6347 @Override
6348 public boolean isShuttingDown() {
6349 synchronized (mGlobalLock) {
6350 return mShuttingDown;
6351 }
6352 }
6353
6354 @Override
6355 public boolean shuttingDown(boolean booted, int timeout) {
6356 synchronized (mGlobalLock) {
6357 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006358 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006359 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006360 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006361 return mStackSupervisor.shutdownLocked(timeout);
6362 }
6363 }
6364
6365 @Override
6366 public void enableScreenAfterBoot(boolean booted) {
6367 synchronized (mGlobalLock) {
6368 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6369 SystemClock.uptimeMillis());
6370 mWindowManager.enableScreenAfterBoot();
6371 updateEventDispatchingLocked(booted);
6372 }
6373 }
6374
6375 @Override
6376 public boolean showStrictModeViolationDialog() {
6377 synchronized (mGlobalLock) {
6378 return mShowDialogs && !mSleeping && !mShuttingDown;
6379 }
6380 }
6381
6382 @Override
6383 public void showSystemReadyErrorDialogsIfNeeded() {
6384 synchronized (mGlobalLock) {
6385 try {
6386 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6387 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6388 + " data partition or your device will be unstable.");
6389 mUiHandler.post(() -> {
6390 if (mShowDialogs) {
6391 AlertDialog d = new BaseErrorDialog(mUiContext);
6392 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6393 d.setCancelable(false);
6394 d.setTitle(mUiContext.getText(R.string.android_system_label));
6395 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6396 d.setButton(DialogInterface.BUTTON_POSITIVE,
6397 mUiContext.getText(R.string.ok),
6398 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6399 d.show();
6400 }
6401 });
6402 }
6403 } catch (RemoteException e) {
6404 }
6405
6406 if (!Build.isBuildConsistent()) {
6407 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6408 mUiHandler.post(() -> {
6409 if (mShowDialogs) {
6410 AlertDialog d = new BaseErrorDialog(mUiContext);
6411 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6412 d.setCancelable(false);
6413 d.setTitle(mUiContext.getText(R.string.android_system_label));
6414 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6415 d.setButton(DialogInterface.BUTTON_POSITIVE,
6416 mUiContext.getText(R.string.ok),
6417 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6418 d.show();
6419 }
6420 });
6421 }
6422 }
6423 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006424
6425 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006426 public void onProcessMapped(int pid, WindowProcessController proc) {
6427 synchronized (mGlobalLock) {
6428 mPidMap.put(pid, proc);
6429 }
6430 }
6431
6432 @Override
6433 public void onProcessUnMapped(int pid) {
6434 synchronized (mGlobalLock) {
6435 mPidMap.remove(pid);
6436 }
6437 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006438
6439 @Override
6440 public void onPackageDataCleared(String name) {
6441 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006442 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006443 mAppWarnings.onPackageDataCleared(name);
6444 }
6445 }
6446
6447 @Override
6448 public void onPackageUninstalled(String name) {
6449 synchronized (mGlobalLock) {
6450 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006451 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006452 }
6453 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006454
6455 @Override
6456 public void onPackageAdded(String name, boolean replacing) {
6457 synchronized (mGlobalLock) {
6458 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6459 }
6460 }
6461
6462 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006463 public void onPackageReplaced(ApplicationInfo aInfo) {
6464 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006465 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006466 }
6467 }
6468
6469 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006470 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6471 synchronized (mGlobalLock) {
6472 return compatibilityInfoForPackageLocked(ai);
6473 }
6474 }
6475
Yunfan Chen75157d72018-07-27 14:47:21 +09006476 /**
6477 * Set the corresponding display information for the process global configuration. To be
6478 * called when we need to show IME on a different display.
6479 *
6480 * @param pid The process id associated with the IME window.
6481 * @param displayId The ID of the display showing the IME.
6482 */
6483 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006484 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006485 if (pid == MY_PID || pid < 0) {
6486 if (DEBUG_CONFIGURATION) {
6487 Slog.w(TAG,
6488 "Trying to update display configuration for system/invalid process.");
6489 }
6490 return;
6491 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006492 synchronized (mGlobalLock) {
6493 final ActivityDisplay activityDisplay =
6494 mRootActivityContainer.getActivityDisplay(displayId);
6495 if (activityDisplay == null) {
6496 // Call might come when display is not yet added or has been removed.
6497 if (DEBUG_CONFIGURATION) {
6498 Slog.w(TAG, "Trying to update display configuration for non-existing "
6499 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006500 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006501 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006502 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006503 final WindowProcessController process = mPidMap.get(pid);
6504 if (process == null) {
6505 if (DEBUG_CONFIGURATION) {
6506 Slog.w(TAG, "Trying to update display configuration for invalid "
6507 + "process, pid=" + pid);
6508 }
6509 return;
6510 }
6511 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6512 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006513 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006514
6515 @Override
6516 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6517 int requestCode, int resultCode, Intent data) {
6518 synchronized (mGlobalLock) {
6519 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006520 if (r != null && r.getActivityStack() != null) {
6521 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6522 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006523 }
6524 }
6525 }
6526
6527 @Override
6528 public void clearPendingResultForActivity(IBinder activityToken,
6529 WeakReference<PendingIntentRecord> pir) {
6530 synchronized (mGlobalLock) {
6531 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6532 if (r != null && r.pendingResults != null) {
6533 r.pendingResults.remove(pir);
6534 }
6535 }
6536 }
6537
6538 @Override
6539 public IIntentSender getIntentSender(int type, String packageName,
6540 int callingUid, int userId, IBinder token, String resultWho,
6541 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6542 Bundle bOptions) {
6543 synchronized (mGlobalLock) {
6544 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6545 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6546 }
6547 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006548
6549 @Override
6550 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6551 synchronized (mGlobalLock) {
6552 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6553 if (r == null) {
6554 return null;
6555 }
6556 if (r.mServiceConnectionsHolder == null) {
6557 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6558 ActivityTaskManagerService.this, r);
6559 }
6560
6561 return r.mServiceConnectionsHolder;
6562 }
6563 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006564
6565 @Override
6566 public Intent getHomeIntent() {
6567 synchronized (mGlobalLock) {
6568 return ActivityTaskManagerService.this.getHomeIntent();
6569 }
6570 }
6571
6572 @Override
6573 public boolean startHomeActivity(int userId, String reason) {
6574 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006575 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006576 }
6577 }
6578
6579 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006580 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006581 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006582 synchronized (mGlobalLock) {
6583 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006584 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006585 }
Chilun8b1f1be2019-03-13 17:14:36 +08006586 }
6587
6588 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006589 public boolean startHomeOnAllDisplays(int userId, String reason) {
6590 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006591 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006592 }
6593 }
6594
Riddle Hsua0536432019-02-16 00:38:59 +08006595 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006596 @Override
6597 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006598 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006599 if (mFactoryTest == FACTORY_TEST_OFF) {
6600 return false;
6601 }
6602 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6603 && wpc.mName.equals(mTopComponent.getPackageName())) {
6604 return true;
6605 }
6606 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6607 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6608 }
6609 }
6610
6611 @Override
6612 public void updateTopComponentForFactoryTest() {
6613 synchronized (mGlobalLock) {
6614 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6615 return;
6616 }
6617 final ResolveInfo ri = mContext.getPackageManager()
6618 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6619 final CharSequence errorMsg;
6620 if (ri != null) {
6621 final ActivityInfo ai = ri.activityInfo;
6622 final ApplicationInfo app = ai.applicationInfo;
6623 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6624 mTopAction = Intent.ACTION_FACTORY_TEST;
6625 mTopData = null;
6626 mTopComponent = new ComponentName(app.packageName, ai.name);
6627 errorMsg = null;
6628 } else {
6629 errorMsg = mContext.getResources().getText(
6630 com.android.internal.R.string.factorytest_not_system);
6631 }
6632 } else {
6633 errorMsg = mContext.getResources().getText(
6634 com.android.internal.R.string.factorytest_no_action);
6635 }
6636 if (errorMsg == null) {
6637 return;
6638 }
6639
6640 mTopAction = null;
6641 mTopData = null;
6642 mTopComponent = null;
6643 mUiHandler.post(() -> {
6644 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6645 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006646 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006647 });
6648 }
6649 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006650
Riddle Hsua0536432019-02-16 00:38:59 +08006651 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006652 @Override
6653 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6654 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006655 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006656 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006657 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006658
6659 wpc.clearRecentTasks();
6660 wpc.clearActivities();
6661
6662 if (wpc.isInstrumenting()) {
6663 finishInstrumentationCallback.run();
6664 }
6665
Jorim Jaggid0752812018-10-16 16:07:20 +02006666 if (!restarting && hasVisibleActivities) {
6667 mWindowManager.deferSurfaceLayout();
6668 try {
6669 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6670 // If there was nothing to resume, and we are not already restarting
6671 // this process, but there is a visible activity that is hosted by the
6672 // process...then make sure all visible activities are running, taking
6673 // care of restarting this process.
6674 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6675 !PRESERVE_WINDOWS);
6676 }
6677 } finally {
6678 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006679 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006680 }
6681 }
6682 }
6683
6684 @Override
6685 public void closeSystemDialogs(String reason) {
6686 enforceNotIsolatedCaller("closeSystemDialogs");
6687
6688 final int pid = Binder.getCallingPid();
6689 final int uid = Binder.getCallingUid();
6690 final long origId = Binder.clearCallingIdentity();
6691 try {
6692 synchronized (mGlobalLock) {
6693 // Only allow this from foreground processes, so that background
6694 // applications can't abuse it to prevent system UI from being shown.
6695 if (uid >= FIRST_APPLICATION_UID) {
6696 final WindowProcessController proc = mPidMap.get(pid);
6697 if (!proc.isPerceptible()) {
6698 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6699 + " from background process " + proc);
6700 return;
6701 }
6702 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006703 mWindowManager.closeSystemDialogs(reason);
6704
Wale Ogunwaled32da472018-11-16 07:19:28 -08006705 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006707 // Call into AM outside the synchronized block.
6708 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 } finally {
6710 Binder.restoreCallingIdentity(origId);
6711 }
6712 }
6713
6714 @Override
6715 public void cleanupDisabledPackageComponents(
6716 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6717 synchronized (mGlobalLock) {
6718 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006719 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006720 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006721 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 mStackSupervisor.scheduleIdleLocked();
6723 }
6724
6725 // Clean-up disabled tasks
6726 getRecentTasks().cleanupDisabledPackageTasksLocked(
6727 packageName, disabledClasses, userId);
6728 }
6729 }
6730
6731 @Override
6732 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6733 int userId) {
6734 synchronized (mGlobalLock) {
6735
6736 boolean didSomething =
6737 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006738 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006739 null, doit, evenPersistent, userId);
6740 return didSomething;
6741 }
6742 }
6743
6744 @Override
6745 public void resumeTopActivities(boolean scheduleIdle) {
6746 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006747 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748 if (scheduleIdle) {
6749 mStackSupervisor.scheduleIdleLocked();
6750 }
6751 }
6752 }
6753
Riddle Hsua0536432019-02-16 00:38:59 +08006754 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006755 @Override
6756 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006757 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6759 }
6760 }
6761
Riddle Hsua0536432019-02-16 00:38:59 +08006762 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 @Override
6764 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006765 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006766 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 }
6768 }
6769
6770 @Override
6771 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6772 try {
6773 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6774 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6775 }
6776 } catch (RemoteException ex) {
6777 throw new SecurityException("Fail to check is caller a privileged app", ex);
6778 }
6779
6780 synchronized (mGlobalLock) {
6781 final long ident = Binder.clearCallingIdentity();
6782 try {
6783 if (mAmInternal.shouldConfirmCredentials(userId)) {
6784 if (mKeyguardController.isKeyguardLocked()) {
6785 // Showing launcher to avoid user entering credential twice.
6786 startHomeActivity(currentUserId, "notifyLockedProfile");
6787 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006788 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 }
6790 } finally {
6791 Binder.restoreCallingIdentity(ident);
6792 }
6793 }
6794 }
6795
6796 @Override
6797 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6798 mAmInternal.enforceCallingPermission(
6799 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6800
6801 synchronized (mGlobalLock) {
6802 final long ident = Binder.clearCallingIdentity();
6803 try {
6804 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6805 FLAG_ACTIVITY_TASK_ON_HOME);
6806 ActivityOptions activityOptions = options != null
6807 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006808 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006809 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006810 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006811 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006812 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6814 UserHandle.CURRENT);
6815 } finally {
6816 Binder.restoreCallingIdentity(ident);
6817 }
6818 }
6819 }
6820
6821 @Override
6822 public void writeActivitiesToProto(ProtoOutputStream proto) {
6823 synchronized (mGlobalLock) {
6824 // The output proto of "activity --proto activities"
6825 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006826 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006827 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6828 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 }
6830 }
6831
6832 @Override
6833 public void saveANRState(String reason) {
6834 synchronized (mGlobalLock) {
6835 final StringWriter sw = new StringWriter();
6836 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6837 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6838 if (reason != null) {
6839 pw.println(" Reason: " + reason);
6840 }
6841 pw.println();
6842 getActivityStartController().dump(pw, " ", null);
6843 pw.println();
6844 pw.println("-------------------------------------------------------------------------------");
6845 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6846 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6847 "" /* header */);
6848 pw.println();
6849 pw.close();
6850
6851 mLastANRState = sw.toString();
6852 }
6853 }
6854
6855 @Override
6856 public void clearSavedANRState() {
6857 synchronized (mGlobalLock) {
6858 mLastANRState = null;
6859 }
6860 }
6861
6862 @Override
6863 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6864 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6865 synchronized (mGlobalLock) {
6866 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6867 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6868 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6869 dumpLastANRLocked(pw);
6870 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6871 dumpLastANRTracesLocked(pw);
6872 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6873 dumpActivityStarterLocked(pw, dumpPackage);
6874 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6875 dumpActivityContainersLocked(pw);
6876 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6877 if (getRecentTasks() != null) {
6878 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6879 }
6880 }
6881 }
6882 }
6883
6884 @Override
6885 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6886 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6887 int wakefulness) {
6888 synchronized (mGlobalLock) {
6889 if (mHomeProcess != null && (dumpPackage == null
6890 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6891 if (needSep) {
6892 pw.println();
6893 needSep = false;
6894 }
6895 pw.println(" mHomeProcess: " + mHomeProcess);
6896 }
6897 if (mPreviousProcess != null && (dumpPackage == null
6898 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6899 if (needSep) {
6900 pw.println();
6901 needSep = false;
6902 }
6903 pw.println(" mPreviousProcess: " + mPreviousProcess);
6904 }
6905 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6906 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6907 StringBuilder sb = new StringBuilder(128);
6908 sb.append(" mPreviousProcessVisibleTime: ");
6909 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6910 pw.println(sb);
6911 }
6912 if (mHeavyWeightProcess != null && (dumpPackage == null
6913 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6914 if (needSep) {
6915 pw.println();
6916 needSep = false;
6917 }
6918 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6919 }
6920 if (dumpPackage == null) {
6921 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006922 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 }
6924 if (dumpAll) {
6925 if (dumpPackage == null) {
6926 pw.println(" mConfigWillChange: "
6927 + getTopDisplayFocusedStack().mConfigWillChange);
6928 }
6929 if (mCompatModePackages.getPackages().size() > 0) {
6930 boolean printed = false;
6931 for (Map.Entry<String, Integer> entry
6932 : mCompatModePackages.getPackages().entrySet()) {
6933 String pkg = entry.getKey();
6934 int mode = entry.getValue();
6935 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6936 continue;
6937 }
6938 if (!printed) {
6939 pw.println(" mScreenCompatPackages:");
6940 printed = true;
6941 }
6942 pw.println(" " + pkg + ": " + mode);
6943 }
6944 }
6945 }
6946
6947 if (dumpPackage == null) {
6948 pw.println(" mWakefulness="
6949 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006950 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006951 if (mRunningVoice != null) {
6952 pw.println(" mRunningVoice=" + mRunningVoice);
6953 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6954 }
6955 pw.println(" mSleeping=" + mSleeping);
6956 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6957 pw.println(" mVrController=" + mVrController);
6958 }
6959 if (mCurAppTimeTracker != null) {
6960 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6961 }
6962 if (mAllowAppSwitchUids.size() > 0) {
6963 boolean printed = false;
6964 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6965 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6966 for (int j = 0; j < types.size(); j++) {
6967 if (dumpPackage == null ||
6968 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6969 if (needSep) {
6970 pw.println();
6971 needSep = false;
6972 }
6973 if (!printed) {
6974 pw.println(" mAllowAppSwitchUids:");
6975 printed = true;
6976 }
6977 pw.print(" User ");
6978 pw.print(mAllowAppSwitchUids.keyAt(i));
6979 pw.print(": Type ");
6980 pw.print(types.keyAt(j));
6981 pw.print(" = ");
6982 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6983 pw.println();
6984 }
6985 }
6986 }
6987 }
6988 if (dumpPackage == null) {
6989 if (mController != null) {
6990 pw.println(" mController=" + mController
6991 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6992 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006993 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6994 pw.println(" mLaunchingActivityWakeLock="
6995 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006996 }
6997
6998 return needSep;
6999 }
7000 }
7001
7002 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007003 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7004 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007005 synchronized (mGlobalLock) {
7006 if (dumpPackage == null) {
7007 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7008 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007009 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7010 if (mRunningVoice != null) {
7011 final long vrToken = proto.start(
7012 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7013 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7014 mRunningVoice.toString());
7015 mVoiceWakeLock.writeToProto(
7016 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7017 proto.end(vrToken);
7018 }
7019 mVrController.writeToProto(proto,
7020 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007021 if (mController != null) {
7022 final long token = proto.start(CONTROLLER);
7023 proto.write(CONTROLLER, mController.toString());
7024 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7025 proto.end(token);
7026 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007027 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7028 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7029 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 }
7031
7032 if (mHomeProcess != null && (dumpPackage == null
7033 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007034 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007035 }
7036
7037 if (mPreviousProcess != null && (dumpPackage == null
7038 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007039 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7041 }
7042
7043 if (mHeavyWeightProcess != null && (dumpPackage == null
7044 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007045 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007046 }
7047
7048 for (Map.Entry<String, Integer> entry
7049 : mCompatModePackages.getPackages().entrySet()) {
7050 String pkg = entry.getKey();
7051 int mode = entry.getValue();
7052 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7053 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7054 proto.write(PACKAGE, pkg);
7055 proto.write(MODE, mode);
7056 proto.end(compatToken);
7057 }
7058 }
7059
7060 if (mCurAppTimeTracker != null) {
7061 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7062 }
7063
7064 }
7065 }
7066
7067 @Override
7068 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7069 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7070 boolean dumpFocusedStackOnly) {
7071 synchronized (mGlobalLock) {
7072 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7073 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7074 }
7075 }
7076
7077 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007078 public void dumpForOom(PrintWriter pw) {
7079 synchronized (mGlobalLock) {
7080 pw.println(" mHomeProcess: " + mHomeProcess);
7081 pw.println(" mPreviousProcess: " + mPreviousProcess);
7082 if (mHeavyWeightProcess != null) {
7083 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7084 }
7085 }
7086 }
7087
7088 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 public boolean canGcNow() {
7090 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007091 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007092 }
7093 }
7094
Riddle Hsua0536432019-02-16 00:38:59 +08007095 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007096 @Override
7097 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007098 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007099 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 return top != null ? top.app : null;
7101 }
7102 }
7103
Riddle Hsua0536432019-02-16 00:38:59 +08007104 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007105 @Override
7106 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007107 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007108 if (mRootActivityContainer != null) {
7109 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 }
7111 }
7112 }
7113
7114 @Override
7115 public void scheduleDestroyAllActivities(String reason) {
7116 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007117 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007118 }
7119 }
7120
7121 @Override
7122 public void removeUser(int userId) {
7123 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007124 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007125 }
7126 }
7127
7128 @Override
7129 public boolean switchUser(int userId, UserState userState) {
7130 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007131 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007132 }
7133 }
7134
7135 @Override
7136 public void onHandleAppCrash(WindowProcessController wpc) {
7137 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007138 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007139 }
7140 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007141
7142 @Override
7143 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7144 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007145 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007146 }
7147 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007148
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 onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007152 mActiveUids.onUidActive(uid, procState);
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 onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007158 mActiveUids.onUidInactive(uid);
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007164 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007165 }
7166
Riddle Hsua0536432019-02-16 00:38:59 +08007167 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007168 @Override
7169 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007170 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007171 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007172
7173 @Override
7174 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007175 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007176 mPendingTempWhitelist.put(uid, tag);
7177 }
7178 }
7179
7180 @Override
7181 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007182 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007183 mPendingTempWhitelist.remove(uid);
7184 }
7185 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007186
7187 @Override
7188 public boolean handleAppCrashInActivityController(String processName, int pid,
7189 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7190 Runnable killCrashingAppCallback) {
7191 synchronized (mGlobalLock) {
7192 if (mController == null) {
7193 return false;
7194 }
7195
7196 try {
7197 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7198 stackTrace)) {
7199 killCrashingAppCallback.run();
7200 return true;
7201 }
7202 } catch (RemoteException e) {
7203 mController = null;
7204 Watchdog.getInstance().setActivityController(null);
7205 }
7206 return false;
7207 }
7208 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007209
7210 @Override
7211 public void removeRecentTasksByPackageName(String packageName, int userId) {
7212 synchronized (mGlobalLock) {
7213 mRecentTasks.removeTasksByPackageName(packageName, userId);
7214 }
7215 }
7216
7217 @Override
7218 public void cleanupRecentTasksForUser(int userId) {
7219 synchronized (mGlobalLock) {
7220 mRecentTasks.cleanupLocked(userId);
7221 }
7222 }
7223
7224 @Override
7225 public void loadRecentTasksForUser(int userId) {
7226 synchronized (mGlobalLock) {
7227 mRecentTasks.loadUserRecentsLocked(userId);
7228 }
7229 }
7230
7231 @Override
7232 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7233 synchronized (mGlobalLock) {
7234 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7235 }
7236 }
7237
7238 @Override
7239 public void flushRecentTasks() {
7240 mRecentTasks.flush();
7241 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007242
7243 @Override
7244 public WindowProcessController getHomeProcess() {
7245 synchronized (mGlobalLock) {
7246 return mHomeProcess;
7247 }
7248 }
7249
7250 @Override
7251 public WindowProcessController getPreviousProcess() {
7252 synchronized (mGlobalLock) {
7253 return mPreviousProcess;
7254 }
7255 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007256
7257 @Override
7258 public void clearLockedTasks(String reason) {
7259 synchronized (mGlobalLock) {
7260 getLockTaskController().clearLockedTasks(reason);
7261 }
7262 }
7263
7264 @Override
7265 public void updateUserConfiguration() {
7266 synchronized (mGlobalLock) {
7267 final Configuration configuration = new Configuration(getGlobalConfiguration());
7268 final int currentUserId = mAmInternal.getCurrentUserId();
7269 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7270 configuration, currentUserId, Settings.System.canWrite(mContext));
7271 updateConfigurationLocked(configuration, null /* starting */,
7272 false /* initLocale */, false /* persistent */, currentUserId,
7273 false /* deferResume */);
7274 }
7275 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007276
7277 @Override
7278 public boolean canShowErrorDialogs() {
7279 synchronized (mGlobalLock) {
7280 return mShowDialogs && !mSleeping && !mShuttingDown
7281 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7282 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7283 mAmInternal.getCurrentUserId())
7284 && !(UserManager.isDeviceInDemoMode(mContext)
7285 && mAmInternal.getCurrentUser().isDemo());
7286 }
7287 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007288
7289 @Override
7290 public void setProfileApp(String profileApp) {
7291 synchronized (mGlobalLock) {
7292 mProfileApp = profileApp;
7293 }
7294 }
7295
7296 @Override
7297 public void setProfileProc(WindowProcessController wpc) {
7298 synchronized (mGlobalLock) {
7299 mProfileProc = wpc;
7300 }
7301 }
7302
7303 @Override
7304 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7305 synchronized (mGlobalLock) {
7306 mProfilerInfo = profilerInfo;
7307 }
7308 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007309
7310 @Override
7311 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7312 synchronized (mGlobalLock) {
7313 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7314 }
7315 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007316
7317 @Override
7318 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7319 synchronized (mGlobalLock) {
7320 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7321 }
7322 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007323
7324 @Override
7325 public boolean isUidForeground(int uid) {
7326 synchronized (mGlobalLock) {
7327 return ActivityTaskManagerService.this.isUidForeground(uid);
7328 }
7329 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007330
7331 @Override
7332 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7333 synchronized (mGlobalLock) {
7334 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7335 }
7336 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007337
7338 @Override
7339 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007340 // Translate package names into UIDs
7341 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007342 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007343 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7344 if (uid >= 0) {
7345 result.add(uid);
7346 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007347 }
7348 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007349 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007350 }
7351 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007352 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007353}