blob: 9717757e71355c2ad6d33e3c5c982d5a802ed4c0 [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
Ricky Wai96f5c352019-04-10 18:40:17 +0100635 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000636
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
2283 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285
2286 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2287 synchronized (mGlobalLock) {
2288 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2289 false /* fromRecents */);
2290 }
2291 }
2292
2293 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2294 boolean fromRecents) {
2295
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002296 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 Binder.getCallingUid(), -1, -1, "Task to front")) {
2298 SafeActivityOptions.abort(options);
2299 return;
2300 }
2301 final long origId = Binder.clearCallingIdentity();
2302 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002303 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 if (task == null) {
2305 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002306 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 return;
2308 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002309 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002311 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 return;
2313 }
2314 ActivityOptions realOptions = options != null
2315 ? options.getOptions(mStackSupervisor)
2316 : null;
2317 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2318 false /* forceNonResizable */);
2319
2320 final ActivityRecord topActivity = task.getTopActivity();
2321 if (topActivity != null) {
2322
2323 // We are reshowing a task, use a starting window to hide the initial draw delay
2324 // so the transition can start earlier.
2325 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2326 true /* taskSwitch */, fromRecents);
2327 }
2328 } finally {
2329 Binder.restoreCallingIdentity(origId);
2330 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002331 }
2332
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002333 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2334 int callingPid, int callingUid, String name) {
2335 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2336 return true;
2337 }
2338
2339 if (getRecentTasks().isCallerRecents(sourceUid)) {
2340 return true;
2341 }
2342
2343 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2344 if (perm == PackageManager.PERMISSION_GRANTED) {
2345 return true;
2346 }
2347 if (checkAllowAppSwitchUid(sourceUid)) {
2348 return true;
2349 }
2350
2351 // If the actual IPC caller is different from the logical source, then
2352 // also see if they are allowed to control app switches.
2353 if (callingUid != -1 && callingUid != sourceUid) {
2354 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2355 if (perm == PackageManager.PERMISSION_GRANTED) {
2356 return true;
2357 }
2358 if (checkAllowAppSwitchUid(callingUid)) {
2359 return true;
2360 }
2361 }
2362
2363 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2364 return false;
2365 }
2366
2367 private boolean checkAllowAppSwitchUid(int uid) {
2368 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2369 if (types != null) {
2370 for (int i = types.size() - 1; i >= 0; i--) {
2371 if (types.valueAt(i).intValue() == uid) {
2372 return true;
2373 }
2374 }
2375 }
2376 return false;
2377 }
2378
2379 @Override
2380 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2381 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2382 "setActivityController()");
2383 synchronized (mGlobalLock) {
2384 mController = controller;
2385 mControllerIsAMonkey = imAMonkey;
2386 Watchdog.getInstance().setActivityController(controller);
2387 }
2388 }
2389
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002390 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002391 synchronized (mGlobalLock) {
2392 return mController != null && mControllerIsAMonkey;
2393 }
2394 }
2395
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 @Override
2397 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2398 synchronized (mGlobalLock) {
2399 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2400 }
2401 }
2402
2403 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002404 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2405 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2406 }
2407
2408 @Override
2409 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2410 @WindowConfiguration.ActivityType int ignoreActivityType,
2411 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2412 final int callingUid = Binder.getCallingUid();
2413 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2414
2415 synchronized (mGlobalLock) {
2416 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2417
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002418 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002419 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002420 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002421 ignoreWindowingMode, callingUid, allowed);
2422 }
2423
2424 return list;
2425 }
2426
2427 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002428 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2429 synchronized (mGlobalLock) {
2430 final long origId = Binder.clearCallingIdentity();
2431 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2432 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002433 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002434 }
2435 Binder.restoreCallingIdentity(origId);
2436 }
2437 }
2438
2439 @Override
2440 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002441 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002442 ActivityStack stack = ActivityRecord.getStackLocked(token);
2443 if (stack != null) {
2444 return stack.willActivityBeVisibleLocked(token);
2445 }
2446 return false;
2447 }
2448 }
2449
2450 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002451 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002452 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002453 synchronized (mGlobalLock) {
2454 final long ident = Binder.clearCallingIdentity();
2455 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002456 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002457 if (task == null) {
2458 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2459 return;
2460 }
2461
2462 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2463 + " to stackId=" + stackId + " toTop=" + toTop);
2464
Wale Ogunwaled32da472018-11-16 07:19:28 -08002465 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002466 if (stack == null) {
2467 throw new IllegalStateException(
2468 "moveTaskToStack: No stack for stackId=" + stackId);
2469 }
2470 if (!stack.isActivityTypeStandardOrUndefined()) {
2471 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2472 + taskId + " to stack " + stackId);
2473 }
2474 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002475 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002476 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2477 }
2478 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2479 "moveTaskToStack");
2480 } finally {
2481 Binder.restoreCallingIdentity(ident);
2482 }
2483 }
2484 }
2485
2486 @Override
2487 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2488 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002489 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002490
2491 final long ident = Binder.clearCallingIdentity();
2492 try {
2493 synchronized (mGlobalLock) {
2494 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002495 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002496 if (stack == null) {
2497 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2498 return;
2499 }
2500 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2501 throw new IllegalArgumentException("Stack: " + stackId
2502 + " doesn't support animated resize.");
2503 }
2504 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2505 animationDuration, false /* fromFullscreen */);
2506 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002507 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 if (stack == null) {
2509 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2510 return;
2511 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002512 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002513 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2514 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2515 }
2516 }
2517 } finally {
2518 Binder.restoreCallingIdentity(ident);
2519 }
2520 }
2521
wilsonshih5c4cf522019-01-25 09:03:47 +08002522 @Override
2523 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2524 int animationDuration) {
2525 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2526
2527 final long ident = Binder.clearCallingIdentity();
2528 try {
2529 synchronized (mGlobalLock) {
2530 if (xOffset == 0 && yOffset == 0) {
2531 return;
2532 }
2533 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2534 if (stack == null) {
2535 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2536 return;
2537 }
2538 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2539 throw new IllegalArgumentException("Stack: " + stackId
2540 + " doesn't support animated resize.");
2541 }
2542 final Rect destBounds = new Rect();
2543 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002544 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002545 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2546 return;
2547 }
2548 destBounds.offset(xOffset, yOffset);
2549 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2550 animationDuration, false /* fromFullscreen */);
2551 }
2552 } finally {
2553 Binder.restoreCallingIdentity(ident);
2554 }
2555 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002556 /**
2557 * Moves the specified task to the primary-split-screen stack.
2558 *
2559 * @param taskId Id of task to move.
2560 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2561 * exist already. See
2562 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2563 * and
2564 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2565 * @param toTop If the task and stack should be moved to the top.
2566 * @param animate Whether we should play an animation for the moving the task.
2567 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2568 * stack. Pass {@code null} to use default bounds.
2569 * @param showRecents If the recents activity should be shown on the other side of the task
2570 * going into split-screen mode.
2571 */
2572 @Override
2573 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2574 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002575 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576 "setTaskWindowingModeSplitScreenPrimary()");
2577 synchronized (mGlobalLock) {
2578 final long ident = Binder.clearCallingIdentity();
2579 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002580 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002581 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002582 if (task == null) {
2583 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2584 return false;
2585 }
2586 if (DEBUG_STACK) Slog.d(TAG_STACK,
2587 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2588 + " to createMode=" + createMode + " toTop=" + toTop);
2589 if (!task.isActivityTypeStandardOrUndefined()) {
2590 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2591 + " non-standard task " + taskId + " to split-screen windowing mode");
2592 }
2593
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002594 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 final int windowingMode = task.getWindowingMode();
2596 final ActivityStack stack = task.getStack();
2597 if (toTop) {
2598 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2599 }
2600 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002601 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2602 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002603 return windowingMode != task.getWindowingMode();
2604 } finally {
2605 Binder.restoreCallingIdentity(ident);
2606 }
2607 }
2608 }
2609
2610 /**
2611 * Removes stacks in the input windowing modes from the system if they are of activity type
2612 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2613 */
2614 @Override
2615 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002616 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 "removeStacksInWindowingModes()");
2618
2619 synchronized (mGlobalLock) {
2620 final long ident = Binder.clearCallingIdentity();
2621 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002622 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002623 } finally {
2624 Binder.restoreCallingIdentity(ident);
2625 }
2626 }
2627 }
2628
2629 @Override
2630 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002631 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002632 "removeStacksWithActivityTypes()");
2633
2634 synchronized (mGlobalLock) {
2635 final long ident = Binder.clearCallingIdentity();
2636 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002637 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 } finally {
2639 Binder.restoreCallingIdentity(ident);
2640 }
2641 }
2642 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002643
2644 @Override
2645 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2646 int userId) {
2647 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002648 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2649 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002650 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002651 final boolean detailed = checkGetTasksPermission(
2652 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2653 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 == PackageManager.PERMISSION_GRANTED;
2655
2656 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002657 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002658 callingUid);
2659 }
2660 }
2661
2662 @Override
2663 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002664 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 long ident = Binder.clearCallingIdentity();
2666 try {
2667 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002668 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002669 }
2670 } finally {
2671 Binder.restoreCallingIdentity(ident);
2672 }
2673 }
2674
2675 @Override
2676 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002677 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 long ident = Binder.clearCallingIdentity();
2679 try {
2680 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002681 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 }
2683 } finally {
2684 Binder.restoreCallingIdentity(ident);
2685 }
2686 }
2687
2688 @Override
2689 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002690 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002691 final long callingUid = Binder.getCallingUid();
2692 final long origId = Binder.clearCallingIdentity();
2693 try {
2694 synchronized (mGlobalLock) {
2695 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002696 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002697 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2698 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2699 }
2700 } finally {
2701 Binder.restoreCallingIdentity(origId);
2702 }
2703 }
2704
2705 @Override
2706 public void startLockTaskModeByToken(IBinder token) {
2707 synchronized (mGlobalLock) {
2708 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2709 if (r == null) {
2710 return;
2711 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002712 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713 }
2714 }
2715
2716 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002717 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002718 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002719 // This makes inner call to look as if it was initiated by system.
2720 long ident = Binder.clearCallingIdentity();
2721 try {
2722 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002723 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002724 MATCH_TASK_IN_STACKS_ONLY);
2725 if (task == null) {
2726 return;
2727 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002728
2729 // When starting lock task mode the stack must be in front and focused
2730 task.getStack().moveToFront("startSystemLockTaskMode");
2731 startLockTaskModeLocked(task, true /* isSystemCaller */);
2732 }
2733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737
2738 @Override
2739 public void stopLockTaskModeByToken(IBinder token) {
2740 synchronized (mGlobalLock) {
2741 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2742 if (r == null) {
2743 return;
2744 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002745 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002746 }
2747 }
2748
2749 /**
2750 * This API should be called by SystemUI only when user perform certain action to dismiss
2751 * lock task mode. We should only dismiss pinned lock task mode in this case.
2752 */
2753 @Override
2754 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002755 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2757 }
2758
2759 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2760 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2761 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2762 return;
2763 }
2764
Wale Ogunwaled32da472018-11-16 07:19:28 -08002765 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 if (stack == null || task != stack.topTask()) {
2767 throw new IllegalArgumentException("Invalid task, not in foreground");
2768 }
2769
2770 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2771 // system or a specific app.
2772 // * System-initiated requests will only start the pinned mode (screen pinning)
2773 // * App-initiated requests
2774 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2775 // - will start the pinned mode, otherwise
2776 final int callingUid = Binder.getCallingUid();
2777 long ident = Binder.clearCallingIdentity();
2778 try {
2779 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002780 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002781
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002782 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 } finally {
2784 Binder.restoreCallingIdentity(ident);
2785 }
2786 }
2787
2788 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2789 final int callingUid = Binder.getCallingUid();
2790 long ident = Binder.clearCallingIdentity();
2791 try {
2792 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002793 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 }
2795 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2796 // task and jumping straight into a call in the case of emergency call back.
2797 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2798 if (tm != null) {
2799 tm.showInCallScreen(false);
2800 }
2801 } finally {
2802 Binder.restoreCallingIdentity(ident);
2803 }
2804 }
2805
2806 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002807 public void updateLockTaskPackages(int userId, String[] packages) {
2808 final int callingUid = Binder.getCallingUid();
2809 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2810 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2811 "updateLockTaskPackages()");
2812 }
2813 synchronized (this) {
2814 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2815 + Arrays.toString(packages));
2816 getLockTaskController().updateLockTaskPackages(userId, packages);
2817 }
2818 }
2819
2820 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 public boolean isInLockTaskMode() {
2822 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2823 }
2824
2825 @Override
2826 public int getLockTaskModeState() {
2827 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002828 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 }
2830 }
2831
2832 @Override
2833 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2834 synchronized (mGlobalLock) {
2835 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2836 if (r != null) {
2837 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002838 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002840 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 }
2842 }
2843 }
2844
2845 @Override
2846 public Bundle getActivityOptions(IBinder token) {
2847 final long origId = Binder.clearCallingIdentity();
2848 try {
2849 synchronized (mGlobalLock) {
2850 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2851 if (r != null) {
2852 final ActivityOptions activityOptions = r.takeOptionsLocked();
2853 return activityOptions == null ? null : activityOptions.toBundle();
2854 }
2855 return null;
2856 }
2857 } finally {
2858 Binder.restoreCallingIdentity(origId);
2859 }
2860 }
2861
2862 @Override
2863 public List<IBinder> getAppTasks(String callingPackage) {
2864 int callingUid = Binder.getCallingUid();
2865 long ident = Binder.clearCallingIdentity();
2866 try {
2867 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002868 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 }
2870 } finally {
2871 Binder.restoreCallingIdentity(ident);
2872 }
2873 }
2874
2875 @Override
2876 public void finishVoiceTask(IVoiceInteractionSession session) {
2877 synchronized (mGlobalLock) {
2878 final long origId = Binder.clearCallingIdentity();
2879 try {
2880 // TODO: VI Consider treating local voice interactions and voice tasks
2881 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002882 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 } finally {
2884 Binder.restoreCallingIdentity(origId);
2885 }
2886 }
2887
2888 }
2889
2890 @Override
2891 public boolean isTopOfTask(IBinder token) {
2892 synchronized (mGlobalLock) {
2893 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002894 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895 }
2896 }
2897
2898 @Override
2899 public void notifyLaunchTaskBehindComplete(IBinder token) {
2900 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2901 }
2902
2903 @Override
2904 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002905 mH.post(() -> {
2906 synchronized (mGlobalLock) {
2907 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002908 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002909 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002910 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002911 } catch (RemoteException e) {
2912 }
2913 }
2914 }
2915
2916 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 }
2918
2919 /** Called from an app when assist data is ready. */
2920 @Override
2921 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2922 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002923 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 synchronized (pae) {
2925 pae.result = extras;
2926 pae.structure = structure;
2927 pae.content = content;
2928 if (referrer != null) {
2929 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2930 }
2931 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002932 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002933 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2934 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 structure.setHomeActivity(pae.isHome);
2936 }
2937 pae.haveResult = true;
2938 pae.notifyAll();
2939 if (pae.intent == null && pae.receiver == null) {
2940 // Caller is just waiting for the result.
2941 return;
2942 }
2943 }
2944 // We are now ready to launch the assist activity.
2945 IAssistDataReceiver sendReceiver = null;
2946 Bundle sendBundle = null;
2947 synchronized (mGlobalLock) {
2948 buildAssistBundleLocked(pae, extras);
2949 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002950 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 if (!exists) {
2952 // Timed out.
2953 return;
2954 }
2955
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002956 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 // Caller wants result sent back to them.
2958 sendBundle = new Bundle();
2959 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2960 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2961 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2962 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2963 }
2964 }
2965 if (sendReceiver != null) {
2966 try {
2967 sendReceiver.onHandleAssistData(sendBundle);
2968 } catch (RemoteException e) {
2969 }
2970 return;
2971 }
2972
2973 final long ident = Binder.clearCallingIdentity();
2974 try {
2975 if (TextUtils.equals(pae.intent.getAction(),
2976 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2977 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01002978
2979 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 } else {
2981 pae.intent.replaceExtras(pae.extras);
2982 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2983 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2984 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002985 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986
2987 try {
2988 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2989 } catch (ActivityNotFoundException e) {
2990 Slog.w(TAG, "No activity to handle assist action.", e);
2991 }
2992 }
2993 } finally {
2994 Binder.restoreCallingIdentity(ident);
2995 }
2996 }
2997
Marvin Ramin830d4e32019-03-12 13:16:58 +01002998 /**
2999 * Workaround for historical API which starts the Assist service with a non-foreground
3000 * {@code startService()} call.
3001 */
3002 private void startVoiceInteractionServiceAsUser(
3003 Intent intent, int userHandle, String reason) {
3004 // Resolve the intent to find out which package we need to whitelist.
3005 ResolveInfo resolveInfo =
3006 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3007 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3008 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3009 return;
3010 }
3011 intent.setPackage(resolveInfo.serviceInfo.packageName);
3012
3013 // Whitelist background services temporarily.
3014 LocalServices.getService(DeviceIdleController.LocalService.class)
3015 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3016 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3017
3018 // Finally, try to start the service.
3019 try {
3020 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3021 } catch (RuntimeException e) {
3022 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3023 }
3024 }
3025
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003026 @Override
3027 public int addAppTask(IBinder activityToken, Intent intent,
3028 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3029 final int callingUid = Binder.getCallingUid();
3030 final long callingIdent = Binder.clearCallingIdentity();
3031
3032 try {
3033 synchronized (mGlobalLock) {
3034 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3035 if (r == null) {
3036 throw new IllegalArgumentException("Activity does not exist; token="
3037 + activityToken);
3038 }
3039 ComponentName comp = intent.getComponent();
3040 if (comp == null) {
3041 throw new IllegalArgumentException("Intent " + intent
3042 + " must specify explicit component");
3043 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003044 if (thumbnail.getWidth() != mThumbnailWidth
3045 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 throw new IllegalArgumentException("Bad thumbnail size: got "
3047 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003048 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 }
3050 if (intent.getSelector() != null) {
3051 intent.setSelector(null);
3052 }
3053 if (intent.getSourceBounds() != null) {
3054 intent.setSourceBounds(null);
3055 }
3056 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3057 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3058 // The caller has added this as an auto-remove task... that makes no
3059 // sense, so turn off auto-remove.
3060 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3061 }
3062 }
3063 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3064 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3065 if (ainfo.applicationInfo.uid != callingUid) {
3066 throw new SecurityException(
3067 "Can't add task for another application: target uid="
3068 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3069 }
3070
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003071 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003073 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003074 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003075 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 // The app has too many tasks already and we can't add any more
3077 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3078 return INVALID_TASK_ID;
3079 }
3080 task.lastTaskDescription.copyFrom(description);
3081
3082 // TODO: Send the thumbnail to WM to store it.
3083
3084 return task.taskId;
3085 }
3086 } finally {
3087 Binder.restoreCallingIdentity(callingIdent);
3088 }
3089 }
3090
3091 @Override
3092 public Point getAppTaskThumbnailSize() {
3093 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003094 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 }
3096 }
3097
3098 @Override
3099 public void setTaskResizeable(int taskId, int resizeableMode) {
3100 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003101 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3103 if (task == null) {
3104 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3105 return;
3106 }
3107 task.setResizeMode(resizeableMode);
3108 }
3109 }
3110
3111 @Override
3112 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003113 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 long ident = Binder.clearCallingIdentity();
3115 try {
3116 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003117 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003118 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 if (task == null) {
3120 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3121 return;
3122 }
3123 // Place the task in the right stack if it isn't there already based on
3124 // the requested bounds.
3125 // The stack transition logic is:
3126 // - a null bounds on a freeform task moves that task to fullscreen
3127 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3128 // that task to freeform
3129 // - otherwise the task is not moved
3130 ActivityStack stack = task.getStack();
3131 if (!task.getWindowConfiguration().canResizeTask()) {
3132 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3133 }
3134 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3135 stack = stack.getDisplay().getOrCreateStack(
3136 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3137 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3138 stack = stack.getDisplay().getOrCreateStack(
3139 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3140 }
3141
3142 // Reparent the task to the right stack if necessary
3143 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3144 if (stack != task.getStack()) {
3145 // Defer resume until the task is resized below
3146 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3147 DEFER_RESUME, "resizeTask");
3148 preserveWindow = false;
3149 }
3150
3151 // After reparenting (which only resizes the task to the stack bounds), resize the
3152 // task to the actual bounds provided
3153 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3154 }
3155 } finally {
3156 Binder.restoreCallingIdentity(ident);
3157 }
3158 }
3159
3160 @Override
3161 public boolean releaseActivityInstance(IBinder token) {
3162 synchronized (mGlobalLock) {
3163 final long origId = Binder.clearCallingIdentity();
3164 try {
3165 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3166 if (r == null) {
3167 return false;
3168 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003169 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 } finally {
3171 Binder.restoreCallingIdentity(origId);
3172 }
3173 }
3174 }
3175
3176 @Override
3177 public void releaseSomeActivities(IApplicationThread appInt) {
3178 synchronized (mGlobalLock) {
3179 final long origId = Binder.clearCallingIdentity();
3180 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003181 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003182 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003183 } finally {
3184 Binder.restoreCallingIdentity(origId);
3185 }
3186 }
3187 }
3188
3189 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003190 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003191 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 != PackageManager.PERMISSION_GRANTED) {
3193 throw new SecurityException("Requires permission "
3194 + android.Manifest.permission.DEVICE_POWER);
3195 }
3196
3197 synchronized (mGlobalLock) {
3198 long ident = Binder.clearCallingIdentity();
3199 if (mKeyguardShown != keyguardShowing) {
3200 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003201 final Message msg = PooledLambda.obtainMessage(
3202 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3203 keyguardShowing);
3204 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 }
3206 try {
wilsonshih177261f2019-02-22 12:02:18 +08003207 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 } finally {
3209 Binder.restoreCallingIdentity(ident);
3210 }
3211 }
3212
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003213 mH.post(() -> {
3214 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3215 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3216 }
3217 });
3218 }
3219
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003220 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003221 mH.post(() -> {
3222 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3223 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3224 }
3225 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 }
3227
3228 @Override
3229 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003230 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3231 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003232
3233 final File passedIconFile = new File(filePath);
3234 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3235 passedIconFile.getName());
3236 if (!legitIconFile.getPath().equals(filePath)
3237 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3238 throw new IllegalArgumentException("Bad file path: " + filePath
3239 + " passed for userId " + userId);
3240 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003241 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 }
3243
3244 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3247 final ActivityOptions activityOptions = safeOptions != null
3248 ? safeOptions.getOptions(mStackSupervisor)
3249 : null;
3250 if (activityOptions == null
3251 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3252 || activityOptions.getCustomInPlaceResId() == 0) {
3253 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3254 "with valid animation");
3255 }
lumark588a3e82018-07-20 18:53:54 +08003256 // Get top display of front most application.
3257 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3258 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003259 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3260 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3261 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003262 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003263 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003264 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003265 }
3266
3267 @Override
3268 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003269 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003270 synchronized (mGlobalLock) {
3271 final long ident = Binder.clearCallingIdentity();
3272 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003273 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003274 if (stack == null) {
3275 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3276 return;
3277 }
3278 if (!stack.isActivityTypeStandardOrUndefined()) {
3279 throw new IllegalArgumentException(
3280 "Removing non-standard stack is not allowed.");
3281 }
3282 mStackSupervisor.removeStack(stack);
3283 } finally {
3284 Binder.restoreCallingIdentity(ident);
3285 }
3286 }
3287 }
3288
3289 @Override
3290 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003291 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003292
3293 synchronized (mGlobalLock) {
3294 final long ident = Binder.clearCallingIdentity();
3295 try {
3296 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3297 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003298 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 } finally {
3300 Binder.restoreCallingIdentity(ident);
3301 }
3302 }
3303 }
3304
3305 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003306 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003307 synchronized (mGlobalLock) {
3308 long ident = Binder.clearCallingIdentity();
3309 try {
3310 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3311 if (r == null) {
3312 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003313 "toggleFreeformWindowingMode: No activity record matching token="
3314 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 }
3316
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003317 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003318 if (stack == null) {
3319 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3320 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 }
3322
Yunfan Chend967af82019-01-17 18:30:18 +09003323 if (!stack.inFreeformWindowingMode()
3324 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3325 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3326 + "toggle between fullscreen and freeform.");
3327 }
3328
3329 if (stack.inFreeformWindowingMode()) {
3330 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3331 } else {
3332 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3333 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 } finally {
3335 Binder.restoreCallingIdentity(ident);
3336 }
3337 }
3338 }
3339
3340 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3341 @Override
3342 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003343 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003345 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 }
3347
3348 /** Unregister a task stack listener so that it stops receiving callbacks. */
3349 @Override
3350 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003351 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003353 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 }
3355
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 @Override
3357 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3358 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3359 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3360 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3361 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3362 }
3363
3364 @Override
3365 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3366 IBinder activityToken, int flags) {
3367 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3368 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3369 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3370 }
3371
3372 @Override
3373 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3374 Bundle args) {
3375 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3376 true /* focused */, true /* newSessionId */, userHandle, args,
3377 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3378 }
3379
3380 @Override
3381 public Bundle getAssistContextExtras(int requestType) {
3382 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3383 null, null, true /* focused */, true /* newSessionId */,
3384 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3385 if (pae == null) {
3386 return null;
3387 }
3388 synchronized (pae) {
3389 while (!pae.haveResult) {
3390 try {
3391 pae.wait();
3392 } catch (InterruptedException e) {
3393 }
3394 }
3395 }
3396 synchronized (mGlobalLock) {
3397 buildAssistBundleLocked(pae, pae.result);
3398 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 }
3401 return pae.extras;
3402 }
3403
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 /**
3405 * Binder IPC calls go through the public entry point.
3406 * This can be called with or without the global lock held.
3407 */
3408 private static int checkCallingPermission(String permission) {
3409 return checkPermission(
3410 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3411 }
3412
3413 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003414 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003415 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3416 mAmInternal.enforceCallingPermission(permission, func);
3417 }
3418 }
3419
3420 @VisibleForTesting
3421 int checkGetTasksPermission(String permission, int pid, int uid) {
3422 return checkPermission(permission, pid, uid);
3423 }
3424
3425 static int checkPermission(String permission, int pid, int uid) {
3426 if (permission == null) {
3427 return PackageManager.PERMISSION_DENIED;
3428 }
3429 return checkComponentPermission(permission, pid, uid, -1, true);
3430 }
3431
Wale Ogunwale214f3482018-10-04 11:00:47 -07003432 public static int checkComponentPermission(String permission, int pid, int uid,
3433 int owningUid, boolean exported) {
3434 return ActivityManagerService.checkComponentPermission(
3435 permission, pid, uid, owningUid, exported);
3436 }
3437
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003438 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3439 if (getRecentTasks().isCallerRecents(callingUid)) {
3440 // Always allow the recents component to get tasks
3441 return true;
3442 }
3443
3444 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3445 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3446 if (!allowed) {
3447 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3448 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3449 // Temporary compatibility: some existing apps on the system image may
3450 // still be requesting the old permission and not switched to the new
3451 // one; if so, we'll still allow them full access. This means we need
3452 // to see if they are holding the old permission and are a system app.
3453 try {
3454 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3455 allowed = true;
3456 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3457 + " is using old GET_TASKS but privileged; allowing");
3458 }
3459 } catch (RemoteException e) {
3460 }
3461 }
3462 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3463 + " does not hold REAL_GET_TASKS; limiting output");
3464 }
3465 return allowed;
3466 }
3467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3469 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3470 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3471 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003472 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 "enqueueAssistContext()");
3474
3475 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003476 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003477 if (activity == null) {
3478 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3479 return null;
3480 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003481 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3483 return null;
3484 }
3485 if (focused) {
3486 if (activityToken != null) {
3487 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3488 if (activity != caller) {
3489 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3490 + " is not current top " + activity);
3491 return null;
3492 }
3493 }
3494 } else {
3495 activity = ActivityRecord.forTokenLocked(activityToken);
3496 if (activity == null) {
3497 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3498 + " couldn't be found");
3499 return null;
3500 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003501 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3503 return null;
3504 }
3505 }
3506
3507 PendingAssistExtras pae;
3508 Bundle extras = new Bundle();
3509 if (args != null) {
3510 extras.putAll(args);
3511 }
3512 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003513 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003514
3515 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3516 userHandle);
3517 pae.isHome = activity.isActivityTypeHome();
3518
3519 // Increment the sessionId if necessary
3520 if (newSessionId) {
3521 mViSessionId++;
3522 }
3523 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003524 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3525 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 } catch (RemoteException e) {
3529 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3530 return null;
3531 }
3532 return pae;
3533 }
3534 }
3535
3536 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3537 if (result != null) {
3538 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3539 }
3540 if (pae.hint != null) {
3541 pae.extras.putBoolean(pae.hint, true);
3542 }
3543 }
3544
3545 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3546 IAssistDataReceiver receiver;
3547 synchronized (mGlobalLock) {
3548 mPendingAssistExtras.remove(pae);
3549 receiver = pae.receiver;
3550 }
3551 if (receiver != null) {
3552 // Caller wants result sent back to them.
3553 Bundle sendBundle = new Bundle();
3554 // At least return the receiver extras
3555 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3556 try {
3557 pae.receiver.onHandleAssistData(sendBundle);
3558 } catch (RemoteException e) {
3559 }
3560 }
3561 }
3562
3563 public class PendingAssistExtras extends Binder implements Runnable {
3564 public final ActivityRecord activity;
3565 public boolean isHome;
3566 public final Bundle extras;
3567 public final Intent intent;
3568 public final String hint;
3569 public final IAssistDataReceiver receiver;
3570 public final int userHandle;
3571 public boolean haveResult = false;
3572 public Bundle result = null;
3573 public AssistStructure structure = null;
3574 public AssistContent content = null;
3575 public Bundle receiverExtras;
3576
3577 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3578 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3579 int _userHandle) {
3580 activity = _activity;
3581 extras = _extras;
3582 intent = _intent;
3583 hint = _hint;
3584 receiver = _receiver;
3585 receiverExtras = _receiverExtras;
3586 userHandle = _userHandle;
3587 }
3588
3589 @Override
3590 public void run() {
3591 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3592 synchronized (this) {
3593 haveResult = true;
3594 notifyAll();
3595 }
3596 pendingAssistExtrasTimedOut(this);
3597 }
3598 }
3599
3600 @Override
3601 public boolean isAssistDataAllowedOnCurrentActivity() {
3602 int userId;
3603 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003604 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3606 return false;
3607 }
3608
3609 final ActivityRecord activity = focusedStack.getTopActivity();
3610 if (activity == null) {
3611 return false;
3612 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003613 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 }
3615 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3616 }
3617
3618 @Override
3619 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3620 long ident = Binder.clearCallingIdentity();
3621 try {
3622 synchronized (mGlobalLock) {
3623 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003624 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 if (top != caller) {
3626 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3627 + " is not current top " + top);
3628 return false;
3629 }
3630 if (!top.nowVisible) {
3631 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3632 + " is not visible");
3633 return false;
3634 }
3635 }
3636 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3637 token);
3638 } finally {
3639 Binder.restoreCallingIdentity(ident);
3640 }
3641 }
3642
3643 @Override
3644 public boolean isRootVoiceInteraction(IBinder token) {
3645 synchronized (mGlobalLock) {
3646 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3647 if (r == null) {
3648 return false;
3649 }
3650 return r.rootVoiceInteraction;
3651 }
3652 }
3653
Wale Ogunwalef6733932018-06-27 05:14:34 -07003654 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3655 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3656 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3657 if (activityToCallback == null) return;
3658 activityToCallback.setVoiceSessionLocked(voiceSession);
3659
3660 // Inform the activity
3661 try {
3662 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3663 voiceInteractor);
3664 long token = Binder.clearCallingIdentity();
3665 try {
3666 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3667 } finally {
3668 Binder.restoreCallingIdentity(token);
3669 }
3670 // TODO: VI Should we cache the activity so that it's easier to find later
3671 // rather than scan through all the stacks and activities?
3672 } catch (RemoteException re) {
3673 activityToCallback.clearVoiceSessionLocked();
3674 // TODO: VI Should this terminate the voice session?
3675 }
3676 }
3677
3678 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3679 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3680 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3681 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3682 boolean wasRunningVoice = mRunningVoice != null;
3683 mRunningVoice = session;
3684 if (!wasRunningVoice) {
3685 mVoiceWakeLock.acquire();
3686 updateSleepIfNeededLocked();
3687 }
3688 }
3689 }
3690
3691 void finishRunningVoiceLocked() {
3692 if (mRunningVoice != null) {
3693 mRunningVoice = null;
3694 mVoiceWakeLock.release();
3695 updateSleepIfNeededLocked();
3696 }
3697 }
3698
3699 @Override
3700 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3701 synchronized (mGlobalLock) {
3702 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3703 if (keepAwake) {
3704 mVoiceWakeLock.acquire();
3705 } else {
3706 mVoiceWakeLock.release();
3707 }
3708 }
3709 }
3710 }
3711
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003712 @Override
3713 public ComponentName getActivityClassForToken(IBinder token) {
3714 synchronized (mGlobalLock) {
3715 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3716 if (r == null) {
3717 return null;
3718 }
3719 return r.intent.getComponent();
3720 }
3721 }
3722
3723 @Override
3724 public String getPackageForToken(IBinder token) {
3725 synchronized (mGlobalLock) {
3726 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3727 if (r == null) {
3728 return null;
3729 }
3730 return r.packageName;
3731 }
3732 }
3733
3734 @Override
3735 public void showLockTaskEscapeMessage(IBinder token) {
3736 synchronized (mGlobalLock) {
3737 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3738 if (r == null) {
3739 return;
3740 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003741 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 }
3743 }
3744
3745 @Override
3746 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003747 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 final long token = Binder.clearCallingIdentity();
3749 try {
3750 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003751 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003752 }
3753 } finally {
3754 Binder.restoreCallingIdentity(token);
3755 }
3756 }
3757
3758 /**
3759 * Try to place task to provided position. The final position might be different depending on
3760 * current user and stacks state. The task will be moved to target stack if it's currently in
3761 * different stack.
3762 */
3763 @Override
3764 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003765 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003766 synchronized (mGlobalLock) {
3767 long ident = Binder.clearCallingIdentity();
3768 try {
3769 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3770 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003771 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003772 if (task == null) {
3773 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3774 + taskId);
3775 }
3776
Wale Ogunwaled32da472018-11-16 07:19:28 -08003777 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003778
3779 if (stack == null) {
3780 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3781 + stackId);
3782 }
3783 if (!stack.isActivityTypeStandardOrUndefined()) {
3784 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3785 + " the position of task " + taskId + " in/to non-standard stack");
3786 }
3787
3788 // TODO: Have the callers of this API call a separate reparent method if that is
3789 // what they intended to do vs. having this method also do reparenting.
3790 if (task.getStack() == stack) {
3791 // Change position in current stack.
3792 stack.positionChildAt(task, position);
3793 } else {
3794 // Reparent to new stack.
3795 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3796 !DEFER_RESUME, "positionTaskInStack");
3797 }
3798 } finally {
3799 Binder.restoreCallingIdentity(ident);
3800 }
3801 }
3802 }
3803
3804 @Override
3805 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3806 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3807 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3808 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3809 synchronized (mGlobalLock) {
3810 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3811 if (record == null) {
3812 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3813 + "found for: " + token);
3814 }
3815 record.setSizeConfigurations(horizontalSizeConfiguration,
3816 verticalSizeConfigurations, smallestSizeConfigurations);
3817 }
3818 }
3819
3820 /**
3821 * Dismisses split-screen multi-window mode.
3822 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3823 */
3824 @Override
3825 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003826 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3828 final long ident = Binder.clearCallingIdentity();
3829 try {
3830 synchronized (mGlobalLock) {
3831 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003832 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 if (stack == null) {
3834 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3835 return;
3836 }
3837
3838 if (toTop) {
3839 // Caller wants the current split-screen primary stack to be the top stack after
3840 // it goes fullscreen, so move it to the front.
3841 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003842 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 // In this case the current split-screen primary stack shouldn't be the top
3844 // stack after it goes fullscreen, but it current has focus, so we move the
3845 // focus to the top-most split-screen secondary stack next to it.
3846 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3847 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3848 if (otherStack != null) {
3849 otherStack.moveToFront("dismissSplitScreenMode_other");
3850 }
3851 }
3852
Evan Rosky10475742018-09-05 19:02:48 -07003853 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854 }
3855 } finally {
3856 Binder.restoreCallingIdentity(ident);
3857 }
3858 }
3859
3860 /**
3861 * Dismisses Pip
3862 * @param animate True if the dismissal should be animated.
3863 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3864 * default animation duration should be used.
3865 */
3866 @Override
3867 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003868 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003869 final long ident = Binder.clearCallingIdentity();
3870 try {
3871 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003872 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003873 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874 if (stack == null) {
3875 Slog.w(TAG, "dismissPip: pinned stack not found.");
3876 return;
3877 }
3878 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3879 throw new IllegalArgumentException("Stack: " + stack
3880 + " doesn't support animated resize.");
3881 }
3882 if (animate) {
3883 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3884 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3885 } else {
3886 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3887 }
3888 }
3889 } finally {
3890 Binder.restoreCallingIdentity(ident);
3891 }
3892 }
3893
3894 @Override
3895 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003896 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003897 synchronized (mGlobalLock) {
3898 mSuppressResizeConfigChanges = suppress;
3899 }
3900 }
3901
3902 /**
3903 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3904 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3905 * activity and clearing the task at the same time.
3906 */
3907 @Override
3908 // TODO: API should just be about changing windowing modes...
3909 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003910 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 "moveTasksToFullscreenStack()");
3912 synchronized (mGlobalLock) {
3913 final long origId = Binder.clearCallingIdentity();
3914 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003915 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 if (stack != null){
3917 if (!stack.isActivityTypeStandardOrUndefined()) {
3918 throw new IllegalArgumentException(
3919 "You can't move tasks from non-standard stacks.");
3920 }
3921 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3922 }
3923 } finally {
3924 Binder.restoreCallingIdentity(origId);
3925 }
3926 }
3927 }
3928
3929 /**
3930 * Moves the top activity in the input stackId to the pinned stack.
3931 *
3932 * @param stackId Id of stack to move the top activity to pinned stack.
3933 * @param bounds Bounds to use for pinned stack.
3934 *
3935 * @return True if the top activity of the input stack was successfully moved to the pinned
3936 * stack.
3937 */
3938 @Override
3939 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003940 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 "moveTopActivityToPinnedStack()");
3942 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003943 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3945 + "Device doesn't support picture-in-picture mode");
3946 }
3947
3948 long ident = Binder.clearCallingIdentity();
3949 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003950 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 } finally {
3952 Binder.restoreCallingIdentity(ident);
3953 }
3954 }
3955 }
3956
3957 @Override
3958 public boolean isInMultiWindowMode(IBinder token) {
3959 final long origId = Binder.clearCallingIdentity();
3960 try {
3961 synchronized (mGlobalLock) {
3962 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3963 if (r == null) {
3964 return false;
3965 }
3966 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3967 return r.inMultiWindowMode();
3968 }
3969 } finally {
3970 Binder.restoreCallingIdentity(origId);
3971 }
3972 }
3973
3974 @Override
3975 public boolean isInPictureInPictureMode(IBinder token) {
3976 final long origId = Binder.clearCallingIdentity();
3977 try {
3978 synchronized (mGlobalLock) {
3979 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3980 }
3981 } finally {
3982 Binder.restoreCallingIdentity(origId);
3983 }
3984 }
3985
3986 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003987 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3988 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 return false;
3990 }
3991
3992 // If we are animating to fullscreen then we have already dispatched the PIP mode
3993 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003994 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3995 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 }
3997
3998 @Override
3999 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4000 final long origId = Binder.clearCallingIdentity();
4001 try {
4002 synchronized (mGlobalLock) {
4003 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4004 "enterPictureInPictureMode", token, params);
4005
4006 // If the activity is already in picture in picture mode, then just return early
4007 if (isInPictureInPictureMode(r)) {
4008 return true;
4009 }
4010
4011 // Activity supports picture-in-picture, now check that we can enter PiP at this
4012 // point, if it is
4013 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4014 false /* beforeStopping */)) {
4015 return false;
4016 }
4017
4018 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004019 synchronized (mGlobalLock) {
4020 // Only update the saved args from the args that are set
4021 r.pictureInPictureArgs.copyOnlySet(params);
4022 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4023 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4024 // Adjust the source bounds by the insets for the transition down
4025 final Rect sourceBounds = new Rect(
4026 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004027 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004028 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004029 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004030 stack.setPictureInPictureAspectRatio(aspectRatio);
4031 stack.setPictureInPictureActions(actions);
4032 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4033 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4034 logPictureInPictureArgs(params);
4035 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 };
4037
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004038 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004039 // If the keyguard is showing or occluded, then try and dismiss it before
4040 // entering picture-in-picture (this will prompt the user to authenticate if the
4041 // device is currently locked).
4042 dismissKeyguard(token, new KeyguardDismissCallback() {
4043 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004044 public void onDismissSucceeded() {
4045 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 }
4047 }, null /* message */);
4048 } else {
4049 // Enter picture in picture immediately otherwise
4050 enterPipRunnable.run();
4051 }
4052 return true;
4053 }
4054 } finally {
4055 Binder.restoreCallingIdentity(origId);
4056 }
4057 }
4058
4059 @Override
4060 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4061 final long origId = Binder.clearCallingIdentity();
4062 try {
4063 synchronized (mGlobalLock) {
4064 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4065 "setPictureInPictureParams", token, params);
4066
4067 // Only update the saved args from the args that are set
4068 r.pictureInPictureArgs.copyOnlySet(params);
4069 if (r.inPinnedWindowingMode()) {
4070 // If the activity is already in picture-in-picture, update the pinned stack now
4071 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4072 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004073 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 if (!stack.isAnimatingBoundsToFullscreen()) {
4075 stack.setPictureInPictureAspectRatio(
4076 r.pictureInPictureArgs.getAspectRatio());
4077 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4078 }
4079 }
4080 logPictureInPictureArgs(params);
4081 }
4082 } finally {
4083 Binder.restoreCallingIdentity(origId);
4084 }
4085 }
4086
4087 @Override
4088 public int getMaxNumPictureInPictureActions(IBinder token) {
4089 // Currently, this is a static constant, but later, we may change this to be dependent on
4090 // the context of the activity
4091 return 3;
4092 }
4093
4094 private void logPictureInPictureArgs(PictureInPictureParams params) {
4095 if (params.hasSetActions()) {
4096 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4097 params.getActions().size());
4098 }
4099 if (params.hasSetAspectRatio()) {
4100 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4101 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4102 MetricsLogger.action(lm);
4103 }
4104 }
4105
4106 /**
4107 * Checks the state of the system and the activity associated with the given {@param token} to
4108 * verify that picture-in-picture is supported for that activity.
4109 *
4110 * @return the activity record for the given {@param token} if all the checks pass.
4111 */
4112 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4113 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 throw new IllegalStateException(caller
4116 + ": Device doesn't support picture-in-picture mode.");
4117 }
4118
4119 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4120 if (r == null) {
4121 throw new IllegalStateException(caller
4122 + ": Can't find activity for token=" + token);
4123 }
4124
4125 if (!r.supportsPictureInPicture()) {
4126 throw new IllegalStateException(caller
4127 + ": Current activity does not support picture-in-picture.");
4128 }
4129
4130 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004131 && !mWindowManager.isValidPictureInPictureAspectRatio(
4132 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 final float minAspectRatio = mContext.getResources().getFloat(
4134 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4135 final float maxAspectRatio = mContext.getResources().getFloat(
4136 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4137 throw new IllegalArgumentException(String.format(caller
4138 + ": Aspect ratio is too extreme (must be between %f and %f).",
4139 minAspectRatio, maxAspectRatio));
4140 }
4141
4142 // Truncate the number of actions if necessary
4143 params.truncateActions(getMaxNumPictureInPictureActions(token));
4144
4145 return r;
4146 }
4147
4148 @Override
4149 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004150 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 synchronized (mGlobalLock) {
4152 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4153 if (r == null) {
4154 throw new IllegalArgumentException("Activity does not exist; token="
4155 + activityToken);
4156 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004157 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 }
4159 }
4160
4161 @Override
4162 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4163 Rect tempDockedTaskInsetBounds,
4164 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004165 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 long ident = Binder.clearCallingIdentity();
4167 try {
4168 synchronized (mGlobalLock) {
4169 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4170 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4171 PRESERVE_WINDOWS);
4172 }
4173 } finally {
4174 Binder.restoreCallingIdentity(ident);
4175 }
4176 }
4177
4178 @Override
4179 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004180 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004181 final long ident = Binder.clearCallingIdentity();
4182 try {
4183 synchronized (mGlobalLock) {
4184 mStackSupervisor.setSplitScreenResizing(resizing);
4185 }
4186 } finally {
4187 Binder.restoreCallingIdentity(ident);
4188 }
4189 }
4190
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 /**
4192 * Check that we have the features required for VR-related API calls, and throw an exception if
4193 * not.
4194 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004195 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004196 if (!mContext.getPackageManager().hasSystemFeature(
4197 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4198 throw new UnsupportedOperationException("VR mode not supported on this device!");
4199 }
4200 }
4201
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 @Override
4203 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205
4206 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4207
4208 ActivityRecord r;
4209 synchronized (mGlobalLock) {
4210 r = ActivityRecord.isInStackLocked(token);
4211 }
4212
4213 if (r == null) {
4214 throw new IllegalArgumentException();
4215 }
4216
4217 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004218 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 VrManagerInternal.NO_ERROR) {
4220 return err;
4221 }
4222
4223 // Clear the binder calling uid since this path may call moveToTask().
4224 final long callingId = Binder.clearCallingIdentity();
4225 try {
4226 synchronized (mGlobalLock) {
4227 r.requestedVrComponent = (enabled) ? packageName : null;
4228
4229 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004230 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004231 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004232 }
4233 return 0;
4234 }
4235 } finally {
4236 Binder.restoreCallingIdentity(callingId);
4237 }
4238 }
4239
4240 @Override
4241 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4242 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4243 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004244 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4246 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4247 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004248 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 || activity.voiceSession != null) {
4250 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4251 return;
4252 }
4253 if (activity.pendingVoiceInteractionStart) {
4254 Slog.w(TAG, "Pending start of voice interaction already.");
4255 return;
4256 }
4257 activity.pendingVoiceInteractionStart = true;
4258 }
4259 LocalServices.getService(VoiceInteractionManagerInternal.class)
4260 .startLocalVoiceInteraction(callingActivity, options);
4261 }
4262
4263 @Override
4264 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4265 LocalServices.getService(VoiceInteractionManagerInternal.class)
4266 .stopLocalVoiceInteraction(callingActivity);
4267 }
4268
4269 @Override
4270 public boolean supportsLocalVoiceInteraction() {
4271 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4272 .supportsLocalVoiceInteraction();
4273 }
4274
4275 /** Notifies all listeners when the pinned stack animation starts. */
4276 @Override
4277 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004278 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 }
4280
4281 /** Notifies all listeners when the pinned stack animation ends. */
4282 @Override
4283 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004284 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 }
4286
4287 @Override
4288 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004289 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290 final long ident = Binder.clearCallingIdentity();
4291 try {
4292 synchronized (mGlobalLock) {
4293 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4294 }
4295 } finally {
4296 Binder.restoreCallingIdentity(ident);
4297 }
4298 }
4299
4300 @Override
4301 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303
4304 synchronized (mGlobalLock) {
4305 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004306 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 // Call might come when display is not yet added or has already been removed.
4308 if (DEBUG_CONFIGURATION) {
4309 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4310 + displayId);
4311 }
4312 return false;
4313 }
4314
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004315 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004317 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 }
4319
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004320 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004321 final Message msg = PooledLambda.obtainMessage(
4322 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4323 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324 }
4325
4326 final long origId = Binder.clearCallingIdentity();
4327 try {
4328 if (values != null) {
4329 Settings.System.clearConfiguration(values);
4330 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004331 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4333 return mTmpUpdateConfigurationResult.changes != 0;
4334 } finally {
4335 Binder.restoreCallingIdentity(origId);
4336 }
4337 }
4338 }
4339
4340 @Override
4341 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004342 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343
4344 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 }
4349
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004350 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004351 final Message msg = PooledLambda.obtainMessage(
4352 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4353 DEFAULT_DISPLAY);
4354 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 }
4356
4357 final long origId = Binder.clearCallingIdentity();
4358 try {
4359 if (values != null) {
4360 Settings.System.clearConfiguration(values);
4361 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004362 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 UserHandle.USER_NULL, false /* deferResume */,
4364 mTmpUpdateConfigurationResult);
4365 return mTmpUpdateConfigurationResult.changes != 0;
4366 } finally {
4367 Binder.restoreCallingIdentity(origId);
4368 }
4369 }
4370 }
4371
4372 @Override
4373 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4374 CharSequence message) {
4375 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004376 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4378 }
4379 final long callingId = Binder.clearCallingIdentity();
4380 try {
4381 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004382 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383 }
4384 } finally {
4385 Binder.restoreCallingIdentity(callingId);
4386 }
4387 }
4388
4389 @Override
4390 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 "cancelTaskWindowTransition()");
4393 final long ident = Binder.clearCallingIdentity();
4394 try {
4395 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004396 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 MATCH_TASK_IN_STACKS_ONLY);
4398 if (task == null) {
4399 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4400 return;
4401 }
4402 task.cancelWindowTransition();
4403 }
4404 } finally {
4405 Binder.restoreCallingIdentity(ident);
4406 }
4407 }
4408
4409 @Override
4410 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 final long ident = Binder.clearCallingIdentity();
4413 try {
4414 final TaskRecord task;
4415 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004416 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004417 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4418 if (task == null) {
4419 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4420 return null;
4421 }
4422 }
4423 // Don't call this while holding the lock as this operation might hit the disk.
4424 return task.getSnapshot(reducedResolution);
4425 } finally {
4426 Binder.restoreCallingIdentity(ident);
4427 }
4428 }
4429
4430 @Override
4431 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4432 synchronized (mGlobalLock) {
4433 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4434 if (r == null) {
4435 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4436 + token);
4437 return;
4438 }
4439 final long origId = Binder.clearCallingIdentity();
4440 try {
4441 r.setDisablePreviewScreenshots(disable);
4442 } finally {
4443 Binder.restoreCallingIdentity(origId);
4444 }
4445 }
4446 }
4447
4448 /** Return the user id of the last resumed activity. */
4449 @Override
4450 public @UserIdInt
4451 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4454 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004455 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004458 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 }
4460 }
4461
4462 @Override
4463 public void updateLockTaskFeatures(int userId, int flags) {
4464 final int callingUid = Binder.getCallingUid();
4465 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004466 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 "updateLockTaskFeatures()");
4468 }
4469 synchronized (mGlobalLock) {
4470 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4471 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004472 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 }
4474 }
4475
4476 @Override
4477 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4478 synchronized (mGlobalLock) {
4479 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4480 if (r == null) {
4481 return;
4482 }
4483 final long origId = Binder.clearCallingIdentity();
4484 try {
4485 r.setShowWhenLocked(showWhenLocked);
4486 } finally {
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489 }
4490 }
4491
4492 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004493 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4494 synchronized (mGlobalLock) {
4495 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4496 if (r == null) {
4497 return;
4498 }
4499 final long origId = Binder.clearCallingIdentity();
4500 try {
4501 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4502 } finally {
4503 Binder.restoreCallingIdentity(origId);
4504 }
4505 }
4506 }
4507
4508 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4510 synchronized (mGlobalLock) {
4511 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4512 if (r == null) {
4513 return;
4514 }
4515 final long origId = Binder.clearCallingIdentity();
4516 try {
4517 r.setTurnScreenOn(turnScreenOn);
4518 } finally {
4519 Binder.restoreCallingIdentity(origId);
4520 }
4521 }
4522 }
4523
4524 @Override
4525 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004526 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004527 "registerRemoteAnimations");
4528 definition.setCallingPid(Binder.getCallingPid());
4529 synchronized (mGlobalLock) {
4530 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4531 if (r == null) {
4532 return;
4533 }
4534 final long origId = Binder.clearCallingIdentity();
4535 try {
4536 r.registerRemoteAnimations(definition);
4537 } finally {
4538 Binder.restoreCallingIdentity(origId);
4539 }
4540 }
4541 }
4542
4543 @Override
4544 public void registerRemoteAnimationForNextActivityStart(String packageName,
4545 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004546 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 "registerRemoteAnimationForNextActivityStart");
4548 adapter.setCallingPid(Binder.getCallingPid());
4549 synchronized (mGlobalLock) {
4550 final long origId = Binder.clearCallingIdentity();
4551 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004552 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 packageName, adapter);
4554 } finally {
4555 Binder.restoreCallingIdentity(origId);
4556 }
4557 }
4558 }
4559
Evan Rosky966759f2019-01-15 10:33:58 -08004560 @Override
4561 public void registerRemoteAnimationsForDisplay(int displayId,
4562 RemoteAnimationDefinition definition) {
4563 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4564 "registerRemoteAnimations");
4565 definition.setCallingPid(Binder.getCallingPid());
4566 synchronized (mGlobalLock) {
4567 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4568 if (display == null) {
4569 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4570 return;
4571 }
4572 final long origId = Binder.clearCallingIdentity();
4573 try {
4574 display.mDisplayContent.registerRemoteAnimations(definition);
4575 } finally {
4576 Binder.restoreCallingIdentity(origId);
4577 }
4578 }
4579 }
4580
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4582 @Override
4583 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4584 synchronized (mGlobalLock) {
4585 final long origId = Binder.clearCallingIdentity();
4586 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004587 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004593
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004594 @Override
4595 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004596 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004597 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004598 final int pid = Binder.getCallingPid();
4599 final WindowProcessController wpc = mPidMap.get(pid);
4600 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004601 }
4602 }
4603
4604 @Override
4605 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004606 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004607 != PERMISSION_GRANTED) {
4608 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4609 + Binder.getCallingPid()
4610 + ", uid=" + Binder.getCallingUid()
4611 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4612 Slog.w(TAG, msg);
4613 throw new SecurityException(msg);
4614 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004615 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004616 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004617 final int pid = Binder.getCallingPid();
4618 final WindowProcessController proc = mPidMap.get(pid);
4619 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004620 }
4621 }
4622
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004623 @Override
4624 public void stopAppSwitches() {
4625 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4626 synchronized (mGlobalLock) {
4627 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4628 mDidAppSwitch = false;
4629 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4630 }
4631 }
4632
4633 @Override
4634 public void resumeAppSwitches() {
4635 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4636 synchronized (mGlobalLock) {
4637 // Note that we don't execute any pending app switches... we will
4638 // let those wait until either the timeout, or the next start
4639 // activity request.
4640 mAppSwitchesAllowedTime = 0;
4641 }
4642 }
4643
4644 void onStartActivitySetDidAppSwitch() {
4645 if (mDidAppSwitch) {
4646 // This is the second allowed switch since we stopped switches, so now just generally
4647 // allow switches. Use case:
4648 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4649 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4650 // anyone to switch again).
4651 mAppSwitchesAllowedTime = 0;
4652 } else {
4653 mDidAppSwitch = true;
4654 }
4655 }
4656
4657 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004658 boolean shouldDisableNonVrUiLocked() {
4659 return mVrController.shouldDisableNonVrUiLocked();
4660 }
4661
Wale Ogunwale53783742018-09-16 10:21:51 -07004662 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 // VR apps are expected to run in a main display. If an app is turning on VR for
4664 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4665 // fullscreen stack before enabling VR Mode.
4666 // TODO: The goal of this code is to keep the VR app on the main display. When the
4667 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4668 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4669 // option would be a better choice here.
4670 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4671 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4672 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004673 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004674 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004675 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004676 }
4677 mH.post(() -> {
4678 if (!mVrController.onVrModeChanged(r)) {
4679 return;
4680 }
4681 synchronized (mGlobalLock) {
4682 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4683 mWindowManager.disableNonVrUi(disableNonVrUi);
4684 if (disableNonVrUi) {
4685 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4686 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004687 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 }
4689 }
4690 });
4691 }
4692
Wale Ogunwale53783742018-09-16 10:21:51 -07004693 @Override
4694 public int getPackageScreenCompatMode(String packageName) {
4695 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4696 synchronized (mGlobalLock) {
4697 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4698 }
4699 }
4700
4701 @Override
4702 public void setPackageScreenCompatMode(String packageName, int mode) {
4703 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4704 "setPackageScreenCompatMode");
4705 synchronized (mGlobalLock) {
4706 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4707 }
4708 }
4709
4710 @Override
4711 public boolean getPackageAskScreenCompat(String packageName) {
4712 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4713 synchronized (mGlobalLock) {
4714 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4715 }
4716 }
4717
4718 @Override
4719 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4720 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4721 "setPackageAskScreenCompat");
4722 synchronized (mGlobalLock) {
4723 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4724 }
4725 }
4726
Wale Ogunwale64258362018-10-16 15:13:37 -07004727 public static String relaunchReasonToString(int relaunchReason) {
4728 switch (relaunchReason) {
4729 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4730 return "window_resize";
4731 case RELAUNCH_REASON_FREE_RESIZE:
4732 return "free_resize";
4733 default:
4734 return null;
4735 }
4736 }
4737
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004738 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004739 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004740 }
4741
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004742 /** Pokes the task persister. */
4743 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4744 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4745 }
4746
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004747 boolean isKeyguardLocked() {
4748 return mKeyguardController.isKeyguardLocked();
4749 }
4750
Garfield Tan01548632018-11-27 10:15:48 -08004751 /**
4752 * Clears launch params for the given package.
4753 * @param packageNames the names of the packages of which the launch params are to be cleared
4754 */
4755 @Override
4756 public void clearLaunchParamsForPackages(List<String> packageNames) {
4757 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4758 "clearLaunchParamsForPackages");
4759 synchronized (mGlobalLock) {
4760 for (int i = 0; i < packageNames.size(); ++i) {
4761 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4762 }
4763 }
4764 }
4765
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004766 /**
4767 * Makes the display with the given id a single task instance display. I.e the display can only
4768 * contain one task.
4769 */
4770 @Override
4771 public void setDisplayToSingleTaskInstance(int displayId) {
4772 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4773 "setDisplayToSingleTaskInstance");
4774 final long origId = Binder.clearCallingIdentity();
4775 try {
4776 final ActivityDisplay display =
4777 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4778 if (display != null) {
4779 display.setDisplayToSingleTaskInstance();
4780 }
4781 } finally {
4782 Binder.restoreCallingIdentity(origId);
4783 }
4784 }
4785
Wale Ogunwale31913b52018-10-13 08:29:31 -07004786 void dumpLastANRLocked(PrintWriter pw) {
4787 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4788 if (mLastANRState == null) {
4789 pw.println(" <no ANR has occurred since boot>");
4790 } else {
4791 pw.println(mLastANRState);
4792 }
4793 }
4794
4795 void dumpLastANRTracesLocked(PrintWriter pw) {
4796 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4797
4798 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4799 if (ArrayUtils.isEmpty(files)) {
4800 pw.println(" <no ANR has occurred since boot>");
4801 return;
4802 }
4803 // Find the latest file.
4804 File latest = null;
4805 for (File f : files) {
4806 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4807 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004808 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004809 }
4810 pw.print("File: ");
4811 pw.print(latest.getName());
4812 pw.println();
4813 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4814 String line;
4815 while ((line = in.readLine()) != null) {
4816 pw.println(line);
4817 }
4818 } catch (IOException e) {
4819 pw.print("Unable to read: ");
4820 pw.print(e);
4821 pw.println();
4822 }
4823 }
4824
4825 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4826 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4827 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4828 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4829 }
4830
4831 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4832 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4833 pw.println(header);
4834
Wale Ogunwaled32da472018-11-16 07:19:28 -08004835 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004836 dumpPackage);
4837 boolean needSep = printedAnything;
4838
4839 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004840 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004841 " ResumedActivity: ");
4842 if (printed) {
4843 printedAnything = true;
4844 needSep = false;
4845 }
4846
4847 if (dumpPackage == null) {
4848 if (needSep) {
4849 pw.println();
4850 }
4851 printedAnything = true;
4852 mStackSupervisor.dump(pw, " ");
4853 }
4854
4855 if (!printedAnything) {
4856 pw.println(" (nothing)");
4857 }
4858 }
4859
4860 void dumpActivityContainersLocked(PrintWriter pw) {
4861 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004862 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004863 pw.println(" ");
4864 }
4865
4866 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4867 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4868 getActivityStartController().dump(pw, "", dumpPackage);
4869 }
4870
4871 /**
4872 * There are three things that cmd can be:
4873 * - a flattened component name that matches an existing activity
4874 * - the cmd arg isn't the flattened component name of an existing activity:
4875 * dump all activity whose component contains the cmd as a substring
4876 * - A hex number of the ActivityRecord object instance.
4877 *
4878 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4879 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4880 */
4881 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4882 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4883 ArrayList<ActivityRecord> activities;
4884
4885 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004886 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004887 dumpFocusedStackOnly);
4888 }
4889
4890 if (activities.size() <= 0) {
4891 return false;
4892 }
4893
4894 String[] newArgs = new String[args.length - opti];
4895 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4896
4897 TaskRecord lastTask = null;
4898 boolean needSep = false;
4899 for (int i = activities.size() - 1; i >= 0; i--) {
4900 ActivityRecord r = activities.get(i);
4901 if (needSep) {
4902 pw.println();
4903 }
4904 needSep = true;
4905 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004906 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004907 if (lastTask != task) {
4908 lastTask = task;
4909 pw.print("TASK "); pw.print(lastTask.affinity);
4910 pw.print(" id="); pw.print(lastTask.taskId);
4911 pw.print(" userId="); pw.println(lastTask.userId);
4912 if (dumpAll) {
4913 lastTask.dump(pw, " ");
4914 }
4915 }
4916 }
4917 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4918 }
4919 return true;
4920 }
4921
4922 /**
4923 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4924 * there is a thread associated with the activity.
4925 */
4926 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4927 final ActivityRecord r, String[] args, boolean dumpAll) {
4928 String innerPrefix = prefix + " ";
4929 synchronized (mGlobalLock) {
4930 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4931 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4932 pw.print(" pid=");
4933 if (r.hasProcess()) pw.println(r.app.getPid());
4934 else pw.println("(not running)");
4935 if (dumpAll) {
4936 r.dump(pw, innerPrefix);
4937 }
4938 }
4939 if (r.attachedToProcess()) {
4940 // flush anything that is already in the PrintWriter since the thread is going
4941 // to write to the file descriptor directly
4942 pw.flush();
4943 try {
4944 TransferPipe tp = new TransferPipe();
4945 try {
4946 r.app.getThread().dumpActivity(tp.getWriteFd(),
4947 r.appToken, innerPrefix, args);
4948 tp.go(fd);
4949 } finally {
4950 tp.kill();
4951 }
4952 } catch (IOException e) {
4953 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4954 } catch (RemoteException e) {
4955 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4956 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004957 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004958 }
4959
sanryhuang498e77e2018-12-06 14:57:01 +08004960 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4961 boolean testPssMode) {
4962 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4963 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4964 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004965 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004966 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4967 st.toString());
4968 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004969 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4970 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4971 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004972 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4973 testPssMode);
4974 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004975 }
4976
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004977 int getCurrentUserId() {
4978 return mAmInternal.getCurrentUserId();
4979 }
4980
4981 private void enforceNotIsolatedCaller(String caller) {
4982 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4983 throw new SecurityException("Isolated process not allowed to call " + caller);
4984 }
4985 }
4986
Wale Ogunwalef6733932018-06-27 05:14:34 -07004987 public Configuration getConfiguration() {
4988 Configuration ci;
4989 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004990 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004991 ci.userSetLocale = false;
4992 }
4993 return ci;
4994 }
4995
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004996 /**
4997 * Current global configuration information. Contains general settings for the entire system,
4998 * also corresponds to the merged configuration of the default display.
4999 */
5000 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005001 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005002 }
5003
5004 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5005 boolean initLocale) {
5006 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5007 }
5008
5009 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5010 boolean initLocale, boolean deferResume) {
5011 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5012 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5013 UserHandle.USER_NULL, deferResume);
5014 }
5015
Wale Ogunwale59507092018-10-29 09:00:30 -07005016 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005017 final long origId = Binder.clearCallingIdentity();
5018 try {
5019 synchronized (mGlobalLock) {
5020 updateConfigurationLocked(values, null, false, true, userId,
5021 false /* deferResume */);
5022 }
5023 } finally {
5024 Binder.restoreCallingIdentity(origId);
5025 }
5026 }
5027
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005028 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5029 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5030 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5031 deferResume, null /* result */);
5032 }
5033
5034 /**
5035 * Do either or both things: (1) change the current configuration, and (2)
5036 * make sure the given activity is running with the (now) current
5037 * configuration. Returns true if the activity has been left running, or
5038 * false if <var>starting</var> is being destroyed to match the new
5039 * configuration.
5040 *
5041 * @param userId is only used when persistent parameter is set to true to persist configuration
5042 * for that particular user
5043 */
5044 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5045 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5046 ActivityTaskManagerService.UpdateConfigurationResult result) {
5047 int changes = 0;
5048 boolean kept = true;
5049
5050 if (mWindowManager != null) {
5051 mWindowManager.deferSurfaceLayout();
5052 }
5053 try {
5054 if (values != null) {
5055 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5056 deferResume);
5057 }
5058
5059 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5060 } finally {
5061 if (mWindowManager != null) {
5062 mWindowManager.continueSurfaceLayout();
5063 }
5064 }
5065
5066 if (result != null) {
5067 result.changes = changes;
5068 result.activityRelaunched = !kept;
5069 }
5070 return kept;
5071 }
5072
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 /** Update default (global) configuration and notify listeners about changes. */
5074 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5075 boolean persistent, int userId, boolean deferResume) {
5076 mTempConfig.setTo(getGlobalConfiguration());
5077 final int changes = mTempConfig.updateFrom(values);
5078 if (changes == 0) {
5079 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5080 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5081 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5082 // (even if there are no actual changes) to unfreeze the window.
5083 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5084 return 0;
5085 }
5086
5087 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5088 "Updating global configuration to: " + values);
5089
5090 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5091 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5092 values.colorMode,
5093 values.densityDpi,
5094 values.fontScale,
5095 values.hardKeyboardHidden,
5096 values.keyboard,
5097 values.keyboardHidden,
5098 values.mcc,
5099 values.mnc,
5100 values.navigation,
5101 values.navigationHidden,
5102 values.orientation,
5103 values.screenHeightDp,
5104 values.screenLayout,
5105 values.screenWidthDp,
5106 values.smallestScreenWidthDp,
5107 values.touchscreen,
5108 values.uiMode);
5109
5110
5111 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5112 final LocaleList locales = values.getLocales();
5113 int bestLocaleIndex = 0;
5114 if (locales.size() > 1) {
5115 if (mSupportedSystemLocales == null) {
5116 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5117 }
5118 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5119 }
5120 SystemProperties.set("persist.sys.locale",
5121 locales.get(bestLocaleIndex).toLanguageTag());
5122 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005123
5124 final Message m = PooledLambda.obtainMessage(
5125 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5126 locales.get(bestLocaleIndex));
5127 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 }
5129
Yunfan Chen75157d72018-07-27 14:47:21 +09005130 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131
5132 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005133 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134
5135 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5136 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005137 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005138
5139 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005140 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005141
5142 AttributeCache ac = AttributeCache.instance();
5143 if (ac != null) {
5144 ac.updateConfiguration(mTempConfig);
5145 }
5146
5147 // Make sure all resources in our process are updated right now, so that anyone who is going
5148 // to retrieve resource values after we return will be sure to get the new ones. This is
5149 // especially important during boot, where the first config change needs to guarantee all
5150 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005151 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152
5153 // We need another copy of global config because we're scheduling some calls instead of
5154 // running them in place. We need to be sure that object we send will be handled unchanged.
5155 final Configuration configCopy = new Configuration(mTempConfig);
5156 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005157 final Message msg = PooledLambda.obtainMessage(
5158 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5159 this, userId, configCopy);
5160 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005161 }
5162
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005163 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005164 final int pid = mPidMap.keyAt(i);
5165 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005166 if (DEBUG_CONFIGURATION) {
5167 Slog.v(TAG_CONFIGURATION, "Update process config of "
5168 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005169 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005170 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 }
5172
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005173 final Message msg = PooledLambda.obtainMessage(
5174 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5175 mAmInternal, changes, initLocale);
5176 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177
5178 // Override configuration of the default display duplicates global config, so we need to
5179 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005180 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005181 DEFAULT_DISPLAY);
5182
5183 return changes;
5184 }
5185
5186 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5187 boolean deferResume, int displayId) {
5188 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5189 displayId, null /* result */);
5190 }
5191
5192 /**
5193 * Updates override configuration specific for the selected display. If no config is provided,
5194 * new one will be computed in WM based on current display info.
5195 */
5196 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5197 ActivityRecord starting, boolean deferResume, int displayId,
5198 ActivityTaskManagerService.UpdateConfigurationResult result) {
5199 int changes = 0;
5200 boolean kept = true;
5201
5202 if (mWindowManager != null) {
5203 mWindowManager.deferSurfaceLayout();
5204 }
5205 try {
5206 if (values != null) {
5207 if (displayId == DEFAULT_DISPLAY) {
5208 // Override configuration of the default display duplicates global config, so
5209 // we're calling global config update instead for default display. It will also
5210 // apply the correct override config.
5211 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5212 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5213 } else {
5214 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5215 }
5216 }
5217
5218 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5219 } finally {
5220 if (mWindowManager != null) {
5221 mWindowManager.continueSurfaceLayout();
5222 }
5223 }
5224
5225 if (result != null) {
5226 result.changes = changes;
5227 result.activityRelaunched = !kept;
5228 }
5229 return kept;
5230 }
5231
5232 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5233 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005234 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235 final int changes = mTempConfig.updateFrom(values);
5236 if (changes != 0) {
5237 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5238 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005239 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240
5241 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5242 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005243 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244
Wale Ogunwale5c918702018-10-18 11:06:33 -07005245 // Post message to start process to avoid possible deadlock of calling into AMS with
5246 // the ATMS lock held.
5247 final Message msg = PooledLambda.obtainMessage(
5248 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005249 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005250 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 }
5252 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 return changes;
5254 }
5255
Wale Ogunwalef6733932018-06-27 05:14:34 -07005256 private void updateEventDispatchingLocked(boolean booted) {
5257 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5258 }
5259
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005260 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5261 final ContentResolver resolver = mContext.getContentResolver();
5262 Settings.System.putConfigurationForUser(resolver, config, userId);
5263 }
5264
5265 private void sendLocaleToMountDaemonMsg(Locale l) {
5266 try {
5267 IBinder service = ServiceManager.getService("mount");
5268 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5269 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5270 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5271 } catch (RemoteException e) {
5272 Log.e(TAG, "Error storing locale for decryption UI", e);
5273 }
5274 }
5275
Alison Cichowlas3e340502018-08-07 17:15:01 -04005276 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5277 mStartActivitySources.remove(permissionToken);
5278 mExpiredStartAsCallerTokens.add(permissionToken);
5279 }
5280
5281 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5282 mExpiredStartAsCallerTokens.remove(permissionToken);
5283 }
5284
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005285 boolean isActivityStartsLoggingEnabled() {
5286 return mAmInternal.isActivityStartsLoggingEnabled();
5287 }
5288
Michal Karpinski8596ded2018-11-14 14:43:48 +00005289 boolean isBackgroundActivityStartsEnabled() {
5290 return mAmInternal.isBackgroundActivityStartsEnabled();
5291 }
5292
Michal Karpinski666631b2019-02-26 16:59:11 +00005293 boolean isPackageNameWhitelistedForBgActivityStarts(String packageName) {
5294 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5295 }
5296
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 void enableScreenAfterBoot(boolean booted) {
5298 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5299 SystemClock.uptimeMillis());
5300 mWindowManager.enableScreenAfterBoot();
5301
5302 synchronized (mGlobalLock) {
5303 updateEventDispatchingLocked(booted);
5304 }
5305 }
5306
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005307 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5308 if (r == null || !r.hasProcess()) {
5309 return KEY_DISPATCHING_TIMEOUT_MS;
5310 }
5311 return getInputDispatchingTimeoutLocked(r.app);
5312 }
5313
5314 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005315 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005316 }
5317
Wale Ogunwalef6733932018-06-27 05:14:34 -07005318 /**
5319 * Decide based on the configuration whether we should show the ANR,
5320 * crash, etc dialogs. The idea is that if there is no affordance to
5321 * press the on-screen buttons, or the user experience would be more
5322 * greatly impacted than the crash itself, we shouldn't show the dialog.
5323 *
5324 * A thought: SystemUI might also want to get told about this, the Power
5325 * dialog / global actions also might want different behaviors.
5326 */
5327 private void updateShouldShowDialogsLocked(Configuration config) {
5328 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5329 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5330 && config.navigation == Configuration.NAVIGATION_NONAV);
5331 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5332 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5333 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5334 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5335 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5336 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5337 HIDE_ERROR_DIALOGS, 0) != 0;
5338 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5339 }
5340
5341 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5342 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5343 FONT_SCALE, 1.0f, userId);
5344
5345 synchronized (this) {
5346 if (getGlobalConfiguration().fontScale == scaleFactor) {
5347 return;
5348 }
5349
5350 final Configuration configuration
5351 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5352 configuration.fontScale = scaleFactor;
5353 updatePersistentConfiguration(configuration, userId);
5354 }
5355 }
5356
5357 // Actually is sleeping or shutting down or whatever else in the future
5358 // is an inactive state.
5359 boolean isSleepingOrShuttingDownLocked() {
5360 return isSleepingLocked() || mShuttingDown;
5361 }
5362
5363 boolean isSleepingLocked() {
5364 return mSleeping;
5365 }
5366
Riddle Hsu16567132018-08-16 21:37:47 +08005367 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005368 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005369 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005370 if (task.isActivityTypeStandard()) {
5371 if (mCurAppTimeTracker != r.appTimeTracker) {
5372 // We are switching app tracking. Complete the current one.
5373 if (mCurAppTimeTracker != null) {
5374 mCurAppTimeTracker.stop();
5375 mH.obtainMessage(
5376 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005377 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 mCurAppTimeTracker = null;
5379 }
5380 if (r.appTimeTracker != null) {
5381 mCurAppTimeTracker = r.appTimeTracker;
5382 startTimeTrackingFocusedActivityLocked();
5383 }
5384 } else {
5385 startTimeTrackingFocusedActivityLocked();
5386 }
5387 } else {
5388 r.appTimeTracker = null;
5389 }
5390 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5391 // TODO: Probably not, because we don't want to resume voice on switching
5392 // back to this activity
5393 if (task.voiceInteractor != null) {
5394 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5395 } else {
5396 finishRunningVoiceLocked();
5397
5398 if (mLastResumedActivity != null) {
5399 final IVoiceInteractionSession session;
5400
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005401 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005402 if (lastResumedActivityTask != null
5403 && lastResumedActivityTask.voiceSession != null) {
5404 session = lastResumedActivityTask.voiceSession;
5405 } else {
5406 session = mLastResumedActivity.voiceSession;
5407 }
5408
5409 if (session != null) {
5410 // We had been in a voice interaction session, but now focused has
5411 // move to something different. Just finish the session, we can't
5412 // return to it and retain the proper state and synchronization with
5413 // the voice interaction service.
5414 finishVoiceTask(session);
5415 }
5416 }
5417 }
5418
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005419 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5420 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005421 }
5422 updateResumedAppTrace(r);
5423 mLastResumedActivity = r;
5424
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005425 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005426
5427 applyUpdateLockStateLocked(r);
5428 applyUpdateVrModeLocked(r);
5429
5430 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005431 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 r == null ? "NULL" : r.shortComponentName,
5433 reason);
5434 }
5435
5436 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5437 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005438 final ActivityTaskManagerInternal.SleepToken token =
5439 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 updateSleepIfNeededLocked();
5441 return token;
5442 }
5443 }
5444
5445 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005446 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005447 final boolean wasSleeping = mSleeping;
5448 boolean updateOomAdj = false;
5449
5450 if (!shouldSleep) {
5451 // If wasSleeping is true, we need to wake up activity manager state from when
5452 // we started sleeping. In either case, we need to apply the sleep tokens, which
5453 // will wake up stacks or put them to sleep as appropriate.
5454 if (wasSleeping) {
5455 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005456 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5457 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 startTimeTrackingFocusedActivityLocked();
5459 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5460 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5461 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005462 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 if (wasSleeping) {
5464 updateOomAdj = true;
5465 }
5466 } else if (!mSleeping && shouldSleep) {
5467 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005468 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5469 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005470 if (mCurAppTimeTracker != null) {
5471 mCurAppTimeTracker.stop();
5472 }
5473 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5474 mStackSupervisor.goingToSleepLocked();
5475 updateResumedAppTrace(null /* resumed */);
5476 updateOomAdj = true;
5477 }
5478 if (updateOomAdj) {
5479 mH.post(mAmInternal::updateOomAdj);
5480 }
5481 }
5482
5483 void updateOomAdj() {
5484 mH.post(mAmInternal::updateOomAdj);
5485 }
5486
Wale Ogunwale53783742018-09-16 10:21:51 -07005487 void updateCpuStats() {
5488 mH.post(mAmInternal::updateCpuStats);
5489 }
5490
Hui Yu03d12402018-12-06 18:00:37 -08005491 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5492 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005493 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5494 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005495 mH.sendMessage(m);
5496 }
5497
Hui Yu03d12402018-12-06 18:00:37 -08005498 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005499 ComponentName taskRoot = null;
5500 final TaskRecord task = activity.getTaskRecord();
5501 if (task != null) {
5502 final ActivityRecord rootActivity = task.getRootActivity();
5503 if (rootActivity != null) {
5504 taskRoot = rootActivity.mActivityComponent;
5505 }
5506 }
5507
Hui Yu03d12402018-12-06 18:00:37 -08005508 final Message m = PooledLambda.obtainMessage(
5509 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005510 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005511 mH.sendMessage(m);
5512 }
5513
Wale Ogunwale53783742018-09-16 10:21:51 -07005514 void setBooting(boolean booting) {
5515 mAmInternal.setBooting(booting);
5516 }
5517
5518 boolean isBooting() {
5519 return mAmInternal.isBooting();
5520 }
5521
5522 void setBooted(boolean booted) {
5523 mAmInternal.setBooted(booted);
5524 }
5525
5526 boolean isBooted() {
5527 return mAmInternal.isBooted();
5528 }
5529
5530 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5531 mH.post(() -> {
5532 if (finishBooting) {
5533 mAmInternal.finishBooting();
5534 }
5535 if (enableScreen) {
5536 mInternal.enableScreenAfterBoot(isBooted());
5537 }
5538 });
5539 }
5540
5541 void setHeavyWeightProcess(ActivityRecord root) {
5542 mHeavyWeightProcess = root.app;
5543 final Message m = PooledLambda.obtainMessage(
5544 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005545 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005546 mH.sendMessage(m);
5547 }
5548
5549 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5550 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5551 return;
5552 }
5553
5554 mHeavyWeightProcess = null;
5555 final Message m = PooledLambda.obtainMessage(
5556 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5557 proc.mUserId);
5558 mH.sendMessage(m);
5559 }
5560
5561 private void cancelHeavyWeightProcessNotification(int userId) {
5562 final INotificationManager inm = NotificationManager.getService();
5563 if (inm == null) {
5564 return;
5565 }
5566 try {
5567 inm.cancelNotificationWithTag("android", null,
5568 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5569 } catch (RuntimeException e) {
5570 Slog.w(TAG, "Error canceling notification for service", e);
5571 } catch (RemoteException e) {
5572 }
5573
5574 }
5575
5576 private void postHeavyWeightProcessNotification(
5577 WindowProcessController proc, Intent intent, int userId) {
5578 if (proc == null) {
5579 return;
5580 }
5581
5582 final INotificationManager inm = NotificationManager.getService();
5583 if (inm == null) {
5584 return;
5585 }
5586
5587 try {
5588 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5589 String text = mContext.getString(R.string.heavy_weight_notification,
5590 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5591 Notification notification =
5592 new Notification.Builder(context,
5593 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5594 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5595 .setWhen(0)
5596 .setOngoing(true)
5597 .setTicker(text)
5598 .setColor(mContext.getColor(
5599 com.android.internal.R.color.system_notification_accent_color))
5600 .setContentTitle(text)
5601 .setContentText(
5602 mContext.getText(R.string.heavy_weight_notification_detail))
5603 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5604 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5605 new UserHandle(userId)))
5606 .build();
5607 try {
5608 inm.enqueueNotificationWithTag("android", "android", null,
5609 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5610 } catch (RuntimeException e) {
5611 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5612 } catch (RemoteException e) {
5613 }
5614 } catch (PackageManager.NameNotFoundException e) {
5615 Slog.w(TAG, "Unable to create context for heavy notification", e);
5616 }
5617
5618 }
5619
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005620 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5621 IBinder token, String resultWho, int requestCode, Intent[] intents,
5622 String[] resolvedTypes, int flags, Bundle bOptions) {
5623
5624 ActivityRecord activity = null;
5625 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5626 activity = ActivityRecord.isInStackLocked(token);
5627 if (activity == null) {
5628 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5629 return null;
5630 }
5631 if (activity.finishing) {
5632 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5633 return null;
5634 }
5635 }
5636
5637 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5638 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5639 bOptions);
5640 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5641 if (noCreate) {
5642 return rec;
5643 }
5644 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5645 if (activity.pendingResults == null) {
5646 activity.pendingResults = new HashSet<>();
5647 }
5648 activity.pendingResults.add(rec.ref);
5649 }
5650 return rec;
5651 }
5652
Andrii Kulian52d255c2018-07-13 11:32:19 -07005653 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005654 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005655 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005656 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5657 mCurAppTimeTracker.start(resumedActivity.packageName);
5658 }
5659 }
5660
5661 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5662 if (mTracedResumedActivity != null) {
5663 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5664 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5665 }
5666 if (resumed != null) {
5667 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5668 constructResumedTraceName(resumed.packageName), 0);
5669 }
5670 mTracedResumedActivity = resumed;
5671 }
5672
5673 private String constructResumedTraceName(String packageName) {
5674 return "focused app: " + packageName;
5675 }
5676
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005677 /** Applies latest configuration and/or visibility updates if needed. */
5678 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5679 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005680 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005681 // mainStack is null during startup.
5682 if (mainStack != null) {
5683 if (changes != 0 && starting == null) {
5684 // If the configuration changed, and the caller is not already
5685 // in the process of starting an activity, then find the top
5686 // activity to check if its configuration needs to change.
5687 starting = mainStack.topRunningActivityLocked();
5688 }
5689
5690 if (starting != null) {
5691 kept = starting.ensureActivityConfiguration(changes,
5692 false /* preserveWindow */);
5693 // And we need to make sure at this point that all other activities
5694 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005695 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005696 !PRESERVE_WINDOWS);
5697 }
5698 }
5699
5700 return kept;
5701 }
5702
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005703 void scheduleAppGcsLocked() {
5704 mH.post(() -> mAmInternal.scheduleAppGcs());
5705 }
5706
Wale Ogunwale53783742018-09-16 10:21:51 -07005707 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5708 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5709 }
5710
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005711 /**
5712 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5713 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5714 * on demand.
5715 */
5716 IPackageManager getPackageManager() {
5717 return AppGlobals.getPackageManager();
5718 }
5719
5720 PackageManagerInternal getPackageManagerInternalLocked() {
5721 if (mPmInternal == null) {
5722 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5723 }
5724 return mPmInternal;
5725 }
5726
Wale Ogunwale008163e2018-07-23 23:11:08 -07005727 AppWarnings getAppWarningsLocked() {
5728 return mAppWarnings;
5729 }
5730
Wale Ogunwale214f3482018-10-04 11:00:47 -07005731 Intent getHomeIntent() {
5732 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5733 intent.setComponent(mTopComponent);
5734 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5735 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5736 intent.addCategory(Intent.CATEGORY_HOME);
5737 }
5738 return intent;
5739 }
5740
Chilun2ef71f72018-11-16 17:57:15 +08005741 /**
5742 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5743 * activities.
5744 *
5745 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5746 * component defined in config_secondaryHomeComponent.
5747 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5748 */
5749 Intent getSecondaryHomeIntent(String preferredPackage) {
5750 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5751 if (preferredPackage == null) {
5752 // Using the component stored in config if no package name.
5753 final String secondaryHomeComponent = mContext.getResources().getString(
5754 com.android.internal.R.string.config_secondaryHomeComponent);
5755 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5756 } else {
5757 intent.setPackage(preferredPackage);
5758 }
5759 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5760 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5761 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5762 }
5763 return intent;
5764 }
5765
Wale Ogunwale214f3482018-10-04 11:00:47 -07005766 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5767 if (info == null) return null;
5768 ApplicationInfo newInfo = new ApplicationInfo(info);
5769 newInfo.initForUser(userId);
5770 return newInfo;
5771 }
5772
Wale Ogunwale9c103022018-10-18 07:44:54 -07005773 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005774 if (uid == SYSTEM_UID) {
5775 // The system gets to run in any process. If there are multiple processes with the same
5776 // uid, just pick the first (this should never happen).
5777 final SparseArray<WindowProcessController> procs =
5778 mProcessNames.getMap().get(processName);
5779 if (procs == null) return null;
5780 final int procCount = procs.size();
5781 for (int i = 0; i < procCount; i++) {
5782 final int procUid = procs.keyAt(i);
5783 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5784 // Don't use an app process or different user process for system component.
5785 continue;
5786 }
5787 return procs.valueAt(i);
5788 }
5789 }
5790
5791 return mProcessNames.get(processName, uid);
5792 }
5793
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005794 WindowProcessController getProcessController(IApplicationThread thread) {
5795 if (thread == null) {
5796 return null;
5797 }
5798
5799 final IBinder threadBinder = thread.asBinder();
5800 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5801 for (int i = pmap.size()-1; i >= 0; i--) {
5802 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5803 for (int j = procs.size() - 1; j >= 0; j--) {
5804 final WindowProcessController proc = procs.valueAt(j);
5805 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5806 return proc;
5807 }
5808 }
5809 }
5810
5811 return null;
5812 }
5813
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005814 WindowProcessController getProcessController(int pid, int uid) {
Yunfan Chen8546b212019-04-01 15:34:44 +09005815 final WindowProcessController proc = mPidMap.get(pid);
5816 if (proc == null) return null;
5817 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5818 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005819 }
5820 return null;
5821 }
5822
Riddle Hsua0536432019-02-16 00:38:59 +08005823 int getUidState(int uid) {
5824 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005825 }
5826
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005827 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005828 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005829 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5830 }
5831
Ricky Wai96f5c352019-04-10 18:40:17 +01005832 boolean isDeviceOwner(int uid) {
5833 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005834 }
5835
Ricky Wai96f5c352019-04-10 18:40:17 +01005836 void setDeviceOwnerUid(int uid) {
5837 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005838 }
5839
Wale Ogunwale9de19442018-10-18 19:05:03 -07005840 /**
5841 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5842 * the whitelist
5843 */
5844 String getPendingTempWhitelistTagForUidLocked(int uid) {
5845 return mPendingTempWhitelist.get(uid);
5846 }
5847
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005848 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5849 if (true || Build.IS_USER) {
5850 return;
5851 }
5852
5853 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5854 StrictMode.allowThreadDiskWrites();
5855 try {
5856 File tracesDir = new File("/data/anr");
5857 File tracesFile = null;
5858 try {
5859 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5860
5861 StringBuilder sb = new StringBuilder();
5862 Time tobj = new Time();
5863 tobj.set(System.currentTimeMillis());
5864 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5865 sb.append(": ");
5866 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5867 sb.append(" since ");
5868 sb.append(msg);
5869 FileOutputStream fos = new FileOutputStream(tracesFile);
5870 fos.write(sb.toString().getBytes());
5871 if (app == null) {
5872 fos.write("\n*** No application process!".getBytes());
5873 }
5874 fos.close();
5875 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5876 } catch (IOException e) {
5877 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5878 return;
5879 }
5880
5881 if (app != null && app.getPid() > 0) {
5882 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5883 firstPids.add(app.getPid());
5884 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5885 }
5886
5887 File lastTracesFile = null;
5888 File curTracesFile = null;
5889 for (int i=9; i>=0; i--) {
5890 String name = String.format(Locale.US, "slow%02d.txt", i);
5891 curTracesFile = new File(tracesDir, name);
5892 if (curTracesFile.exists()) {
5893 if (lastTracesFile != null) {
5894 curTracesFile.renameTo(lastTracesFile);
5895 } else {
5896 curTracesFile.delete();
5897 }
5898 }
5899 lastTracesFile = curTracesFile;
5900 }
5901 tracesFile.renameTo(curTracesFile);
5902 } finally {
5903 StrictMode.setThreadPolicy(oldPolicy);
5904 }
5905 }
5906
Michal Karpinskida34cd42019-04-02 19:46:52 +01005907 boolean isAssociatedCompanionApp(int userId, int uid) {
5908 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5909 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005910 return false;
5911 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005912 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005913 }
5914
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005915 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005916 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005917
5918
Wale Ogunwale98875612018-10-12 07:53:02 -07005919 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5920 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005921
Riddle Hsud93a6c42018-11-29 21:50:06 +08005922 H(Looper looper) {
5923 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005924 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005925
5926 @Override
5927 public void handleMessage(Message msg) {
5928 switch (msg.what) {
5929 case REPORT_TIME_TRACKER_MSG: {
5930 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5931 tracker.deliverResult(mContext);
5932 } break;
5933 }
5934 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005935 }
5936
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005937 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005938 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005939
5940 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005941 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005942 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005943
5944 @Override
5945 public void handleMessage(Message msg) {
5946 switch (msg.what) {
5947 case DISMISS_DIALOG_UI_MSG: {
5948 final Dialog d = (Dialog) msg.obj;
5949 d.dismiss();
5950 break;
5951 }
5952 }
5953 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005954 }
5955
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005956 final class LocalService extends ActivityTaskManagerInternal {
5957 @Override
5958 public SleepToken acquireSleepToken(String tag, int displayId) {
5959 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005960 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005961 }
5962
5963 @Override
5964 public ComponentName getHomeActivityForUser(int userId) {
5965 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005966 final ActivityRecord homeActivity =
5967 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005968 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005969 }
5970 }
5971
5972 @Override
5973 public void onLocalVoiceInteractionStarted(IBinder activity,
5974 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5975 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005976 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005977 }
5978 }
5979
5980 @Override
5981 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5982 synchronized (mGlobalLock) {
5983 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5984 reasons, timestamp);
5985 }
5986 }
5987
5988 @Override
5989 public void notifyAppTransitionFinished() {
5990 synchronized (mGlobalLock) {
5991 mStackSupervisor.notifyAppTransitionDone();
5992 }
5993 }
5994
5995 @Override
5996 public void notifyAppTransitionCancelled() {
5997 synchronized (mGlobalLock) {
5998 mStackSupervisor.notifyAppTransitionDone();
5999 }
6000 }
6001
6002 @Override
6003 public List<IBinder> getTopVisibleActivities() {
6004 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006005 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006006 }
6007 }
6008
6009 @Override
6010 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6011 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006012 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006013 }
6014 }
6015
6016 @Override
6017 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6018 Bundle bOptions) {
6019 Preconditions.checkNotNull(intents, "intents");
6020 final String[] resolvedTypes = new String[intents.length];
6021
6022 // UID of the package on user userId.
6023 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6024 // packageUid may not be initialized.
6025 int packageUid = 0;
6026 final long ident = Binder.clearCallingIdentity();
6027
6028 try {
6029 for (int i = 0; i < intents.length; i++) {
6030 resolvedTypes[i] =
6031 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6032 }
6033
6034 packageUid = AppGlobals.getPackageManager().getPackageUid(
6035 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6036 } catch (RemoteException e) {
6037 // Shouldn't happen.
6038 } finally {
6039 Binder.restoreCallingIdentity(ident);
6040 }
6041
Riddle Hsu591bf612019-02-14 17:55:31 +08006042 return getActivityStartController().startActivitiesInPackage(
6043 packageUid, packageName,
6044 intents, resolvedTypes, null /* resultTo */,
6045 SafeActivityOptions.fromBundle(bOptions), userId,
6046 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6047 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006048 }
6049
6050 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006051 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6052 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6053 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6054 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006055 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006056 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006057 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6058 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6059 userId, validateIncomingUser, originatingPendingIntent,
6060 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006061 }
6062 }
6063
6064 @Override
6065 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6066 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6067 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6068 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006069 PendingIntentRecord originatingPendingIntent,
6070 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006071 synchronized (mGlobalLock) {
6072 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6073 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6074 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006075 validateIncomingUser, originatingPendingIntent,
6076 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006077 }
6078 }
6079
6080 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006081 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6082 Intent intent, Bundle options, int userId) {
6083 return ActivityTaskManagerService.this.startActivityAsUser(
6084 caller, callerPacakge, intent,
6085 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6086 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6087 false /*validateIncomingUser*/);
6088 }
6089
6090 @Override
lumark588a3e82018-07-20 18:53:54 +08006091 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006092 synchronized (mGlobalLock) {
6093
6094 // We might change the visibilities here, so prepare an empty app transition which
6095 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006096 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006097 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006098 if (activityDisplay == null) {
6099 return;
6100 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006101 final DisplayContent dc = activityDisplay.mDisplayContent;
6102 final boolean wasTransitionSet =
6103 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006105 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006107 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006108
6109 // If there was a transition set already we don't want to interfere with it as we
6110 // might be starting it too early.
6111 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006112 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006113 }
6114 }
6115 if (callback != null) {
6116 callback.run();
6117 }
6118 }
6119
6120 @Override
6121 public void notifyKeyguardTrustedChanged() {
6122 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006123 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006124 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 }
6126 }
6127 }
6128
6129 /**
6130 * Called after virtual display Id is updated by
6131 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6132 * {@param vrVr2dDisplayId}.
6133 */
6134 @Override
6135 public void setVr2dDisplayId(int vr2dDisplayId) {
6136 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6137 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006138 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006139 }
6140 }
6141
6142 @Override
6143 public void setFocusedActivity(IBinder token) {
6144 synchronized (mGlobalLock) {
6145 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6146 if (r == null) {
6147 throw new IllegalArgumentException(
6148 "setFocusedActivity: No activity record matching token=" + token);
6149 }
Louis Chang19443452018-10-09 12:10:21 +08006150 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006151 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006152 }
6153 }
6154 }
6155
6156 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006158 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006159 }
6160
6161 @Override
6162 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006163 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 }
6165
6166 @Override
6167 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006168 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006169 }
6170
6171 @Override
6172 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6173 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6174 }
6175
6176 @Override
6177 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006178 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006180
6181 @Override
6182 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6183 synchronized (mGlobalLock) {
6184 mActiveVoiceInteractionServiceComponent = component;
6185 }
6186 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006187
6188 @Override
6189 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6190 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6191 return;
6192 }
6193 synchronized (mGlobalLock) {
6194 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6195 if (types == null) {
6196 if (uid < 0) {
6197 return;
6198 }
6199 types = new ArrayMap<>();
6200 mAllowAppSwitchUids.put(userId, types);
6201 }
6202 if (uid < 0) {
6203 types.remove(type);
6204 } else {
6205 types.put(type, uid);
6206 }
6207 }
6208 }
6209
6210 @Override
6211 public void onUserStopped(int userId) {
6212 synchronized (mGlobalLock) {
6213 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6214 mAllowAppSwitchUids.remove(userId);
6215 }
6216 }
6217
6218 @Override
6219 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6220 synchronized (mGlobalLock) {
6221 return ActivityTaskManagerService.this.isGetTasksAllowed(
6222 caller, callingPid, callingUid);
6223 }
6224 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006225
Riddle Hsua0536432019-02-16 00:38:59 +08006226 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006227 @Override
6228 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006229 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006230 mProcessNames.put(proc.mName, proc.mUid, proc);
6231 }
6232 }
6233
Riddle Hsua0536432019-02-16 00:38:59 +08006234 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006235 @Override
6236 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006237 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006238 mProcessNames.remove(name, uid);
6239 }
6240 }
6241
Riddle Hsua0536432019-02-16 00:38:59 +08006242 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006243 @Override
6244 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006245 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006246 if (proc == mHomeProcess) {
6247 mHomeProcess = null;
6248 }
6249 if (proc == mPreviousProcess) {
6250 mPreviousProcess = null;
6251 }
6252 }
6253 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006254
Riddle Hsua0536432019-02-16 00:38:59 +08006255 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006256 @Override
6257 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006258 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006259 return mTopProcessState;
6260 }
6261 }
6262
Riddle Hsua0536432019-02-16 00:38:59 +08006263 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006264 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006265 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006266 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006267 return proc == mHeavyWeightProcess;
6268 }
6269 }
6270
Riddle Hsua0536432019-02-16 00:38:59 +08006271 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006272 @Override
6273 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006274 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006275 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6276 }
6277 }
6278
6279 @Override
6280 public void finishHeavyWeightApp() {
6281 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006282 if (mHeavyWeightProcess != null) {
6283 mHeavyWeightProcess.finishActivities();
6284 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006285 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6286 mHeavyWeightProcess);
6287 }
6288 }
6289
Riddle Hsua0536432019-02-16 00:38:59 +08006290 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006291 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006292 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006293 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006294 return isSleepingLocked();
6295 }
6296 }
6297
6298 @Override
6299 public boolean isShuttingDown() {
6300 synchronized (mGlobalLock) {
6301 return mShuttingDown;
6302 }
6303 }
6304
6305 @Override
6306 public boolean shuttingDown(boolean booted, int timeout) {
6307 synchronized (mGlobalLock) {
6308 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006309 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006310 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006311 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006312 return mStackSupervisor.shutdownLocked(timeout);
6313 }
6314 }
6315
6316 @Override
6317 public void enableScreenAfterBoot(boolean booted) {
6318 synchronized (mGlobalLock) {
6319 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6320 SystemClock.uptimeMillis());
6321 mWindowManager.enableScreenAfterBoot();
6322 updateEventDispatchingLocked(booted);
6323 }
6324 }
6325
6326 @Override
6327 public boolean showStrictModeViolationDialog() {
6328 synchronized (mGlobalLock) {
6329 return mShowDialogs && !mSleeping && !mShuttingDown;
6330 }
6331 }
6332
6333 @Override
6334 public void showSystemReadyErrorDialogsIfNeeded() {
6335 synchronized (mGlobalLock) {
6336 try {
6337 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6338 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6339 + " data partition or your device will be unstable.");
6340 mUiHandler.post(() -> {
6341 if (mShowDialogs) {
6342 AlertDialog d = new BaseErrorDialog(mUiContext);
6343 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6344 d.setCancelable(false);
6345 d.setTitle(mUiContext.getText(R.string.android_system_label));
6346 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6347 d.setButton(DialogInterface.BUTTON_POSITIVE,
6348 mUiContext.getText(R.string.ok),
6349 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6350 d.show();
6351 }
6352 });
6353 }
6354 } catch (RemoteException e) {
6355 }
6356
6357 if (!Build.isBuildConsistent()) {
6358 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6359 mUiHandler.post(() -> {
6360 if (mShowDialogs) {
6361 AlertDialog d = new BaseErrorDialog(mUiContext);
6362 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6363 d.setCancelable(false);
6364 d.setTitle(mUiContext.getText(R.string.android_system_label));
6365 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6366 d.setButton(DialogInterface.BUTTON_POSITIVE,
6367 mUiContext.getText(R.string.ok),
6368 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6369 d.show();
6370 }
6371 });
6372 }
6373 }
6374 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006375
6376 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006377 public void onProcessMapped(int pid, WindowProcessController proc) {
6378 synchronized (mGlobalLock) {
6379 mPidMap.put(pid, proc);
6380 }
6381 }
6382
6383 @Override
6384 public void onProcessUnMapped(int pid) {
6385 synchronized (mGlobalLock) {
6386 mPidMap.remove(pid);
6387 }
6388 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006389
6390 @Override
6391 public void onPackageDataCleared(String name) {
6392 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006393 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006394 mAppWarnings.onPackageDataCleared(name);
6395 }
6396 }
6397
6398 @Override
6399 public void onPackageUninstalled(String name) {
6400 synchronized (mGlobalLock) {
6401 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006403 }
6404 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006405
6406 @Override
6407 public void onPackageAdded(String name, boolean replacing) {
6408 synchronized (mGlobalLock) {
6409 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6410 }
6411 }
6412
6413 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006414 public void onPackageReplaced(ApplicationInfo aInfo) {
6415 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006416 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006417 }
6418 }
6419
6420 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006421 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6422 synchronized (mGlobalLock) {
6423 return compatibilityInfoForPackageLocked(ai);
6424 }
6425 }
6426
Yunfan Chen75157d72018-07-27 14:47:21 +09006427 /**
6428 * Set the corresponding display information for the process global configuration. To be
6429 * called when we need to show IME on a different display.
6430 *
6431 * @param pid The process id associated with the IME window.
6432 * @param displayId The ID of the display showing the IME.
6433 */
6434 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006435 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006436 if (pid == MY_PID || pid < 0) {
6437 if (DEBUG_CONFIGURATION) {
6438 Slog.w(TAG,
6439 "Trying to update display configuration for system/invalid process.");
6440 }
6441 return;
6442 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006443 synchronized (mGlobalLock) {
6444 final ActivityDisplay activityDisplay =
6445 mRootActivityContainer.getActivityDisplay(displayId);
6446 if (activityDisplay == null) {
6447 // Call might come when display is not yet added or has been removed.
6448 if (DEBUG_CONFIGURATION) {
6449 Slog.w(TAG, "Trying to update display configuration for non-existing "
6450 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006451 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006452 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006453 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006454 final WindowProcessController process = mPidMap.get(pid);
6455 if (process == null) {
6456 if (DEBUG_CONFIGURATION) {
6457 Slog.w(TAG, "Trying to update display configuration for invalid "
6458 + "process, pid=" + pid);
6459 }
6460 return;
6461 }
6462 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6463 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006464 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006465
6466 @Override
6467 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6468 int requestCode, int resultCode, Intent data) {
6469 synchronized (mGlobalLock) {
6470 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006471 if (r != null && r.getActivityStack() != null) {
6472 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6473 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006474 }
6475 }
6476 }
6477
6478 @Override
6479 public void clearPendingResultForActivity(IBinder activityToken,
6480 WeakReference<PendingIntentRecord> pir) {
6481 synchronized (mGlobalLock) {
6482 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6483 if (r != null && r.pendingResults != null) {
6484 r.pendingResults.remove(pir);
6485 }
6486 }
6487 }
6488
6489 @Override
6490 public IIntentSender getIntentSender(int type, String packageName,
6491 int callingUid, int userId, IBinder token, String resultWho,
6492 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6493 Bundle bOptions) {
6494 synchronized (mGlobalLock) {
6495 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6496 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6497 }
6498 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006499
6500 @Override
6501 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6502 synchronized (mGlobalLock) {
6503 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6504 if (r == null) {
6505 return null;
6506 }
6507 if (r.mServiceConnectionsHolder == null) {
6508 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6509 ActivityTaskManagerService.this, r);
6510 }
6511
6512 return r.mServiceConnectionsHolder;
6513 }
6514 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006515
6516 @Override
6517 public Intent getHomeIntent() {
6518 synchronized (mGlobalLock) {
6519 return ActivityTaskManagerService.this.getHomeIntent();
6520 }
6521 }
6522
6523 @Override
6524 public boolean startHomeActivity(int userId, String reason) {
6525 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006526 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006527 }
6528 }
6529
6530 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006531 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006532 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006533 synchronized (mGlobalLock) {
6534 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006535 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006536 }
Chilun8b1f1be2019-03-13 17:14:36 +08006537 }
6538
6539 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006540 public boolean startHomeOnAllDisplays(int userId, String reason) {
6541 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006542 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006543 }
6544 }
6545
Riddle Hsua0536432019-02-16 00:38:59 +08006546 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006547 @Override
6548 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006549 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006550 if (mFactoryTest == FACTORY_TEST_OFF) {
6551 return false;
6552 }
6553 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6554 && wpc.mName.equals(mTopComponent.getPackageName())) {
6555 return true;
6556 }
6557 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6558 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6559 }
6560 }
6561
6562 @Override
6563 public void updateTopComponentForFactoryTest() {
6564 synchronized (mGlobalLock) {
6565 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6566 return;
6567 }
6568 final ResolveInfo ri = mContext.getPackageManager()
6569 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6570 final CharSequence errorMsg;
6571 if (ri != null) {
6572 final ActivityInfo ai = ri.activityInfo;
6573 final ApplicationInfo app = ai.applicationInfo;
6574 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6575 mTopAction = Intent.ACTION_FACTORY_TEST;
6576 mTopData = null;
6577 mTopComponent = new ComponentName(app.packageName, ai.name);
6578 errorMsg = null;
6579 } else {
6580 errorMsg = mContext.getResources().getText(
6581 com.android.internal.R.string.factorytest_not_system);
6582 }
6583 } else {
6584 errorMsg = mContext.getResources().getText(
6585 com.android.internal.R.string.factorytest_no_action);
6586 }
6587 if (errorMsg == null) {
6588 return;
6589 }
6590
6591 mTopAction = null;
6592 mTopData = null;
6593 mTopComponent = null;
6594 mUiHandler.post(() -> {
6595 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6596 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006597 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006598 });
6599 }
6600 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006601
Riddle Hsua0536432019-02-16 00:38:59 +08006602 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006603 @Override
6604 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6605 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006606 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006607 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006608 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006609
6610 wpc.clearRecentTasks();
6611 wpc.clearActivities();
6612
6613 if (wpc.isInstrumenting()) {
6614 finishInstrumentationCallback.run();
6615 }
6616
Jorim Jaggid0752812018-10-16 16:07:20 +02006617 if (!restarting && hasVisibleActivities) {
6618 mWindowManager.deferSurfaceLayout();
6619 try {
6620 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6621 // If there was nothing to resume, and we are not already restarting
6622 // this process, but there is a visible activity that is hosted by the
6623 // process...then make sure all visible activities are running, taking
6624 // care of restarting this process.
6625 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6626 !PRESERVE_WINDOWS);
6627 }
6628 } finally {
6629 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006630 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006631 }
6632 }
6633 }
6634
6635 @Override
6636 public void closeSystemDialogs(String reason) {
6637 enforceNotIsolatedCaller("closeSystemDialogs");
6638
6639 final int pid = Binder.getCallingPid();
6640 final int uid = Binder.getCallingUid();
6641 final long origId = Binder.clearCallingIdentity();
6642 try {
6643 synchronized (mGlobalLock) {
6644 // Only allow this from foreground processes, so that background
6645 // applications can't abuse it to prevent system UI from being shown.
6646 if (uid >= FIRST_APPLICATION_UID) {
6647 final WindowProcessController proc = mPidMap.get(pid);
6648 if (!proc.isPerceptible()) {
6649 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6650 + " from background process " + proc);
6651 return;
6652 }
6653 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654 mWindowManager.closeSystemDialogs(reason);
6655
Wale Ogunwaled32da472018-11-16 07:19:28 -08006656 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006657 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006658 // Call into AM outside the synchronized block.
6659 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660 } finally {
6661 Binder.restoreCallingIdentity(origId);
6662 }
6663 }
6664
6665 @Override
6666 public void cleanupDisabledPackageComponents(
6667 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6668 synchronized (mGlobalLock) {
6669 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006670 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006671 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006672 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006673 mStackSupervisor.scheduleIdleLocked();
6674 }
6675
6676 // Clean-up disabled tasks
6677 getRecentTasks().cleanupDisabledPackageTasksLocked(
6678 packageName, disabledClasses, userId);
6679 }
6680 }
6681
6682 @Override
6683 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6684 int userId) {
6685 synchronized (mGlobalLock) {
6686
6687 boolean didSomething =
6688 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006689 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006690 null, doit, evenPersistent, userId);
6691 return didSomething;
6692 }
6693 }
6694
6695 @Override
6696 public void resumeTopActivities(boolean scheduleIdle) {
6697 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006698 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699 if (scheduleIdle) {
6700 mStackSupervisor.scheduleIdleLocked();
6701 }
6702 }
6703 }
6704
Riddle Hsua0536432019-02-16 00:38:59 +08006705 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 @Override
6707 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006708 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6710 }
6711 }
6712
Riddle Hsua0536432019-02-16 00:38:59 +08006713 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006714 @Override
6715 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006716 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006717 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 }
6719 }
6720
6721 @Override
6722 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6723 try {
6724 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6725 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6726 }
6727 } catch (RemoteException ex) {
6728 throw new SecurityException("Fail to check is caller a privileged app", ex);
6729 }
6730
6731 synchronized (mGlobalLock) {
6732 final long ident = Binder.clearCallingIdentity();
6733 try {
6734 if (mAmInternal.shouldConfirmCredentials(userId)) {
6735 if (mKeyguardController.isKeyguardLocked()) {
6736 // Showing launcher to avoid user entering credential twice.
6737 startHomeActivity(currentUserId, "notifyLockedProfile");
6738 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006739 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 }
6741 } finally {
6742 Binder.restoreCallingIdentity(ident);
6743 }
6744 }
6745 }
6746
6747 @Override
6748 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6749 mAmInternal.enforceCallingPermission(
6750 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6751
6752 synchronized (mGlobalLock) {
6753 final long ident = Binder.clearCallingIdentity();
6754 try {
6755 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6756 FLAG_ACTIVITY_TASK_ON_HOME);
6757 ActivityOptions activityOptions = options != null
6758 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006759 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006760 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006761 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006762 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006763 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006764 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6765 UserHandle.CURRENT);
6766 } finally {
6767 Binder.restoreCallingIdentity(ident);
6768 }
6769 }
6770 }
6771
6772 @Override
6773 public void writeActivitiesToProto(ProtoOutputStream proto) {
6774 synchronized (mGlobalLock) {
6775 // The output proto of "activity --proto activities"
6776 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006777 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006778 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6779 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 }
6781 }
6782
6783 @Override
6784 public void saveANRState(String reason) {
6785 synchronized (mGlobalLock) {
6786 final StringWriter sw = new StringWriter();
6787 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6788 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6789 if (reason != null) {
6790 pw.println(" Reason: " + reason);
6791 }
6792 pw.println();
6793 getActivityStartController().dump(pw, " ", null);
6794 pw.println();
6795 pw.println("-------------------------------------------------------------------------------");
6796 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6797 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6798 "" /* header */);
6799 pw.println();
6800 pw.close();
6801
6802 mLastANRState = sw.toString();
6803 }
6804 }
6805
6806 @Override
6807 public void clearSavedANRState() {
6808 synchronized (mGlobalLock) {
6809 mLastANRState = null;
6810 }
6811 }
6812
6813 @Override
6814 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6815 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6816 synchronized (mGlobalLock) {
6817 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6818 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6819 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6820 dumpLastANRLocked(pw);
6821 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6822 dumpLastANRTracesLocked(pw);
6823 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6824 dumpActivityStarterLocked(pw, dumpPackage);
6825 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6826 dumpActivityContainersLocked(pw);
6827 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6828 if (getRecentTasks() != null) {
6829 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6830 }
6831 }
6832 }
6833 }
6834
6835 @Override
6836 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6837 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6838 int wakefulness) {
6839 synchronized (mGlobalLock) {
6840 if (mHomeProcess != null && (dumpPackage == null
6841 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6842 if (needSep) {
6843 pw.println();
6844 needSep = false;
6845 }
6846 pw.println(" mHomeProcess: " + mHomeProcess);
6847 }
6848 if (mPreviousProcess != null && (dumpPackage == null
6849 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6850 if (needSep) {
6851 pw.println();
6852 needSep = false;
6853 }
6854 pw.println(" mPreviousProcess: " + mPreviousProcess);
6855 }
6856 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6857 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6858 StringBuilder sb = new StringBuilder(128);
6859 sb.append(" mPreviousProcessVisibleTime: ");
6860 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6861 pw.println(sb);
6862 }
6863 if (mHeavyWeightProcess != null && (dumpPackage == null
6864 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6865 if (needSep) {
6866 pw.println();
6867 needSep = false;
6868 }
6869 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6870 }
6871 if (dumpPackage == null) {
6872 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006873 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 }
6875 if (dumpAll) {
6876 if (dumpPackage == null) {
6877 pw.println(" mConfigWillChange: "
6878 + getTopDisplayFocusedStack().mConfigWillChange);
6879 }
6880 if (mCompatModePackages.getPackages().size() > 0) {
6881 boolean printed = false;
6882 for (Map.Entry<String, Integer> entry
6883 : mCompatModePackages.getPackages().entrySet()) {
6884 String pkg = entry.getKey();
6885 int mode = entry.getValue();
6886 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6887 continue;
6888 }
6889 if (!printed) {
6890 pw.println(" mScreenCompatPackages:");
6891 printed = true;
6892 }
6893 pw.println(" " + pkg + ": " + mode);
6894 }
6895 }
6896 }
6897
6898 if (dumpPackage == null) {
6899 pw.println(" mWakefulness="
6900 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006901 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 if (mRunningVoice != null) {
6903 pw.println(" mRunningVoice=" + mRunningVoice);
6904 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6905 }
6906 pw.println(" mSleeping=" + mSleeping);
6907 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6908 pw.println(" mVrController=" + mVrController);
6909 }
6910 if (mCurAppTimeTracker != null) {
6911 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6912 }
6913 if (mAllowAppSwitchUids.size() > 0) {
6914 boolean printed = false;
6915 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6916 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6917 for (int j = 0; j < types.size(); j++) {
6918 if (dumpPackage == null ||
6919 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6920 if (needSep) {
6921 pw.println();
6922 needSep = false;
6923 }
6924 if (!printed) {
6925 pw.println(" mAllowAppSwitchUids:");
6926 printed = true;
6927 }
6928 pw.print(" User ");
6929 pw.print(mAllowAppSwitchUids.keyAt(i));
6930 pw.print(": Type ");
6931 pw.print(types.keyAt(j));
6932 pw.print(" = ");
6933 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6934 pw.println();
6935 }
6936 }
6937 }
6938 }
6939 if (dumpPackage == null) {
6940 if (mController != null) {
6941 pw.println(" mController=" + mController
6942 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6943 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006944 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6945 pw.println(" mLaunchingActivityWakeLock="
6946 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 }
6948
6949 return needSep;
6950 }
6951 }
6952
6953 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006954 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6955 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 synchronized (mGlobalLock) {
6957 if (dumpPackage == null) {
6958 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6959 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006960 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6961 if (mRunningVoice != null) {
6962 final long vrToken = proto.start(
6963 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6964 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6965 mRunningVoice.toString());
6966 mVoiceWakeLock.writeToProto(
6967 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6968 proto.end(vrToken);
6969 }
6970 mVrController.writeToProto(proto,
6971 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006972 if (mController != null) {
6973 final long token = proto.start(CONTROLLER);
6974 proto.write(CONTROLLER, mController.toString());
6975 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6976 proto.end(token);
6977 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006978 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6979 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6980 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006981 }
6982
6983 if (mHomeProcess != null && (dumpPackage == null
6984 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006985 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 }
6987
6988 if (mPreviousProcess != null && (dumpPackage == null
6989 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006990 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006991 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6992 }
6993
6994 if (mHeavyWeightProcess != null && (dumpPackage == null
6995 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006996 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006997 }
6998
6999 for (Map.Entry<String, Integer> entry
7000 : mCompatModePackages.getPackages().entrySet()) {
7001 String pkg = entry.getKey();
7002 int mode = entry.getValue();
7003 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7004 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7005 proto.write(PACKAGE, pkg);
7006 proto.write(MODE, mode);
7007 proto.end(compatToken);
7008 }
7009 }
7010
7011 if (mCurAppTimeTracker != null) {
7012 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7013 }
7014
7015 }
7016 }
7017
7018 @Override
7019 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7020 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7021 boolean dumpFocusedStackOnly) {
7022 synchronized (mGlobalLock) {
7023 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7024 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7025 }
7026 }
7027
7028 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007029 public void dumpForOom(PrintWriter pw) {
7030 synchronized (mGlobalLock) {
7031 pw.println(" mHomeProcess: " + mHomeProcess);
7032 pw.println(" mPreviousProcess: " + mPreviousProcess);
7033 if (mHeavyWeightProcess != null) {
7034 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7035 }
7036 }
7037 }
7038
7039 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 public boolean canGcNow() {
7041 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007042 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007043 }
7044 }
7045
Riddle Hsua0536432019-02-16 00:38:59 +08007046 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007047 @Override
7048 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007049 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007050 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007051 return top != null ? top.app : null;
7052 }
7053 }
7054
Riddle Hsua0536432019-02-16 00:38:59 +08007055 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007056 @Override
7057 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007058 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007059 if (mRootActivityContainer != null) {
7060 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007061 }
7062 }
7063 }
7064
7065 @Override
7066 public void scheduleDestroyAllActivities(String reason) {
7067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007068 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007069 }
7070 }
7071
7072 @Override
7073 public void removeUser(int userId) {
7074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007075 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007076 }
7077 }
7078
7079 @Override
7080 public boolean switchUser(int userId, UserState userState) {
7081 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007082 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 }
7084 }
7085
7086 @Override
7087 public void onHandleAppCrash(WindowProcessController wpc) {
7088 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007089 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 }
7091 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007092
7093 @Override
7094 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7095 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007096 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007097 }
7098 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007099
Riddle Hsua0536432019-02-16 00:38:59 +08007100 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007101 @Override
7102 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007103 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007104 }
7105
Riddle Hsua0536432019-02-16 00:38:59 +08007106 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007107 @Override
7108 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007109 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007110 }
7111
Riddle Hsua0536432019-02-16 00:38:59 +08007112 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007113 @Override
7114 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007115 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007116 }
7117
Riddle Hsua0536432019-02-16 00:38:59 +08007118 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007119 @Override
7120 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007121 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007122 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007123
7124 @Override
7125 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007126 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007127 mPendingTempWhitelist.put(uid, tag);
7128 }
7129 }
7130
7131 @Override
7132 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007133 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007134 mPendingTempWhitelist.remove(uid);
7135 }
7136 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007137
7138 @Override
7139 public boolean handleAppCrashInActivityController(String processName, int pid,
7140 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7141 Runnable killCrashingAppCallback) {
7142 synchronized (mGlobalLock) {
7143 if (mController == null) {
7144 return false;
7145 }
7146
7147 try {
7148 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7149 stackTrace)) {
7150 killCrashingAppCallback.run();
7151 return true;
7152 }
7153 } catch (RemoteException e) {
7154 mController = null;
7155 Watchdog.getInstance().setActivityController(null);
7156 }
7157 return false;
7158 }
7159 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007160
7161 @Override
7162 public void removeRecentTasksByPackageName(String packageName, int userId) {
7163 synchronized (mGlobalLock) {
7164 mRecentTasks.removeTasksByPackageName(packageName, userId);
7165 }
7166 }
7167
7168 @Override
7169 public void cleanupRecentTasksForUser(int userId) {
7170 synchronized (mGlobalLock) {
7171 mRecentTasks.cleanupLocked(userId);
7172 }
7173 }
7174
7175 @Override
7176 public void loadRecentTasksForUser(int userId) {
7177 synchronized (mGlobalLock) {
7178 mRecentTasks.loadUserRecentsLocked(userId);
7179 }
7180 }
7181
7182 @Override
7183 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7184 synchronized (mGlobalLock) {
7185 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7186 }
7187 }
7188
7189 @Override
7190 public void flushRecentTasks() {
7191 mRecentTasks.flush();
7192 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007193
7194 @Override
7195 public WindowProcessController getHomeProcess() {
7196 synchronized (mGlobalLock) {
7197 return mHomeProcess;
7198 }
7199 }
7200
7201 @Override
7202 public WindowProcessController getPreviousProcess() {
7203 synchronized (mGlobalLock) {
7204 return mPreviousProcess;
7205 }
7206 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007207
7208 @Override
7209 public void clearLockedTasks(String reason) {
7210 synchronized (mGlobalLock) {
7211 getLockTaskController().clearLockedTasks(reason);
7212 }
7213 }
7214
7215 @Override
7216 public void updateUserConfiguration() {
7217 synchronized (mGlobalLock) {
7218 final Configuration configuration = new Configuration(getGlobalConfiguration());
7219 final int currentUserId = mAmInternal.getCurrentUserId();
7220 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7221 configuration, currentUserId, Settings.System.canWrite(mContext));
7222 updateConfigurationLocked(configuration, null /* starting */,
7223 false /* initLocale */, false /* persistent */, currentUserId,
7224 false /* deferResume */);
7225 }
7226 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007227
7228 @Override
7229 public boolean canShowErrorDialogs() {
7230 synchronized (mGlobalLock) {
7231 return mShowDialogs && !mSleeping && !mShuttingDown
7232 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7233 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7234 mAmInternal.getCurrentUserId())
7235 && !(UserManager.isDeviceInDemoMode(mContext)
7236 && mAmInternal.getCurrentUser().isDemo());
7237 }
7238 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007239
7240 @Override
7241 public void setProfileApp(String profileApp) {
7242 synchronized (mGlobalLock) {
7243 mProfileApp = profileApp;
7244 }
7245 }
7246
7247 @Override
7248 public void setProfileProc(WindowProcessController wpc) {
7249 synchronized (mGlobalLock) {
7250 mProfileProc = wpc;
7251 }
7252 }
7253
7254 @Override
7255 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7256 synchronized (mGlobalLock) {
7257 mProfilerInfo = profilerInfo;
7258 }
7259 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007260
7261 @Override
7262 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7263 synchronized (mGlobalLock) {
7264 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7265 }
7266 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007267
7268 @Override
7269 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7270 synchronized (mGlobalLock) {
7271 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7272 }
7273 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007274
7275 @Override
7276 public boolean isUidForeground(int uid) {
7277 synchronized (mGlobalLock) {
7278 return ActivityTaskManagerService.this.isUidForeground(uid);
7279 }
7280 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007281
7282 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007283 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007284 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007285 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007286 }
7287 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007288
7289 @Override
7290 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007291 // Translate package names into UIDs
7292 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007293 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007294 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7295 if (uid >= 0) {
7296 result.add(uid);
7297 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007298 }
7299 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007300 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007301 }
7302 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007303 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007304}