blob: faa98fa79be9ff9bf20f4e70407092fca939db71 [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
Wale Ogunwalee2172292018-10-25 10:11:10 -0700446 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447 KeyguardController mKeyguardController;
448 private final ClientLifecycleManager mLifecycleManager;
449 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700450 /** The controller for all operations related to locktask. */
451 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700452 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700454 boolean mSuppressResizeConfigChanges;
455
456 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
457 new UpdateConfigurationResult();
458
459 static final class UpdateConfigurationResult {
460 // Configuration changes that were updated.
461 int changes;
462 // If the activity was relaunched to match the new configuration.
463 boolean activityRelaunched;
464
465 void reset() {
466 changes = 0;
467 activityRelaunched = false;
468 }
469 }
470
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700471 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700472 private int mConfigurationSeq;
473 // To cache the list of supported system locales
474 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700475
476 /**
477 * Temp object used when global and/or display override configuration is updated. It is also
478 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
479 * anyone...
480 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 private Configuration mTempConfig = new Configuration();
482
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 /** Temporary to avoid allocations. */
484 final StringBuilder mStringBuilder = new StringBuilder(256);
485
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 // Amount of time after a call to stopAppSwitches() during which we will
487 // prevent further untrusted switches from happening.
488 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
489
490 /**
491 * The time at which we will allow normal application switches again,
492 * after a call to {@link #stopAppSwitches()}.
493 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 /**
496 * This is set to true after the first switch after mAppSwitchesAllowedTime
497 * is set; any switches after that will clear the time.
498 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500
501 IActivityController mController = null;
502 boolean mControllerIsAMonkey = false;
503
Wale Ogunwale214f3482018-10-04 11:00:47 -0700504 final int mFactoryTest;
505
506 /** Used to control how we initialize the service. */
507 ComponentName mTopComponent;
508 String mTopAction = Intent.ACTION_MAIN;
509 String mTopData;
510
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800511 /** Profiling app information. */
512 String mProfileApp = null;
513 WindowProcessController mProfileProc = null;
514 ProfilerInfo mProfilerInfo = null;
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700517 * Dump of the activity state at the time of the last ANR. Cleared after
518 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
519 */
520 String mLastANRState;
521
522 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 * Used to retain an update lock when the foreground activity is in
524 * immersive mode.
525 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700526 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527
528 /**
529 * Packages that are being allowed to perform unrestricted app switches. Mapping is
530 * User -> Type -> uid.
531 */
532 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
533
534 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700535 private int mThumbnailWidth;
536 private int mThumbnailHeight;
537 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538
539 /**
540 * Flag that indicates if multi-window is enabled.
541 *
542 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
543 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
544 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
545 * At least one of the forms of multi-window must be enabled in order for this flag to be
546 * initialized to 'true'.
547 *
548 * @see #mSupportsSplitScreenMultiWindow
549 * @see #mSupportsFreeformWindowManagement
550 * @see #mSupportsPictureInPicture
551 * @see #mSupportsMultiDisplay
552 */
553 boolean mSupportsMultiWindow;
554 boolean mSupportsSplitScreenMultiWindow;
555 boolean mSupportsFreeformWindowManagement;
556 boolean mSupportsPictureInPicture;
557 boolean mSupportsMultiDisplay;
558 boolean mForceResizableActivities;
559
560 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
561
562 // VR Vr2d Display Id.
563 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700564
Wale Ogunwalef6733932018-06-27 05:14:34 -0700565 /**
566 * Set while we are wanting to sleep, to prevent any
567 * activities from being started/resumed.
568 *
569 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
570 *
571 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
572 * while in the sleep state until there is a pending transition out of sleep, in which case
573 * mSleeping is set to false, and remains false while awake.
574 *
575 * Whether mSleeping can quickly toggled between true/false without the device actually
576 * display changing states is undefined.
577 */
578 private boolean mSleeping = false;
579
580 /**
581 * The process state used for processes that are running the top activities.
582 * This changes between TOP and TOP_SLEEPING to following mSleeping.
583 */
584 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
585
586 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
587 // automatically. Important for devices without direct input devices.
588 private boolean mShowDialogs = true;
589
590 /** Set if we are shutting down the system, similar to sleeping. */
591 boolean mShuttingDown = false;
592
593 /**
594 * We want to hold a wake lock while running a voice interaction session, since
595 * this may happen with the screen off and we need to keep the CPU running to
596 * be able to continue to interact with the user.
597 */
598 PowerManager.WakeLock mVoiceWakeLock;
599
600 /**
601 * Set while we are running a voice interaction. This overrides sleeping while it is active.
602 */
603 IVoiceInteractionSession mRunningVoice;
604
605 /**
606 * The last resumed activity. This is identical to the current resumed activity most
607 * of the time but could be different when we're pausing one activity before we resume
608 * another activity.
609 */
610 ActivityRecord mLastResumedActivity;
611
612 /**
613 * The activity that is currently being traced as the active resumed activity.
614 *
615 * @see #updateResumedAppTrace
616 */
617 private @Nullable ActivityRecord mTracedResumedActivity;
618
619 /** If non-null, we are tracking the time the user spends in the currently focused app. */
620 AppTimeTracker mCurAppTimeTracker;
621
Wale Ogunwale008163e2018-07-23 23:11:08 -0700622 private AppWarnings mAppWarnings;
623
Wale Ogunwale53783742018-09-16 10:21:51 -0700624 /**
625 * Packages that the user has asked to have run in screen size
626 * compatibility mode instead of filling the screen.
627 */
628 CompatModePackages mCompatModePackages;
629
Wale Ogunwalef6733932018-06-27 05:14:34 -0700630 private FontScaleSettingObserver mFontScaleSettingObserver;
631
Michal Karpinski4026cae2019-02-12 11:51:47 +0000632 private String mDeviceOwnerPackageName;
633
Wale Ogunwalef6733932018-06-27 05:14:34 -0700634 private final class FontScaleSettingObserver extends ContentObserver {
635 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
636 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
637
638 public FontScaleSettingObserver() {
639 super(mH);
640 final ContentResolver resolver = mContext.getContentResolver();
641 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
642 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
643 UserHandle.USER_ALL);
644 }
645
646 @Override
647 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
648 if (mFontScaleUri.equals(uri)) {
649 updateFontScaleIfNeeded(userId);
650 } else if (mHideErrorDialogsUri.equals(uri)) {
651 synchronized (mGlobalLock) {
652 updateShouldShowDialogsLocked(getGlobalConfiguration());
653 }
654 }
655 }
656 }
657
Riddle Hsua0536432019-02-16 00:38:59 +0800658 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
659 @Target(ElementType.METHOD)
660 @Retention(RetentionPolicy.SOURCE)
661 @interface HotPath {
662 int NONE = 0;
663 int OOM_ADJUSTMENT = 1;
664 int LRU_UPDATE = 2;
665 int PROCESS_CHANGE = 3;
666 int caller() default NONE;
667 }
668
Charles Chen8d98dd22018-12-26 17:36:54 +0800669 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
670 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700671 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700672 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700673 mSystemThread = ActivityThread.currentActivityThread();
674 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700675 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800676 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700677 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700678 }
679
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700680 public void onSystemReady() {
681 synchronized (mGlobalLock) {
682 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
683 PackageManager.FEATURE_CANT_SAVE_STATE);
684 mAssistUtils = new AssistUtils(mContext);
685 mVrController.onSystemReady();
686 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700687 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700688 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700689 }
690
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700691 public void onInitPowerManagement() {
692 synchronized (mGlobalLock) {
693 mStackSupervisor.initPowerManagement();
694 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
695 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
696 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
697 mVoiceWakeLock.setReferenceCounted(false);
698 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700699 }
700
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700701 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700702 mFontScaleSettingObserver = new FontScaleSettingObserver();
703 }
704
Wale Ogunwale59507092018-10-29 09:00:30 -0700705 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706 final boolean freeformWindowManagement =
707 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
708 || Settings.Global.getInt(
709 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
710
711 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
712 final boolean supportsPictureInPicture = supportsMultiWindow &&
713 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
714 final boolean supportsSplitScreenMultiWindow =
715 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
716 final boolean supportsMultiDisplay = mContext.getPackageManager()
717 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700718 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
719 final boolean forceResizable = Settings.Global.getInt(
720 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700721 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722
723 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900724 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725
726 final Configuration configuration = new Configuration();
727 Settings.System.getConfiguration(resolver, configuration);
728 if (forceRtl) {
729 // This will take care of setting the correct layout direction flags
730 configuration.setLayoutDirection(configuration.locale);
731 }
732
733 synchronized (mGlobalLock) {
734 mForceResizableActivities = forceResizable;
735 final boolean multiWindowFormEnabled = freeformWindowManagement
736 || supportsSplitScreenMultiWindow
737 || supportsPictureInPicture
738 || supportsMultiDisplay;
739 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
740 mSupportsMultiWindow = true;
741 mSupportsFreeformWindowManagement = freeformWindowManagement;
742 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
743 mSupportsPictureInPicture = supportsPictureInPicture;
744 mSupportsMultiDisplay = supportsMultiDisplay;
745 } else {
746 mSupportsMultiWindow = false;
747 mSupportsFreeformWindowManagement = false;
748 mSupportsSplitScreenMultiWindow = false;
749 mSupportsPictureInPicture = false;
750 mSupportsMultiDisplay = false;
751 }
752 mWindowManager.setForceResizableTasks(mForceResizableActivities);
753 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700754 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
755 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700756 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700757 // This happens before any activities are started, so we can change global configuration
758 // in-place.
759 updateConfigurationLocked(configuration, null, true);
760 final Configuration globalConfig = getGlobalConfiguration();
761 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
762
763 // Load resources only after the current configuration has been set.
764 final Resources res = mContext.getResources();
765 mThumbnailWidth = res.getDimensionPixelSize(
766 com.android.internal.R.dimen.thumbnail_width);
767 mThumbnailHeight = res.getDimensionPixelSize(
768 com.android.internal.R.dimen.thumbnail_height);
769
770 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
771 mFullscreenThumbnailScale = (float) res
772 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
773 (float) globalConfig.screenWidthDp;
774 } else {
775 mFullscreenThumbnailScale = res.getFraction(
776 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
777 }
778 }
779 }
780
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800781 public WindowManagerGlobalLock getGlobalLock() {
782 return mGlobalLock;
783 }
784
Yunfan Chen585f2932019-01-29 16:04:45 +0900785 /** For test purpose only. */
786 @VisibleForTesting
787 public ActivityTaskManagerInternal getAtmInternal() {
788 return mInternal;
789 }
790
Riddle Hsud93a6c42018-11-29 21:50:06 +0800791 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
792 Looper looper) {
793 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700794 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700795 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700796 final File systemDir = SystemServiceManager.ensureSystemDir();
797 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
798 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700799 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700800
801 mTempConfig.setToDefaults();
802 mTempConfig.setLocales(LocaleList.getDefault());
803 mConfigurationSeq = mTempConfig.seq = 1;
804 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800805 mRootActivityContainer = new RootActivityContainer(this);
806 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700807
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700808 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700809 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700810 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700811 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700812 mRecentTasks = createRecentTasks();
813 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700814 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 mKeyguardController = mStackSupervisor.getKeyguardController();
816 }
817
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700818 public void onActivityManagerInternalAdded() {
819 synchronized (mGlobalLock) {
820 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
821 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
822 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700823 }
824
Yunfan Chen75157d72018-07-27 14:47:21 +0900825 int increaseConfigurationSeqLocked() {
826 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
827 return mConfigurationSeq;
828 }
829
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700830 protected ActivityStackSupervisor createStackSupervisor() {
831 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
832 supervisor.initialize();
833 return supervisor;
834 }
835
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700836 public void setWindowManager(WindowManagerService wm) {
837 synchronized (mGlobalLock) {
838 mWindowManager = wm;
839 mLockTaskController.setWindowManager(wm);
840 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800841 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700843 }
844
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700845 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
846 synchronized (mGlobalLock) {
847 mUsageStatsInternal = usageStatsManager;
848 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700849 }
850
Wale Ogunwalef6733932018-06-27 05:14:34 -0700851 UserManagerService getUserManager() {
852 if (mUserManager == null) {
853 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
854 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
855 }
856 return mUserManager;
857 }
858
859 AppOpsService getAppOpsService() {
860 if (mAppOpsService == null) {
861 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
862 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
863 }
864 return mAppOpsService;
865 }
866
867 boolean hasUserRestriction(String restriction, int userId) {
868 return getUserManager().hasUserRestriction(restriction, userId);
869 }
870
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700871 protected RecentTasks createRecentTasks() {
872 return new RecentTasks(this, mStackSupervisor);
873 }
874
875 RecentTasks getRecentTasks() {
876 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700877 }
878
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700879 ClientLifecycleManager getLifecycleManager() {
880 return mLifecycleManager;
881 }
882
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700883 ActivityStartController getActivityStartController() {
884 return mActivityStartController;
885 }
886
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700887 TaskChangeNotificationController getTaskChangeNotificationController() {
888 return mTaskChangeNotificationController;
889 }
890
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700891 LockTaskController getLockTaskController() {
892 return mLockTaskController;
893 }
894
Yunfan Chen75157d72018-07-27 14:47:21 +0900895 /**
896 * Return the global configuration used by the process corresponding to the input pid. This is
897 * usually the global configuration with some overrides specific to that process.
898 */
899 Configuration getGlobalConfigurationForCallingPid() {
900 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800901 return getGlobalConfigurationForPid(pid);
902 }
903
904 /**
905 * Return the global configuration used by the process corresponding to the given pid.
906 */
907 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900908 if (pid == MY_PID || pid < 0) {
909 return getGlobalConfiguration();
910 }
911 synchronized (mGlobalLock) {
912 final WindowProcessController app = mPidMap.get(pid);
913 return app != null ? app.getConfiguration() : getGlobalConfiguration();
914 }
915 }
916
917 /**
918 * Return the device configuration info used by the process corresponding to the input pid.
919 * The value is consistent with the global configuration for the process.
920 */
921 @Override
922 public ConfigurationInfo getDeviceConfigurationInfo() {
923 ConfigurationInfo config = new ConfigurationInfo();
924 synchronized (mGlobalLock) {
925 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
926 config.reqTouchScreen = globalConfig.touchscreen;
927 config.reqKeyboardType = globalConfig.keyboard;
928 config.reqNavigation = globalConfig.navigation;
929 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
930 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
931 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
932 }
933 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
934 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
935 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
936 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700937 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900938 }
939 return config;
940 }
941
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700942 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700943 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700944 }
945
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700946 public static final class Lifecycle extends SystemService {
947 private final ActivityTaskManagerService mService;
948
949 public Lifecycle(Context context) {
950 super(context);
951 mService = new ActivityTaskManagerService(context);
952 }
953
954 @Override
955 public void onStart() {
956 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700957 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700958 }
959
Garfield Tan891146c2018-10-09 12:14:00 -0700960 @Override
961 public void onUnlockUser(int userId) {
962 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800963 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700964 }
965 }
966
967 @Override
968 public void onCleanupUser(int userId) {
969 synchronized (mService.getGlobalLock()) {
970 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
971 }
972 }
973
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700974 public ActivityTaskManagerService getService() {
975 return mService;
976 }
977 }
978
979 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980 public final int startActivity(IApplicationThread caller, String callingPackage,
981 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
982 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
983 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
984 resultWho, requestCode, startFlags, profilerInfo, bOptions,
985 UserHandle.getCallingUserId());
986 }
987
988 @Override
989 public final int startActivities(IApplicationThread caller, String callingPackage,
990 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
991 int userId) {
992 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700993 enforceNotIsolatedCaller(reason);
994 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700995 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000996 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
997 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
998 reason, null /* originatingPendingIntent */,
999 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001000 }
1001
1002 @Override
1003 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1004 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1005 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1006 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1007 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1008 true /*validateIncomingUser*/);
1009 }
1010
1011 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1012 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1013 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1014 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001017 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001018 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1019
1020 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001021 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 .setCaller(caller)
1023 .setCallingPackage(callingPackage)
1024 .setResolvedType(resolvedType)
1025 .setResultTo(resultTo)
1026 .setResultWho(resultWho)
1027 .setRequestCode(requestCode)
1028 .setStartFlags(startFlags)
1029 .setProfilerInfo(profilerInfo)
1030 .setActivityOptions(bOptions)
1031 .setMayWait(userId)
1032 .execute();
1033
1034 }
1035
1036 @Override
1037 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1038 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001039 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1040 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001041 // Refuse possible leaked file descriptors
1042 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1043 throw new IllegalArgumentException("File descriptors passed in Intent");
1044 }
1045
1046 if (!(target instanceof PendingIntentRecord)) {
1047 throw new IllegalArgumentException("Bad PendingIntent object");
1048 }
1049
1050 PendingIntentRecord pir = (PendingIntentRecord)target;
1051
1052 synchronized (mGlobalLock) {
1053 // If this is coming from the currently resumed activity, it is
1054 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001055 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 if (stack.mResumedActivity != null &&
1057 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001058 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059 }
1060 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001061 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 }
1064
1065 @Override
1066 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1067 Bundle bOptions) {
1068 // Refuse possible leaked file descriptors
1069 if (intent != null && intent.hasFileDescriptors()) {
1070 throw new IllegalArgumentException("File descriptors passed in Intent");
1071 }
1072 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1073
1074 synchronized (mGlobalLock) {
1075 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1076 if (r == null) {
1077 SafeActivityOptions.abort(options);
1078 return false;
1079 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001080 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 // The caller is not running... d'oh!
1082 SafeActivityOptions.abort(options);
1083 return false;
1084 }
1085 intent = new Intent(intent);
1086 // The caller is not allowed to change the data.
1087 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1088 // And we are resetting to find the next component...
1089 intent.setComponent(null);
1090
1091 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1092
1093 ActivityInfo aInfo = null;
1094 try {
1095 List<ResolveInfo> resolves =
1096 AppGlobals.getPackageManager().queryIntentActivities(
1097 intent, r.resolvedType,
1098 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1099 UserHandle.getCallingUserId()).getList();
1100
1101 // Look for the original activity in the list...
1102 final int N = resolves != null ? resolves.size() : 0;
1103 for (int i=0; i<N; i++) {
1104 ResolveInfo rInfo = resolves.get(i);
1105 if (rInfo.activityInfo.packageName.equals(r.packageName)
1106 && rInfo.activityInfo.name.equals(r.info.name)) {
1107 // We found the current one... the next matching is
1108 // after it.
1109 i++;
1110 if (i<N) {
1111 aInfo = resolves.get(i).activityInfo;
1112 }
1113 if (debug) {
1114 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1115 + "/" + r.info.name);
1116 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1117 ? "null" : aInfo.packageName + "/" + aInfo.name));
1118 }
1119 break;
1120 }
1121 }
1122 } catch (RemoteException e) {
1123 }
1124
1125 if (aInfo == null) {
1126 // Nobody who is next!
1127 SafeActivityOptions.abort(options);
1128 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1129 return false;
1130 }
1131
1132 intent.setComponent(new ComponentName(
1133 aInfo.applicationInfo.packageName, aInfo.name));
1134 intent.setFlags(intent.getFlags()&~(
1135 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1136 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1137 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1138 FLAG_ACTIVITY_NEW_TASK));
1139
1140 // Okay now we need to start the new activity, replacing the currently running activity.
1141 // This is a little tricky because we want to start the new one as if the current one is
1142 // finished, but not finish the current one first so that there is no flicker.
1143 // And thus...
1144 final boolean wasFinishing = r.finishing;
1145 r.finishing = true;
1146
1147 // Propagate reply information over to the new activity.
1148 final ActivityRecord resultTo = r.resultTo;
1149 final String resultWho = r.resultWho;
1150 final int requestCode = r.requestCode;
1151 r.resultTo = null;
1152 if (resultTo != null) {
1153 resultTo.removeResultsLocked(r, resultWho, requestCode);
1154 }
1155
1156 final long origId = Binder.clearCallingIdentity();
1157 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001158 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001159 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001160 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001161 .setResolvedType(r.resolvedType)
1162 .setActivityInfo(aInfo)
1163 .setResultTo(resultTo != null ? resultTo.appToken : null)
1164 .setResultWho(resultWho)
1165 .setRequestCode(requestCode)
1166 .setCallingPid(-1)
1167 .setCallingUid(r.launchedFromUid)
1168 .setCallingPackage(r.launchedFromPackage)
1169 .setRealCallingPid(-1)
1170 .setRealCallingUid(r.launchedFromUid)
1171 .setActivityOptions(options)
1172 .execute();
1173 Binder.restoreCallingIdentity(origId);
1174
1175 r.finishing = wasFinishing;
1176 if (res != ActivityManager.START_SUCCESS) {
1177 return false;
1178 }
1179 return true;
1180 }
1181 }
1182
1183 @Override
1184 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1185 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1186 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1187 final WaitResult res = new WaitResult();
1188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001189 enforceNotIsolatedCaller("startActivityAndWait");
1190 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1191 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .setCaller(caller)
1195 .setCallingPackage(callingPackage)
1196 .setResolvedType(resolvedType)
1197 .setResultTo(resultTo)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setStartFlags(startFlags)
1201 .setActivityOptions(bOptions)
1202 .setMayWait(userId)
1203 .setProfilerInfo(profilerInfo)
1204 .setWaitResult(res)
1205 .execute();
1206 }
1207 return res;
1208 }
1209
1210 @Override
1211 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1212 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1213 int startFlags, Configuration config, Bundle bOptions, int userId) {
1214 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001215 enforceNotIsolatedCaller("startActivityWithConfig");
1216 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1217 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001218 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001219 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 .setCaller(caller)
1221 .setCallingPackage(callingPackage)
1222 .setResolvedType(resolvedType)
1223 .setResultTo(resultTo)
1224 .setResultWho(resultWho)
1225 .setRequestCode(requestCode)
1226 .setStartFlags(startFlags)
1227 .setGlobalConfiguration(config)
1228 .setActivityOptions(bOptions)
1229 .setMayWait(userId)
1230 .execute();
1231 }
1232 }
1233
Alison Cichowlas3e340502018-08-07 17:15:01 -04001234
1235 @Override
1236 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1237 int callingUid = Binder.getCallingUid();
1238 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1239 throw new SecurityException("Only the system process can request a permission token, "
1240 + "received request from uid: " + callingUid);
1241 }
1242 IBinder permissionToken = new Binder();
1243 synchronized (mGlobalLock) {
1244 mStartActivitySources.put(permissionToken, delegatorToken);
1245 }
1246
1247 Message expireMsg = PooledLambda.obtainMessage(
1248 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1249 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1250
1251 Message forgetMsg = PooledLambda.obtainMessage(
1252 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1253 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1254
1255 return permissionToken;
1256 }
1257
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001258 @Override
1259 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1260 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001261 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1262 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001263 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001264 // permission grants) as any app that may launch one of your own activities. So we only
1265 // allow this in two cases:
1266 // 1) The caller is an activity that is part of the core framework, and then only when it
1267 // is running as the system.
1268 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1269 // can only be requested by a system activity, which may then delegate this call to
1270 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 final ActivityRecord sourceRecord;
1272 final int targetUid;
1273 final String targetPackage;
1274 final boolean isResolver;
1275 synchronized (mGlobalLock) {
1276 if (resultTo == null) {
1277 throw new SecurityException("Must be called from an activity");
1278 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 final IBinder sourceToken;
1280 if (permissionToken != null) {
1281 // To even attempt to use a permissionToken, an app must also have this signature
1282 // permission.
1283 mAmInternal.enforceCallingPermission(
1284 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1285 "startActivityAsCaller");
1286 // If called with a permissionToken, we want the sourceRecord from the delegator
1287 // activity that requested this token.
1288 sourceToken = mStartActivitySources.remove(permissionToken);
1289 if (sourceToken == null) {
1290 // Invalid permissionToken, check if it recently expired.
1291 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1292 throw new SecurityException("Called with expired permission token: "
1293 + permissionToken);
1294 } else {
1295 throw new SecurityException("Called with invalid permission token: "
1296 + permissionToken);
1297 }
1298 }
1299 } else {
1300 // This method was called directly by the source.
1301 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001302 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001303
Wale Ogunwaled32da472018-11-16 07:19:28 -08001304 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001305 if (sourceRecord == null) {
1306 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001307 }
1308 if (sourceRecord.app == null) {
1309 throw new SecurityException("Called without a process attached to activity");
1310 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001311
1312 // Whether called directly or from a delegate, the source activity must be from the
1313 // android package.
1314 if (!sourceRecord.info.packageName.equals("android")) {
1315 throw new SecurityException("Must be called from an activity that is "
1316 + "declared in the android package");
1317 }
1318
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001319 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 // This is still okay, as long as this activity is running under the
1321 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001322 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001324 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 + " must be system uid or original calling uid "
1326 + sourceRecord.launchedFromUid);
1327 }
1328 }
1329 if (ignoreTargetSecurity) {
1330 if (intent.getComponent() == null) {
1331 throw new SecurityException(
1332 "Component must be specified with ignoreTargetSecurity");
1333 }
1334 if (intent.getSelector() != null) {
1335 throw new SecurityException(
1336 "Selector not allowed with ignoreTargetSecurity");
1337 }
1338 }
1339 targetUid = sourceRecord.launchedFromUid;
1340 targetPackage = sourceRecord.launchedFromPackage;
1341 isResolver = sourceRecord.isResolverOrChildActivity();
1342 }
1343
1344 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001345 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 }
1347
1348 // TODO: Switch to user app stacks here.
1349 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001350 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 .setCallingUid(targetUid)
1352 .setCallingPackage(targetPackage)
1353 .setResolvedType(resolvedType)
1354 .setResultTo(resultTo)
1355 .setResultWho(resultWho)
1356 .setRequestCode(requestCode)
1357 .setStartFlags(startFlags)
1358 .setActivityOptions(bOptions)
1359 .setMayWait(userId)
1360 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1361 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1362 .execute();
1363 } catch (SecurityException e) {
1364 // XXX need to figure out how to propagate to original app.
1365 // A SecurityException here is generally actually a fault of the original
1366 // calling activity (such as a fairly granting permissions), so propagate it
1367 // back to them.
1368 /*
1369 StringBuilder msg = new StringBuilder();
1370 msg.append("While launching");
1371 msg.append(intent.toString());
1372 msg.append(": ");
1373 msg.append(e.getMessage());
1374 */
1375 throw e;
1376 }
1377 }
1378
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001379 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1380 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1381 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1382 }
1383
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 @Override
1385 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1386 Intent intent, String resolvedType, IVoiceInteractionSession session,
1387 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1388 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001389 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 if (session == null || interactor == null) {
1391 throw new NullPointerException("null session or interactor");
1392 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001393 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001395 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .setCallingUid(callingUid)
1397 .setCallingPackage(callingPackage)
1398 .setResolvedType(resolvedType)
1399 .setVoiceSession(session)
1400 .setVoiceInteractor(interactor)
1401 .setStartFlags(startFlags)
1402 .setProfilerInfo(profilerInfo)
1403 .setActivityOptions(bOptions)
1404 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001405 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 .execute();
1407 }
1408
1409 @Override
1410 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1411 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001412 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1413 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001415 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 .setCallingUid(callingUid)
1417 .setCallingPackage(callingPackage)
1418 .setResolvedType(resolvedType)
1419 .setActivityOptions(bOptions)
1420 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001421 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 .execute();
1423 }
1424
1425 @Override
1426 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1427 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 final int callingPid = Binder.getCallingPid();
1430 final long origId = Binder.clearCallingIdentity();
1431 try {
1432 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001433 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1434 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435
1436 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1438 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1440 recentsUid, assistDataReceiver);
1441 }
1442 } finally {
1443 Binder.restoreCallingIdentity(origId);
1444 }
1445 }
1446
1447 @Override
1448 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450 "startActivityFromRecents()");
1451
1452 final int callingPid = Binder.getCallingPid();
1453 final int callingUid = Binder.getCallingUid();
1454 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1455 final long origId = Binder.clearCallingIdentity();
1456 try {
1457 synchronized (mGlobalLock) {
1458 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1459 safeOptions);
1460 }
1461 } finally {
1462 Binder.restoreCallingIdentity(origId);
1463 }
1464 }
1465
1466 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001467 * Public API to check if the client is allowed to start an activity on specified display.
1468 *
1469 * If the target display is private or virtual, some restrictions will apply.
1470 *
1471 * @param displayId Target display id.
1472 * @param intent Intent used to launch the activity.
1473 * @param resolvedType The MIME type of the intent.
1474 * @param userId The id of the user for whom the call is made.
1475 * @return {@code true} if a call to start an activity on the target display should succeed and
1476 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1477 */
1478 @Override
1479 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1480 String resolvedType, int userId) {
1481 final int callingUid = Binder.getCallingUid();
1482 final int callingPid = Binder.getCallingPid();
1483 final long origId = Binder.clearCallingIdentity();
1484
1485 try {
1486 // Collect information about the target of the Intent.
1487 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1488 0 /* startFlags */, null /* profilerInfo */, userId,
1489 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1490 UserHandle.USER_NULL));
1491 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1492
1493 synchronized (mGlobalLock) {
1494 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1495 aInfo);
1496 }
1497 } finally {
1498 Binder.restoreCallingIdentity(origId);
1499 }
1500 }
1501
1502 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 * This is the internal entry point for handling Activity.finish().
1504 *
1505 * @param token The Binder token referencing the Activity we want to finish.
1506 * @param resultCode Result code, if any, from this Activity.
1507 * @param resultData Result data (Intent), if any, from this Activity.
1508 * @param finishTask Whether to finish the task associated with this Activity.
1509 *
1510 * @return Returns true if the activity successfully finished, or false if it is still running.
1511 */
1512 @Override
1513 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1514 int finishTask) {
1515 // Refuse possible leaked file descriptors
1516 if (resultData != null && resultData.hasFileDescriptors()) {
1517 throw new IllegalArgumentException("File descriptors passed in Intent");
1518 }
1519
1520 synchronized (mGlobalLock) {
1521 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1522 if (r == null) {
1523 return true;
1524 }
1525 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001526 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001527 ActivityRecord rootR = tr.getRootActivity();
1528 if (rootR == null) {
1529 Slog.w(TAG, "Finishing task with all activities already finished");
1530 }
1531 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1532 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001533 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 return false;
1535 }
1536
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001537 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1538 // We should consolidate.
1539 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001540 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001541 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001542 if (next != null) {
1543 // ask watcher if this is allowed
1544 boolean resumeOK = true;
1545 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001546 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001548 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001549 Watchdog.getInstance().setActivityController(null);
1550 }
1551
1552 if (!resumeOK) {
1553 Slog.i(TAG, "Not finishing activity because controller resumed");
1554 return false;
1555 }
1556 }
1557 }
1558 final long origId = Binder.clearCallingIdentity();
1559 try {
1560 boolean res;
1561 final boolean finishWithRootActivity =
1562 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1563 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1564 || (finishWithRootActivity && r == rootR)) {
1565 // If requested, remove the task that is associated to this activity only if it
1566 // was the root activity in the task. The result code and data is ignored
1567 // because we don't support returning them across task boundaries. Also, to
1568 // keep backwards compatibility we remove the task from recents when finishing
1569 // task with root activity.
1570 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1571 finishWithRootActivity, "finish-activity");
1572 if (!res) {
1573 Slog.i(TAG, "Removing task failed to finish activity");
1574 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001575 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001576 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 } else {
1578 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1579 resultData, "app-request", true);
1580 if (!res) {
1581 Slog.i(TAG, "Failed to finish by app-request");
1582 }
1583 }
1584 return res;
1585 } finally {
1586 Binder.restoreCallingIdentity(origId);
1587 }
1588 }
1589 }
1590
1591 @Override
1592 public boolean finishActivityAffinity(IBinder token) {
1593 synchronized (mGlobalLock) {
1594 final long origId = Binder.clearCallingIdentity();
1595 try {
1596 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1597 if (r == null) {
1598 return false;
1599 }
1600
1601 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1602 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001603 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001604 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 return false;
1606 }
1607 return task.getStack().finishActivityAffinityLocked(r);
1608 } finally {
1609 Binder.restoreCallingIdentity(origId);
1610 }
1611 }
1612 }
1613
1614 @Override
1615 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1616 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001617 try {
1618 WindowProcessController proc = null;
1619 synchronized (mGlobalLock) {
1620 ActivityStack stack = ActivityRecord.getStackLocked(token);
1621 if (stack == null) {
1622 return;
1623 }
1624 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1625 false /* fromTimeout */, false /* processPausingActivities */, config);
1626 if (r != null) {
1627 proc = r.app;
1628 }
1629 if (stopProfiling && proc != null) {
1630 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001631 }
1632 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001633 } finally {
1634 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001636 }
1637
1638 @Override
1639 public final void activityResumed(IBinder token) {
1640 final long origId = Binder.clearCallingIdentity();
1641 synchronized (mGlobalLock) {
1642 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001643 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 }
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647
1648 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001649 public final void activityTopResumedStateLost() {
1650 final long origId = Binder.clearCallingIdentity();
1651 synchronized (mGlobalLock) {
1652 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1653 }
1654 Binder.restoreCallingIdentity(origId);
1655 }
1656
1657 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 public final void activityPaused(IBinder token) {
1659 final long origId = Binder.clearCallingIdentity();
1660 synchronized (mGlobalLock) {
1661 ActivityStack stack = ActivityRecord.getStackLocked(token);
1662 if (stack != null) {
1663 stack.activityPausedLocked(token, false);
1664 }
1665 }
1666 Binder.restoreCallingIdentity(origId);
1667 }
1668
1669 @Override
1670 public final void activityStopped(IBinder token, Bundle icicle,
1671 PersistableBundle persistentState, CharSequence description) {
1672 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1673
1674 // Refuse possible leaked file descriptors
1675 if (icicle != null && icicle.hasFileDescriptors()) {
1676 throw new IllegalArgumentException("File descriptors passed in Bundle");
1677 }
1678
1679 final long origId = Binder.clearCallingIdentity();
1680
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001681 String restartingName = null;
1682 int restartingUid = 0;
1683 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001685 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001687 if (r.attachedToProcess()
1688 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1689 // The activity was requested to restart from
1690 // {@link #restartActivityProcessIfVisible}.
1691 restartingName = r.app.mName;
1692 restartingUid = r.app.mUid;
1693 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 r.activityStoppedLocked(icicle, persistentState, description);
1695 }
1696 }
1697
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001698 if (restartingName != null) {
1699 // In order to let the foreground activity can be restarted with its saved state from
1700 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1701 // until the activity reports stopped with the state. And the activity record will be
1702 // kept because the record state is restarting, then the activity will be restarted
1703 // immediately if it is still the top one.
1704 mStackSupervisor.removeRestartTimeouts(r);
1705 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1706 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001707 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708
1709 Binder.restoreCallingIdentity(origId);
1710 }
1711
1712 @Override
1713 public final void activityDestroyed(IBinder token) {
1714 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1715 synchronized (mGlobalLock) {
1716 ActivityStack stack = ActivityRecord.getStackLocked(token);
1717 if (stack != null) {
1718 stack.activityDestroyedLocked(token, "activityDestroyed");
1719 }
1720 }
1721 }
1722
1723 @Override
1724 public final void activityRelaunched(IBinder token) {
1725 final long origId = Binder.clearCallingIdentity();
1726 synchronized (mGlobalLock) {
1727 mStackSupervisor.activityRelaunchedLocked(token);
1728 }
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 public final void activitySlept(IBinder token) {
1733 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1734
1735 final long origId = Binder.clearCallingIdentity();
1736
1737 synchronized (mGlobalLock) {
1738 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1739 if (r != null) {
1740 mStackSupervisor.activitySleptLocked(r);
1741 }
1742 }
1743
1744 Binder.restoreCallingIdentity(origId);
1745 }
1746
1747 @Override
1748 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1749 synchronized (mGlobalLock) {
1750 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1751 if (r == null) {
1752 return;
1753 }
1754 final long origId = Binder.clearCallingIdentity();
1755 try {
1756 r.setRequestedOrientation(requestedOrientation);
1757 } finally {
1758 Binder.restoreCallingIdentity(origId);
1759 }
1760 }
1761 }
1762
1763 @Override
1764 public int getRequestedOrientation(IBinder token) {
1765 synchronized (mGlobalLock) {
1766 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1767 if (r == null) {
1768 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1769 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001770 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 }
1772 }
1773
1774 @Override
1775 public void setImmersive(IBinder token, boolean immersive) {
1776 synchronized (mGlobalLock) {
1777 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1778 if (r == null) {
1779 throw new IllegalArgumentException();
1780 }
1781 r.immersive = immersive;
1782
1783 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001784 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001785 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001786 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
1788 }
1789 }
1790
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001791 void applyUpdateLockStateLocked(ActivityRecord r) {
1792 // Modifications to the UpdateLock state are done on our handler, outside
1793 // the activity manager's locks. The new state is determined based on the
1794 // state *now* of the relevant activity record. The object is passed to
1795 // the handler solely for logging detail, not to be consulted/modified.
1796 final boolean nextState = r != null && r.immersive;
1797 mH.post(() -> {
1798 if (mUpdateLock.isHeld() != nextState) {
1799 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1800 "Applying new update lock state '" + nextState + "' for " + r);
1801 if (nextState) {
1802 mUpdateLock.acquire();
1803 } else {
1804 mUpdateLock.release();
1805 }
1806 }
1807 });
1808 }
1809
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 @Override
1811 public boolean isImmersive(IBinder token) {
1812 synchronized (mGlobalLock) {
1813 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1814 if (r == null) {
1815 throw new IllegalArgumentException();
1816 }
1817 return r.immersive;
1818 }
1819 }
1820
1821 @Override
1822 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001823 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001825 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 return (r != null) ? r.immersive : false;
1827 }
1828 }
1829
1830 @Override
1831 public void overridePendingTransition(IBinder token, String packageName,
1832 int enterAnim, int exitAnim) {
1833 synchronized (mGlobalLock) {
1834 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1835 if (self == null) {
1836 return;
1837 }
1838
1839 final long origId = Binder.clearCallingIdentity();
1840
1841 if (self.isState(
1842 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001843 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001844 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001845 }
1846
1847 Binder.restoreCallingIdentity(origId);
1848 }
1849 }
1850
1851 @Override
1852 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001855 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001856 if (r == null) {
1857 return ActivityManager.COMPAT_MODE_UNKNOWN;
1858 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001859 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 }
1861 }
1862
1863 @Override
1864 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001865 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001867 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001869 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 if (r == null) {
1871 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1872 return;
1873 }
1874 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001875 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 }
1877 }
1878
1879 @Override
1880 public int getLaunchedFromUid(IBinder activityToken) {
1881 ActivityRecord srec;
1882 synchronized (mGlobalLock) {
1883 srec = ActivityRecord.forTokenLocked(activityToken);
1884 }
1885 if (srec == null) {
1886 return -1;
1887 }
1888 return srec.launchedFromUid;
1889 }
1890
1891 @Override
1892 public String getLaunchedFromPackage(IBinder activityToken) {
1893 ActivityRecord srec;
1894 synchronized (mGlobalLock) {
1895 srec = ActivityRecord.forTokenLocked(activityToken);
1896 }
1897 if (srec == null) {
1898 return null;
1899 }
1900 return srec.launchedFromPackage;
1901 }
1902
1903 @Override
1904 public boolean convertFromTranslucent(IBinder token) {
1905 final long origId = Binder.clearCallingIdentity();
1906 try {
1907 synchronized (mGlobalLock) {
1908 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1909 if (r == null) {
1910 return false;
1911 }
1912 final boolean translucentChanged = r.changeWindowTranslucency(true);
1913 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001914 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001916 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001917 return translucentChanged;
1918 }
1919 } finally {
1920 Binder.restoreCallingIdentity(origId);
1921 }
1922 }
1923
1924 @Override
1925 public boolean convertToTranslucent(IBinder token, Bundle options) {
1926 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1927 final long origId = Binder.clearCallingIdentity();
1928 try {
1929 synchronized (mGlobalLock) {
1930 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1931 if (r == null) {
1932 return false;
1933 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001934 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 int index = task.mActivities.lastIndexOf(r);
1936 if (index > 0) {
1937 ActivityRecord under = task.mActivities.get(index - 1);
1938 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1939 }
1940 final boolean translucentChanged = r.changeWindowTranslucency(false);
1941 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001942 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001943 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001944 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001945 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 return translucentChanged;
1947 }
1948 } finally {
1949 Binder.restoreCallingIdentity(origId);
1950 }
1951 }
1952
1953 @Override
1954 public void notifyActivityDrawn(IBinder token) {
1955 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1956 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001957 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001959 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
1961 }
1962 }
1963
1964 @Override
1965 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1966 synchronized (mGlobalLock) {
1967 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1968 if (r == null) {
1969 return;
1970 }
1971 r.reportFullyDrawnLocked(restoredFromBundle);
1972 }
1973 }
1974
1975 @Override
1976 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1977 synchronized (mGlobalLock) {
1978 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1979 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1980 return stack.mDisplayId;
1981 }
1982 return DEFAULT_DISPLAY;
1983 }
1984 }
1985
1986 @Override
1987 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001988 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 long ident = Binder.clearCallingIdentity();
1990 try {
1991 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001992 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001994 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 }
1996 return null;
1997 }
1998 } finally {
1999 Binder.restoreCallingIdentity(ident);
2000 }
2001 }
2002
2003 @Override
2004 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002005 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2007 final long callingId = Binder.clearCallingIdentity();
2008 try {
2009 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002010 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 if (stack == null) {
2012 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2013 return;
2014 }
2015 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002016 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002017 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 }
2019 }
2020 } finally {
2021 Binder.restoreCallingIdentity(callingId);
2022 }
2023 }
2024
2025 @Override
2026 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002027 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2029 final long callingId = Binder.clearCallingIdentity();
2030 try {
2031 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002032 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002033 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 if (task == null) {
2035 return;
2036 }
2037 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002038 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002039 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 }
2042 } finally {
2043 Binder.restoreCallingIdentity(callingId);
2044 }
2045 }
2046
2047 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002048 public void restartActivityProcessIfVisible(IBinder activityToken) {
2049 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2050 final long callingId = Binder.clearCallingIdentity();
2051 try {
2052 synchronized (mGlobalLock) {
2053 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2054 if (r == null) {
2055 return;
2056 }
2057 r.restartProcessIfVisible();
2058 }
2059 } finally {
2060 Binder.restoreCallingIdentity(callingId);
2061 }
2062 }
2063
2064 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002065 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 synchronized (mGlobalLock) {
2068 final long ident = Binder.clearCallingIdentity();
2069 try {
2070 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2071 "remove-task");
2072 } finally {
2073 Binder.restoreCallingIdentity(ident);
2074 }
2075 }
2076 }
2077
2078 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002079 public void removeAllVisibleRecentTasks() {
2080 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2081 synchronized (mGlobalLock) {
2082 final long ident = Binder.clearCallingIdentity();
2083 try {
2084 getRecentTasks().removeAllVisibleTasks();
2085 } finally {
2086 Binder.restoreCallingIdentity(ident);
2087 }
2088 }
2089 }
2090
2091 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2093 synchronized (mGlobalLock) {
2094 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2095 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002096 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 }
2098 }
2099 return false;
2100 }
2101
2102 @Override
2103 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2104 Intent resultData) {
2105
2106 synchronized (mGlobalLock) {
2107 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2108 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002109 return r.getActivityStack().navigateUpToLocked(
2110 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 }
2112 return false;
2113 }
2114 }
2115
2116 /**
2117 * Attempts to move a task backwards in z-order (the order of activities within the task is
2118 * unchanged).
2119 *
2120 * There are several possible results of this call:
2121 * - if the task is locked, then we will show the lock toast
2122 * - if there is a task behind the provided task, then that task is made visible and resumed as
2123 * this task is moved to the back
2124 * - otherwise, if there are no other tasks in the stack:
2125 * - if this task is in the pinned stack, then we remove the stack completely, which will
2126 * have the effect of moving the task to the top or bottom of the fullscreen stack
2127 * (depending on whether it is visible)
2128 * - otherwise, we simply return home and hide this task
2129 *
2130 * @param token A reference to the activity we wish to move
2131 * @param nonRoot If false then this only works if the activity is the root
2132 * of a task; if true it will work for any activity in a task.
2133 * @return Returns true if the move completed, false if not.
2134 */
2135 @Override
2136 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002137 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 synchronized (mGlobalLock) {
2139 final long origId = Binder.clearCallingIdentity();
2140 try {
2141 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002142 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002143 if (task != null) {
2144 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2145 }
2146 } finally {
2147 Binder.restoreCallingIdentity(origId);
2148 }
2149 }
2150 return false;
2151 }
2152
2153 @Override
2154 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002155 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 long ident = Binder.clearCallingIdentity();
2157 Rect rect = new Rect();
2158 try {
2159 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002160 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2162 if (task == null) {
2163 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2164 return rect;
2165 }
2166 if (task.getStack() != null) {
2167 // Return the bounds from window manager since it will be adjusted for various
2168 // things like the presense of a docked stack for tasks that aren't resizeable.
2169 task.getWindowContainerBounds(rect);
2170 } else {
2171 // Task isn't in window manager yet since it isn't associated with a stack.
2172 // Return the persist value from activity manager
2173 if (!task.matchParentBounds()) {
2174 rect.set(task.getBounds());
2175 } else if (task.mLastNonFullscreenBounds != null) {
2176 rect.set(task.mLastNonFullscreenBounds);
2177 }
2178 }
2179 }
2180 } finally {
2181 Binder.restoreCallingIdentity(ident);
2182 }
2183 return rect;
2184 }
2185
2186 @Override
2187 public ActivityManager.TaskDescription getTaskDescription(int id) {
2188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002189 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002191 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2193 if (tr != null) {
2194 return tr.lastTaskDescription;
2195 }
2196 }
2197 return null;
2198 }
2199
2200 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002201 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2202 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2203 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2204 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2205 return;
2206 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002207 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002208 synchronized (mGlobalLock) {
2209 final long ident = Binder.clearCallingIdentity();
2210 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002211 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002212 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002213 if (task == null) {
2214 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2215 return;
2216 }
2217
2218 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2219 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2220
2221 if (!task.isActivityTypeStandardOrUndefined()) {
2222 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2223 + " non-standard task " + taskId + " to windowing mode="
2224 + windowingMode);
2225 }
2226
2227 final ActivityStack stack = task.getStack();
2228 if (toTop) {
2229 stack.moveToFront("setTaskWindowingMode", task);
2230 }
2231 stack.setWindowingMode(windowingMode);
2232 } finally {
2233 Binder.restoreCallingIdentity(ident);
2234 }
2235 }
2236 }
2237
2238 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002240 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 ActivityRecord r = getCallingRecordLocked(token);
2242 return r != null ? r.info.packageName : null;
2243 }
2244 }
2245
2246 @Override
2247 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002248 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 ActivityRecord r = getCallingRecordLocked(token);
2250 return r != null ? r.intent.getComponent() : null;
2251 }
2252 }
2253
2254 private ActivityRecord getCallingRecordLocked(IBinder token) {
2255 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2256 if (r == null) {
2257 return null;
2258 }
2259 return r.resultTo;
2260 }
2261
2262 @Override
2263 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002264 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265
2266 synchronized (mGlobalLock) {
2267 final long origId = Binder.clearCallingIdentity();
2268 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002269 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002270 } finally {
2271 Binder.restoreCallingIdentity(origId);
2272 }
2273 }
2274 }
2275
2276 /**
2277 * TODO: Add mController hook
2278 */
2279 @Override
2280 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002281 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002282
2283 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2284 synchronized (mGlobalLock) {
2285 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2286 false /* fromRecents */);
2287 }
2288 }
2289
2290 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2291 boolean fromRecents) {
2292
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002293 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 Binder.getCallingUid(), -1, -1, "Task to front")) {
2295 SafeActivityOptions.abort(options);
2296 return;
2297 }
2298 final long origId = Binder.clearCallingIdentity();
2299 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002300 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301 if (task == null) {
2302 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002303 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 return;
2305 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002306 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002308 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 return;
2310 }
2311 ActivityOptions realOptions = options != null
2312 ? options.getOptions(mStackSupervisor)
2313 : null;
2314 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2315 false /* forceNonResizable */);
2316
2317 final ActivityRecord topActivity = task.getTopActivity();
2318 if (topActivity != null) {
2319
2320 // We are reshowing a task, use a starting window to hide the initial draw delay
2321 // so the transition can start earlier.
2322 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2323 true /* taskSwitch */, fromRecents);
2324 }
2325 } finally {
2326 Binder.restoreCallingIdentity(origId);
2327 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 }
2329
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002330 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2331 int callingPid, int callingUid, String name) {
2332 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2333 return true;
2334 }
2335
2336 if (getRecentTasks().isCallerRecents(sourceUid)) {
2337 return true;
2338 }
2339
2340 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2341 if (perm == PackageManager.PERMISSION_GRANTED) {
2342 return true;
2343 }
2344 if (checkAllowAppSwitchUid(sourceUid)) {
2345 return true;
2346 }
2347
2348 // If the actual IPC caller is different from the logical source, then
2349 // also see if they are allowed to control app switches.
2350 if (callingUid != -1 && callingUid != sourceUid) {
2351 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2352 if (perm == PackageManager.PERMISSION_GRANTED) {
2353 return true;
2354 }
2355 if (checkAllowAppSwitchUid(callingUid)) {
2356 return true;
2357 }
2358 }
2359
2360 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2361 return false;
2362 }
2363
2364 private boolean checkAllowAppSwitchUid(int uid) {
2365 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2366 if (types != null) {
2367 for (int i = types.size() - 1; i >= 0; i--) {
2368 if (types.valueAt(i).intValue() == uid) {
2369 return true;
2370 }
2371 }
2372 }
2373 return false;
2374 }
2375
2376 @Override
2377 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2378 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2379 "setActivityController()");
2380 synchronized (mGlobalLock) {
2381 mController = controller;
2382 mControllerIsAMonkey = imAMonkey;
2383 Watchdog.getInstance().setActivityController(controller);
2384 }
2385 }
2386
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002387 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002388 synchronized (mGlobalLock) {
2389 return mController != null && mControllerIsAMonkey;
2390 }
2391 }
2392
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 @Override
2394 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2395 synchronized (mGlobalLock) {
2396 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2397 }
2398 }
2399
2400 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002401 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2402 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2403 }
2404
2405 @Override
2406 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2407 @WindowConfiguration.ActivityType int ignoreActivityType,
2408 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2409 final int callingUid = Binder.getCallingUid();
2410 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2411
2412 synchronized (mGlobalLock) {
2413 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2414
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002417 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002418 ignoreWindowingMode, callingUid, allowed);
2419 }
2420
2421 return list;
2422 }
2423
2424 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002425 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2426 synchronized (mGlobalLock) {
2427 final long origId = Binder.clearCallingIdentity();
2428 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2429 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002430 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002431 }
2432 Binder.restoreCallingIdentity(origId);
2433 }
2434 }
2435
2436 @Override
2437 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002438 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002439 ActivityStack stack = ActivityRecord.getStackLocked(token);
2440 if (stack != null) {
2441 return stack.willActivityBeVisibleLocked(token);
2442 }
2443 return false;
2444 }
2445 }
2446
2447 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002448 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002449 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002450 synchronized (mGlobalLock) {
2451 final long ident = Binder.clearCallingIdentity();
2452 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002453 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002454 if (task == null) {
2455 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2456 return;
2457 }
2458
2459 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2460 + " to stackId=" + stackId + " toTop=" + toTop);
2461
Wale Ogunwaled32da472018-11-16 07:19:28 -08002462 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002463 if (stack == null) {
2464 throw new IllegalStateException(
2465 "moveTaskToStack: No stack for stackId=" + stackId);
2466 }
2467 if (!stack.isActivityTypeStandardOrUndefined()) {
2468 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2469 + taskId + " to stack " + stackId);
2470 }
2471 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002472 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002473 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2474 }
2475 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2476 "moveTaskToStack");
2477 } finally {
2478 Binder.restoreCallingIdentity(ident);
2479 }
2480 }
2481 }
2482
2483 @Override
2484 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2485 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002486 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002487
2488 final long ident = Binder.clearCallingIdentity();
2489 try {
2490 synchronized (mGlobalLock) {
2491 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002492 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002493 if (stack == null) {
2494 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2495 return;
2496 }
2497 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2498 throw new IllegalArgumentException("Stack: " + stackId
2499 + " doesn't support animated resize.");
2500 }
2501 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2502 animationDuration, false /* fromFullscreen */);
2503 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002504 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 if (stack == null) {
2506 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2507 return;
2508 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002509 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002510 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2511 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2512 }
2513 }
2514 } finally {
2515 Binder.restoreCallingIdentity(ident);
2516 }
2517 }
2518
wilsonshih5c4cf522019-01-25 09:03:47 +08002519 @Override
2520 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2521 int animationDuration) {
2522 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2523
2524 final long ident = Binder.clearCallingIdentity();
2525 try {
2526 synchronized (mGlobalLock) {
2527 if (xOffset == 0 && yOffset == 0) {
2528 return;
2529 }
2530 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2531 if (stack == null) {
2532 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2533 return;
2534 }
2535 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2536 throw new IllegalArgumentException("Stack: " + stackId
2537 + " doesn't support animated resize.");
2538 }
2539 final Rect destBounds = new Rect();
2540 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002541 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002542 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2543 return;
2544 }
2545 destBounds.offset(xOffset, yOffset);
2546 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2547 animationDuration, false /* fromFullscreen */);
2548 }
2549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
2552 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 /**
2554 * Moves the specified task to the primary-split-screen stack.
2555 *
2556 * @param taskId Id of task to move.
2557 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2558 * exist already. See
2559 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2560 * and
2561 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2562 * @param toTop If the task and stack should be moved to the top.
2563 * @param animate Whether we should play an animation for the moving the task.
2564 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2565 * stack. Pass {@code null} to use default bounds.
2566 * @param showRecents If the recents activity should be shown on the other side of the task
2567 * going into split-screen mode.
2568 */
2569 @Override
2570 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2571 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 "setTaskWindowingModeSplitScreenPrimary()");
2574 synchronized (mGlobalLock) {
2575 final long ident = Binder.clearCallingIdentity();
2576 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002577 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002578 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002579 if (task == null) {
2580 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2581 return false;
2582 }
2583 if (DEBUG_STACK) Slog.d(TAG_STACK,
2584 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2585 + " to createMode=" + createMode + " toTop=" + toTop);
2586 if (!task.isActivityTypeStandardOrUndefined()) {
2587 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2588 + " non-standard task " + taskId + " to split-screen windowing mode");
2589 }
2590
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002591 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 final int windowingMode = task.getWindowingMode();
2593 final ActivityStack stack = task.getStack();
2594 if (toTop) {
2595 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2596 }
2597 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002598 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2599 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002600 return windowingMode != task.getWindowingMode();
2601 } finally {
2602 Binder.restoreCallingIdentity(ident);
2603 }
2604 }
2605 }
2606
2607 /**
2608 * Removes stacks in the input windowing modes from the system if they are of activity type
2609 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2610 */
2611 @Override
2612 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002613 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002614 "removeStacksInWindowingModes()");
2615
2616 synchronized (mGlobalLock) {
2617 final long ident = Binder.clearCallingIdentity();
2618 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002619 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002620 } finally {
2621 Binder.restoreCallingIdentity(ident);
2622 }
2623 }
2624 }
2625
2626 @Override
2627 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002628 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629 "removeStacksWithActivityTypes()");
2630
2631 synchronized (mGlobalLock) {
2632 final long ident = Binder.clearCallingIdentity();
2633 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002634 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002635 } finally {
2636 Binder.restoreCallingIdentity(ident);
2637 }
2638 }
2639 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002640
2641 @Override
2642 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2643 int userId) {
2644 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002645 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2646 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002647 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002648 final boolean detailed = checkGetTasksPermission(
2649 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2650 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002651 == PackageManager.PERMISSION_GRANTED;
2652
2653 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002654 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002655 callingUid);
2656 }
2657 }
2658
2659 @Override
2660 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002661 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662 long ident = Binder.clearCallingIdentity();
2663 try {
2664 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002665 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002666 }
2667 } finally {
2668 Binder.restoreCallingIdentity(ident);
2669 }
2670 }
2671
2672 @Override
2673 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002674 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002675 long ident = Binder.clearCallingIdentity();
2676 try {
2677 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002678 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002679 }
2680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
2684
2685 @Override
2686 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002687 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002688 final long callingUid = Binder.getCallingUid();
2689 final long origId = Binder.clearCallingIdentity();
2690 try {
2691 synchronized (mGlobalLock) {
2692 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002693 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002694 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2695 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2696 }
2697 } finally {
2698 Binder.restoreCallingIdentity(origId);
2699 }
2700 }
2701
2702 @Override
2703 public void startLockTaskModeByToken(IBinder token) {
2704 synchronized (mGlobalLock) {
2705 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2706 if (r == null) {
2707 return;
2708 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002709 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002710 }
2711 }
2712
2713 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002714 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002715 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002716 // This makes inner call to look as if it was initiated by system.
2717 long ident = Binder.clearCallingIdentity();
2718 try {
2719 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002720 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002721 MATCH_TASK_IN_STACKS_ONLY);
2722 if (task == null) {
2723 return;
2724 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002725
2726 // When starting lock task mode the stack must be in front and focused
2727 task.getStack().moveToFront("startSystemLockTaskMode");
2728 startLockTaskModeLocked(task, true /* isSystemCaller */);
2729 }
2730 } finally {
2731 Binder.restoreCallingIdentity(ident);
2732 }
2733 }
2734
2735 @Override
2736 public void stopLockTaskModeByToken(IBinder token) {
2737 synchronized (mGlobalLock) {
2738 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2739 if (r == null) {
2740 return;
2741 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002742 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 }
2744 }
2745
2746 /**
2747 * This API should be called by SystemUI only when user perform certain action to dismiss
2748 * lock task mode. We should only dismiss pinned lock task mode in this case.
2749 */
2750 @Override
2751 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002752 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002753 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2754 }
2755
2756 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2757 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2758 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2759 return;
2760 }
2761
Wale Ogunwaled32da472018-11-16 07:19:28 -08002762 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 if (stack == null || task != stack.topTask()) {
2764 throw new IllegalArgumentException("Invalid task, not in foreground");
2765 }
2766
2767 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2768 // system or a specific app.
2769 // * System-initiated requests will only start the pinned mode (screen pinning)
2770 // * App-initiated requests
2771 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2772 // - will start the pinned mode, otherwise
2773 final int callingUid = Binder.getCallingUid();
2774 long ident = Binder.clearCallingIdentity();
2775 try {
2776 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002777 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002779 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 } finally {
2781 Binder.restoreCallingIdentity(ident);
2782 }
2783 }
2784
2785 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2786 final int callingUid = Binder.getCallingUid();
2787 long ident = Binder.clearCallingIdentity();
2788 try {
2789 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002790 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 }
2792 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2793 // task and jumping straight into a call in the case of emergency call back.
2794 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2795 if (tm != null) {
2796 tm.showInCallScreen(false);
2797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(ident);
2800 }
2801 }
2802
2803 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002804 public void updateLockTaskPackages(int userId, String[] packages) {
2805 final int callingUid = Binder.getCallingUid();
2806 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2807 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2808 "updateLockTaskPackages()");
2809 }
2810 synchronized (this) {
2811 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2812 + Arrays.toString(packages));
2813 getLockTaskController().updateLockTaskPackages(userId, packages);
2814 }
2815 }
2816
2817 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 public boolean isInLockTaskMode() {
2819 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2820 }
2821
2822 @Override
2823 public int getLockTaskModeState() {
2824 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002825 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 }
2828
2829 @Override
2830 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2831 synchronized (mGlobalLock) {
2832 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2833 if (r != null) {
2834 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002835 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002837 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 }
2839 }
2840 }
2841
2842 @Override
2843 public Bundle getActivityOptions(IBinder token) {
2844 final long origId = Binder.clearCallingIdentity();
2845 try {
2846 synchronized (mGlobalLock) {
2847 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2848 if (r != null) {
2849 final ActivityOptions activityOptions = r.takeOptionsLocked();
2850 return activityOptions == null ? null : activityOptions.toBundle();
2851 }
2852 return null;
2853 }
2854 } finally {
2855 Binder.restoreCallingIdentity(origId);
2856 }
2857 }
2858
2859 @Override
2860 public List<IBinder> getAppTasks(String callingPackage) {
2861 int callingUid = Binder.getCallingUid();
2862 long ident = Binder.clearCallingIdentity();
2863 try {
2864 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002865 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 }
2867 } finally {
2868 Binder.restoreCallingIdentity(ident);
2869 }
2870 }
2871
2872 @Override
2873 public void finishVoiceTask(IVoiceInteractionSession session) {
2874 synchronized (mGlobalLock) {
2875 final long origId = Binder.clearCallingIdentity();
2876 try {
2877 // TODO: VI Consider treating local voice interactions and voice tasks
2878 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002879 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 } finally {
2881 Binder.restoreCallingIdentity(origId);
2882 }
2883 }
2884
2885 }
2886
2887 @Override
2888 public boolean isTopOfTask(IBinder token) {
2889 synchronized (mGlobalLock) {
2890 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002891 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 }
2893 }
2894
2895 @Override
2896 public void notifyLaunchTaskBehindComplete(IBinder token) {
2897 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2898 }
2899
2900 @Override
2901 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002902 mH.post(() -> {
2903 synchronized (mGlobalLock) {
2904 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002905 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002906 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002907 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002908 } catch (RemoteException e) {
2909 }
2910 }
2911 }
2912
2913 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 }
2915
2916 /** Called from an app when assist data is ready. */
2917 @Override
2918 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2919 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002920 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 synchronized (pae) {
2922 pae.result = extras;
2923 pae.structure = structure;
2924 pae.content = content;
2925 if (referrer != null) {
2926 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2927 }
2928 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002929 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002930 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2931 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002932 structure.setHomeActivity(pae.isHome);
2933 }
2934 pae.haveResult = true;
2935 pae.notifyAll();
2936 if (pae.intent == null && pae.receiver == null) {
2937 // Caller is just waiting for the result.
2938 return;
2939 }
2940 }
2941 // We are now ready to launch the assist activity.
2942 IAssistDataReceiver sendReceiver = null;
2943 Bundle sendBundle = null;
2944 synchronized (mGlobalLock) {
2945 buildAssistBundleLocked(pae, extras);
2946 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002947 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 if (!exists) {
2949 // Timed out.
2950 return;
2951 }
2952
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002953 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 // Caller wants result sent back to them.
2955 sendBundle = new Bundle();
2956 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2957 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2958 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2959 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2960 }
2961 }
2962 if (sendReceiver != null) {
2963 try {
2964 sendReceiver.onHandleAssistData(sendBundle);
2965 } catch (RemoteException e) {
2966 }
2967 return;
2968 }
2969
2970 final long ident = Binder.clearCallingIdentity();
2971 try {
2972 if (TextUtils.equals(pae.intent.getAction(),
2973 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2974 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01002975
2976 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 } else {
2978 pae.intent.replaceExtras(pae.extras);
2979 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2980 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2981 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002982 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983
2984 try {
2985 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2986 } catch (ActivityNotFoundException e) {
2987 Slog.w(TAG, "No activity to handle assist action.", e);
2988 }
2989 }
2990 } finally {
2991 Binder.restoreCallingIdentity(ident);
2992 }
2993 }
2994
Marvin Ramin830d4e32019-03-12 13:16:58 +01002995 /**
2996 * Workaround for historical API which starts the Assist service with a non-foreground
2997 * {@code startService()} call.
2998 */
2999 private void startVoiceInteractionServiceAsUser(
3000 Intent intent, int userHandle, String reason) {
3001 // Resolve the intent to find out which package we need to whitelist.
3002 ResolveInfo resolveInfo =
3003 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3004 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3005 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3006 return;
3007 }
3008 intent.setPackage(resolveInfo.serviceInfo.packageName);
3009
3010 // Whitelist background services temporarily.
3011 LocalServices.getService(DeviceIdleController.LocalService.class)
3012 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3013 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3014
3015 // Finally, try to start the service.
3016 try {
3017 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3018 } catch (RuntimeException e) {
3019 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3020 }
3021 }
3022
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 @Override
3024 public int addAppTask(IBinder activityToken, Intent intent,
3025 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3026 final int callingUid = Binder.getCallingUid();
3027 final long callingIdent = Binder.clearCallingIdentity();
3028
3029 try {
3030 synchronized (mGlobalLock) {
3031 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3032 if (r == null) {
3033 throw new IllegalArgumentException("Activity does not exist; token="
3034 + activityToken);
3035 }
3036 ComponentName comp = intent.getComponent();
3037 if (comp == null) {
3038 throw new IllegalArgumentException("Intent " + intent
3039 + " must specify explicit component");
3040 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003041 if (thumbnail.getWidth() != mThumbnailWidth
3042 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 throw new IllegalArgumentException("Bad thumbnail size: got "
3044 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003045 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 }
3047 if (intent.getSelector() != null) {
3048 intent.setSelector(null);
3049 }
3050 if (intent.getSourceBounds() != null) {
3051 intent.setSourceBounds(null);
3052 }
3053 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3054 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3055 // The caller has added this as an auto-remove task... that makes no
3056 // sense, so turn off auto-remove.
3057 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3058 }
3059 }
3060 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3061 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3062 if (ainfo.applicationInfo.uid != callingUid) {
3063 throw new SecurityException(
3064 "Can't add task for another application: target uid="
3065 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3066 }
3067
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003068 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003070 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003072 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 // The app has too many tasks already and we can't add any more
3074 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3075 return INVALID_TASK_ID;
3076 }
3077 task.lastTaskDescription.copyFrom(description);
3078
3079 // TODO: Send the thumbnail to WM to store it.
3080
3081 return task.taskId;
3082 }
3083 } finally {
3084 Binder.restoreCallingIdentity(callingIdent);
3085 }
3086 }
3087
3088 @Override
3089 public Point getAppTaskThumbnailSize() {
3090 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003091 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 }
3093 }
3094
3095 @Override
3096 public void setTaskResizeable(int taskId, int resizeableMode) {
3097 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003098 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3100 if (task == null) {
3101 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3102 return;
3103 }
3104 task.setResizeMode(resizeableMode);
3105 }
3106 }
3107
3108 @Override
3109 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 long ident = Binder.clearCallingIdentity();
3112 try {
3113 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003114 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003115 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 if (task == null) {
3117 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3118 return;
3119 }
3120 // Place the task in the right stack if it isn't there already based on
3121 // the requested bounds.
3122 // The stack transition logic is:
3123 // - a null bounds on a freeform task moves that task to fullscreen
3124 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3125 // that task to freeform
3126 // - otherwise the task is not moved
3127 ActivityStack stack = task.getStack();
3128 if (!task.getWindowConfiguration().canResizeTask()) {
3129 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3130 }
3131 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3132 stack = stack.getDisplay().getOrCreateStack(
3133 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3134 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3135 stack = stack.getDisplay().getOrCreateStack(
3136 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3137 }
3138
3139 // Reparent the task to the right stack if necessary
3140 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3141 if (stack != task.getStack()) {
3142 // Defer resume until the task is resized below
3143 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3144 DEFER_RESUME, "resizeTask");
3145 preserveWindow = false;
3146 }
3147
3148 // After reparenting (which only resizes the task to the stack bounds), resize the
3149 // task to the actual bounds provided
3150 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3151 }
3152 } finally {
3153 Binder.restoreCallingIdentity(ident);
3154 }
3155 }
3156
3157 @Override
3158 public boolean releaseActivityInstance(IBinder token) {
3159 synchronized (mGlobalLock) {
3160 final long origId = Binder.clearCallingIdentity();
3161 try {
3162 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3163 if (r == null) {
3164 return false;
3165 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003166 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003167 } finally {
3168 Binder.restoreCallingIdentity(origId);
3169 }
3170 }
3171 }
3172
3173 @Override
3174 public void releaseSomeActivities(IApplicationThread appInt) {
3175 synchronized (mGlobalLock) {
3176 final long origId = Binder.clearCallingIdentity();
3177 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003178 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003179 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 } finally {
3181 Binder.restoreCallingIdentity(origId);
3182 }
3183 }
3184 }
3185
3186 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003187 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 != PackageManager.PERMISSION_GRANTED) {
3190 throw new SecurityException("Requires permission "
3191 + android.Manifest.permission.DEVICE_POWER);
3192 }
3193
3194 synchronized (mGlobalLock) {
3195 long ident = Binder.clearCallingIdentity();
3196 if (mKeyguardShown != keyguardShowing) {
3197 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003198 final Message msg = PooledLambda.obtainMessage(
3199 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3200 keyguardShowing);
3201 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003202 }
3203 try {
wilsonshih177261f2019-02-22 12:02:18 +08003204 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 } finally {
3206 Binder.restoreCallingIdentity(ident);
3207 }
3208 }
3209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003210 mH.post(() -> {
3211 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3212 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3213 }
3214 });
3215 }
3216
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003217 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003218 mH.post(() -> {
3219 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3220 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3221 }
3222 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003223 }
3224
3225 @Override
3226 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003227 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3228 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003229
3230 final File passedIconFile = new File(filePath);
3231 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3232 passedIconFile.getName());
3233 if (!legitIconFile.getPath().equals(filePath)
3234 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3235 throw new IllegalArgumentException("Bad file path: " + filePath
3236 + " passed for userId " + userId);
3237 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003238 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003239 }
3240
3241 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003242 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3244 final ActivityOptions activityOptions = safeOptions != null
3245 ? safeOptions.getOptions(mStackSupervisor)
3246 : null;
3247 if (activityOptions == null
3248 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3249 || activityOptions.getCustomInPlaceResId() == 0) {
3250 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3251 "with valid animation");
3252 }
lumark588a3e82018-07-20 18:53:54 +08003253 // Get top display of front most application.
3254 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3255 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003256 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3257 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3258 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003259 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003260 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003261 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 }
3263
3264 @Override
3265 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003266 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 synchronized (mGlobalLock) {
3268 final long ident = Binder.clearCallingIdentity();
3269 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003270 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 if (stack == null) {
3272 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3273 return;
3274 }
3275 if (!stack.isActivityTypeStandardOrUndefined()) {
3276 throw new IllegalArgumentException(
3277 "Removing non-standard stack is not allowed.");
3278 }
3279 mStackSupervisor.removeStack(stack);
3280 } finally {
3281 Binder.restoreCallingIdentity(ident);
3282 }
3283 }
3284 }
3285
3286 @Override
3287 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003288 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289
3290 synchronized (mGlobalLock) {
3291 final long ident = Binder.clearCallingIdentity();
3292 try {
3293 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3294 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003295 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 } finally {
3297 Binder.restoreCallingIdentity(ident);
3298 }
3299 }
3300 }
3301
3302 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003303 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003304 synchronized (mGlobalLock) {
3305 long ident = Binder.clearCallingIdentity();
3306 try {
3307 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3308 if (r == null) {
3309 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003310 "toggleFreeformWindowingMode: No activity record matching token="
3311 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 }
3313
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003314 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003315 if (stack == null) {
3316 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3317 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 }
3319
Yunfan Chend967af82019-01-17 18:30:18 +09003320 if (!stack.inFreeformWindowingMode()
3321 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3322 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3323 + "toggle between fullscreen and freeform.");
3324 }
3325
3326 if (stack.inFreeformWindowingMode()) {
3327 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3328 } else {
3329 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3330 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 } finally {
3332 Binder.restoreCallingIdentity(ident);
3333 }
3334 }
3335 }
3336
3337 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3338 @Override
3339 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003340 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003342 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 }
3344
3345 /** Unregister a task stack listener so that it stops receiving callbacks. */
3346 @Override
3347 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003348 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003350 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 }
3352
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 @Override
3354 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3355 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3356 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3357 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3358 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3359 }
3360
3361 @Override
3362 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3363 IBinder activityToken, int flags) {
3364 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3365 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3366 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3367 }
3368
3369 @Override
3370 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3371 Bundle args) {
3372 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3373 true /* focused */, true /* newSessionId */, userHandle, args,
3374 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3375 }
3376
3377 @Override
3378 public Bundle getAssistContextExtras(int requestType) {
3379 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3380 null, null, true /* focused */, true /* newSessionId */,
3381 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3382 if (pae == null) {
3383 return null;
3384 }
3385 synchronized (pae) {
3386 while (!pae.haveResult) {
3387 try {
3388 pae.wait();
3389 } catch (InterruptedException e) {
3390 }
3391 }
3392 }
3393 synchronized (mGlobalLock) {
3394 buildAssistBundleLocked(pae, pae.result);
3395 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003396 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 }
3398 return pae.extras;
3399 }
3400
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003401 /**
3402 * Binder IPC calls go through the public entry point.
3403 * This can be called with or without the global lock held.
3404 */
3405 private static int checkCallingPermission(String permission) {
3406 return checkPermission(
3407 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3408 }
3409
3410 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003411 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3413 mAmInternal.enforceCallingPermission(permission, func);
3414 }
3415 }
3416
3417 @VisibleForTesting
3418 int checkGetTasksPermission(String permission, int pid, int uid) {
3419 return checkPermission(permission, pid, uid);
3420 }
3421
3422 static int checkPermission(String permission, int pid, int uid) {
3423 if (permission == null) {
3424 return PackageManager.PERMISSION_DENIED;
3425 }
3426 return checkComponentPermission(permission, pid, uid, -1, true);
3427 }
3428
Wale Ogunwale214f3482018-10-04 11:00:47 -07003429 public static int checkComponentPermission(String permission, int pid, int uid,
3430 int owningUid, boolean exported) {
3431 return ActivityManagerService.checkComponentPermission(
3432 permission, pid, uid, owningUid, exported);
3433 }
3434
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3436 if (getRecentTasks().isCallerRecents(callingUid)) {
3437 // Always allow the recents component to get tasks
3438 return true;
3439 }
3440
3441 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3442 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3443 if (!allowed) {
3444 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3445 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3446 // Temporary compatibility: some existing apps on the system image may
3447 // still be requesting the old permission and not switched to the new
3448 // one; if so, we'll still allow them full access. This means we need
3449 // to see if they are holding the old permission and are a system app.
3450 try {
3451 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3452 allowed = true;
3453 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3454 + " is using old GET_TASKS but privileged; allowing");
3455 }
3456 } catch (RemoteException e) {
3457 }
3458 }
3459 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3460 + " does not hold REAL_GET_TASKS; limiting output");
3461 }
3462 return allowed;
3463 }
3464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3466 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3467 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3468 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003469 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 "enqueueAssistContext()");
3471
3472 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003473 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474 if (activity == null) {
3475 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3476 return null;
3477 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003478 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3480 return null;
3481 }
3482 if (focused) {
3483 if (activityToken != null) {
3484 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3485 if (activity != caller) {
3486 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3487 + " is not current top " + activity);
3488 return null;
3489 }
3490 }
3491 } else {
3492 activity = ActivityRecord.forTokenLocked(activityToken);
3493 if (activity == null) {
3494 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3495 + " couldn't be found");
3496 return null;
3497 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003498 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003499 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3500 return null;
3501 }
3502 }
3503
3504 PendingAssistExtras pae;
3505 Bundle extras = new Bundle();
3506 if (args != null) {
3507 extras.putAll(args);
3508 }
3509 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003510 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511
3512 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3513 userHandle);
3514 pae.isHome = activity.isActivityTypeHome();
3515
3516 // Increment the sessionId if necessary
3517 if (newSessionId) {
3518 mViSessionId++;
3519 }
3520 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003521 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3522 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003523 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003524 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 } catch (RemoteException e) {
3526 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3527 return null;
3528 }
3529 return pae;
3530 }
3531 }
3532
3533 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3534 if (result != null) {
3535 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3536 }
3537 if (pae.hint != null) {
3538 pae.extras.putBoolean(pae.hint, true);
3539 }
3540 }
3541
3542 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3543 IAssistDataReceiver receiver;
3544 synchronized (mGlobalLock) {
3545 mPendingAssistExtras.remove(pae);
3546 receiver = pae.receiver;
3547 }
3548 if (receiver != null) {
3549 // Caller wants result sent back to them.
3550 Bundle sendBundle = new Bundle();
3551 // At least return the receiver extras
3552 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3553 try {
3554 pae.receiver.onHandleAssistData(sendBundle);
3555 } catch (RemoteException e) {
3556 }
3557 }
3558 }
3559
3560 public class PendingAssistExtras extends Binder implements Runnable {
3561 public final ActivityRecord activity;
3562 public boolean isHome;
3563 public final Bundle extras;
3564 public final Intent intent;
3565 public final String hint;
3566 public final IAssistDataReceiver receiver;
3567 public final int userHandle;
3568 public boolean haveResult = false;
3569 public Bundle result = null;
3570 public AssistStructure structure = null;
3571 public AssistContent content = null;
3572 public Bundle receiverExtras;
3573
3574 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3575 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3576 int _userHandle) {
3577 activity = _activity;
3578 extras = _extras;
3579 intent = _intent;
3580 hint = _hint;
3581 receiver = _receiver;
3582 receiverExtras = _receiverExtras;
3583 userHandle = _userHandle;
3584 }
3585
3586 @Override
3587 public void run() {
3588 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3589 synchronized (this) {
3590 haveResult = true;
3591 notifyAll();
3592 }
3593 pendingAssistExtrasTimedOut(this);
3594 }
3595 }
3596
3597 @Override
3598 public boolean isAssistDataAllowedOnCurrentActivity() {
3599 int userId;
3600 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003601 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003602 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3603 return false;
3604 }
3605
3606 final ActivityRecord activity = focusedStack.getTopActivity();
3607 if (activity == null) {
3608 return false;
3609 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003610 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 }
3612 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3613 }
3614
3615 @Override
3616 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3617 long ident = Binder.clearCallingIdentity();
3618 try {
3619 synchronized (mGlobalLock) {
3620 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003621 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 if (top != caller) {
3623 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3624 + " is not current top " + top);
3625 return false;
3626 }
3627 if (!top.nowVisible) {
3628 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3629 + " is not visible");
3630 return false;
3631 }
3632 }
3633 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3634 token);
3635 } finally {
3636 Binder.restoreCallingIdentity(ident);
3637 }
3638 }
3639
3640 @Override
3641 public boolean isRootVoiceInteraction(IBinder token) {
3642 synchronized (mGlobalLock) {
3643 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3644 if (r == null) {
3645 return false;
3646 }
3647 return r.rootVoiceInteraction;
3648 }
3649 }
3650
Wale Ogunwalef6733932018-06-27 05:14:34 -07003651 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3652 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3653 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3654 if (activityToCallback == null) return;
3655 activityToCallback.setVoiceSessionLocked(voiceSession);
3656
3657 // Inform the activity
3658 try {
3659 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3660 voiceInteractor);
3661 long token = Binder.clearCallingIdentity();
3662 try {
3663 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3664 } finally {
3665 Binder.restoreCallingIdentity(token);
3666 }
3667 // TODO: VI Should we cache the activity so that it's easier to find later
3668 // rather than scan through all the stacks and activities?
3669 } catch (RemoteException re) {
3670 activityToCallback.clearVoiceSessionLocked();
3671 // TODO: VI Should this terminate the voice session?
3672 }
3673 }
3674
3675 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3676 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3677 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3678 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3679 boolean wasRunningVoice = mRunningVoice != null;
3680 mRunningVoice = session;
3681 if (!wasRunningVoice) {
3682 mVoiceWakeLock.acquire();
3683 updateSleepIfNeededLocked();
3684 }
3685 }
3686 }
3687
3688 void finishRunningVoiceLocked() {
3689 if (mRunningVoice != null) {
3690 mRunningVoice = null;
3691 mVoiceWakeLock.release();
3692 updateSleepIfNeededLocked();
3693 }
3694 }
3695
3696 @Override
3697 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3698 synchronized (mGlobalLock) {
3699 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3700 if (keepAwake) {
3701 mVoiceWakeLock.acquire();
3702 } else {
3703 mVoiceWakeLock.release();
3704 }
3705 }
3706 }
3707 }
3708
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003709 @Override
3710 public ComponentName getActivityClassForToken(IBinder token) {
3711 synchronized (mGlobalLock) {
3712 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3713 if (r == null) {
3714 return null;
3715 }
3716 return r.intent.getComponent();
3717 }
3718 }
3719
3720 @Override
3721 public String getPackageForToken(IBinder token) {
3722 synchronized (mGlobalLock) {
3723 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3724 if (r == null) {
3725 return null;
3726 }
3727 return r.packageName;
3728 }
3729 }
3730
3731 @Override
3732 public void showLockTaskEscapeMessage(IBinder token) {
3733 synchronized (mGlobalLock) {
3734 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3735 if (r == null) {
3736 return;
3737 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003738 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 }
3740 }
3741
3742 @Override
3743 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003744 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003745 final long token = Binder.clearCallingIdentity();
3746 try {
3747 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003748 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 }
3750 } finally {
3751 Binder.restoreCallingIdentity(token);
3752 }
3753 }
3754
3755 /**
3756 * Try to place task to provided position. The final position might be different depending on
3757 * current user and stacks state. The task will be moved to target stack if it's currently in
3758 * different stack.
3759 */
3760 @Override
3761 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003762 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003763 synchronized (mGlobalLock) {
3764 long ident = Binder.clearCallingIdentity();
3765 try {
3766 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3767 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003768 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003769 if (task == null) {
3770 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3771 + taskId);
3772 }
3773
Wale Ogunwaled32da472018-11-16 07:19:28 -08003774 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775
3776 if (stack == null) {
3777 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3778 + stackId);
3779 }
3780 if (!stack.isActivityTypeStandardOrUndefined()) {
3781 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3782 + " the position of task " + taskId + " in/to non-standard stack");
3783 }
3784
3785 // TODO: Have the callers of this API call a separate reparent method if that is
3786 // what they intended to do vs. having this method also do reparenting.
3787 if (task.getStack() == stack) {
3788 // Change position in current stack.
3789 stack.positionChildAt(task, position);
3790 } else {
3791 // Reparent to new stack.
3792 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3793 !DEFER_RESUME, "positionTaskInStack");
3794 }
3795 } finally {
3796 Binder.restoreCallingIdentity(ident);
3797 }
3798 }
3799 }
3800
3801 @Override
3802 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3803 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3804 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3805 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3806 synchronized (mGlobalLock) {
3807 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3808 if (record == null) {
3809 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3810 + "found for: " + token);
3811 }
3812 record.setSizeConfigurations(horizontalSizeConfiguration,
3813 verticalSizeConfigurations, smallestSizeConfigurations);
3814 }
3815 }
3816
3817 /**
3818 * Dismisses split-screen multi-window mode.
3819 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3820 */
3821 @Override
3822 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003823 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003824 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3825 final long ident = Binder.clearCallingIdentity();
3826 try {
3827 synchronized (mGlobalLock) {
3828 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003829 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 if (stack == null) {
3831 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3832 return;
3833 }
3834
3835 if (toTop) {
3836 // Caller wants the current split-screen primary stack to be the top stack after
3837 // it goes fullscreen, so move it to the front.
3838 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003839 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 // In this case the current split-screen primary stack shouldn't be the top
3841 // stack after it goes fullscreen, but it current has focus, so we move the
3842 // focus to the top-most split-screen secondary stack next to it.
3843 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3844 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3845 if (otherStack != null) {
3846 otherStack.moveToFront("dismissSplitScreenMode_other");
3847 }
3848 }
3849
Evan Rosky10475742018-09-05 19:02:48 -07003850 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003851 }
3852 } finally {
3853 Binder.restoreCallingIdentity(ident);
3854 }
3855 }
3856
3857 /**
3858 * Dismisses Pip
3859 * @param animate True if the dismissal should be animated.
3860 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3861 * default animation duration should be used.
3862 */
3863 @Override
3864 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003865 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003866 final long ident = Binder.clearCallingIdentity();
3867 try {
3868 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003869 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003870 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 if (stack == null) {
3872 Slog.w(TAG, "dismissPip: pinned stack not found.");
3873 return;
3874 }
3875 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3876 throw new IllegalArgumentException("Stack: " + stack
3877 + " doesn't support animated resize.");
3878 }
3879 if (animate) {
3880 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3881 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3882 } else {
3883 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3884 }
3885 }
3886 } finally {
3887 Binder.restoreCallingIdentity(ident);
3888 }
3889 }
3890
3891 @Override
3892 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003893 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894 synchronized (mGlobalLock) {
3895 mSuppressResizeConfigChanges = suppress;
3896 }
3897 }
3898
3899 /**
3900 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3901 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3902 * activity and clearing the task at the same time.
3903 */
3904 @Override
3905 // TODO: API should just be about changing windowing modes...
3906 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003907 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908 "moveTasksToFullscreenStack()");
3909 synchronized (mGlobalLock) {
3910 final long origId = Binder.clearCallingIdentity();
3911 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003912 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 if (stack != null){
3914 if (!stack.isActivityTypeStandardOrUndefined()) {
3915 throw new IllegalArgumentException(
3916 "You can't move tasks from non-standard stacks.");
3917 }
3918 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3919 }
3920 } finally {
3921 Binder.restoreCallingIdentity(origId);
3922 }
3923 }
3924 }
3925
3926 /**
3927 * Moves the top activity in the input stackId to the pinned stack.
3928 *
3929 * @param stackId Id of stack to move the top activity to pinned stack.
3930 * @param bounds Bounds to use for pinned stack.
3931 *
3932 * @return True if the top activity of the input stack was successfully moved to the pinned
3933 * stack.
3934 */
3935 @Override
3936 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003937 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 "moveTopActivityToPinnedStack()");
3939 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003940 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3942 + "Device doesn't support picture-in-picture mode");
3943 }
3944
3945 long ident = Binder.clearCallingIdentity();
3946 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003947 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 } finally {
3949 Binder.restoreCallingIdentity(ident);
3950 }
3951 }
3952 }
3953
3954 @Override
3955 public boolean isInMultiWindowMode(IBinder token) {
3956 final long origId = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
3959 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3960 if (r == null) {
3961 return false;
3962 }
3963 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3964 return r.inMultiWindowMode();
3965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(origId);
3968 }
3969 }
3970
3971 @Override
3972 public boolean isInPictureInPictureMode(IBinder token) {
3973 final long origId = Binder.clearCallingIdentity();
3974 try {
3975 synchronized (mGlobalLock) {
3976 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3977 }
3978 } finally {
3979 Binder.restoreCallingIdentity(origId);
3980 }
3981 }
3982
3983 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003984 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3985 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003986 return false;
3987 }
3988
3989 // If we are animating to fullscreen then we have already dispatched the PIP mode
3990 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003991 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3992 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 }
3994
3995 @Override
3996 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3997 final long origId = Binder.clearCallingIdentity();
3998 try {
3999 synchronized (mGlobalLock) {
4000 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4001 "enterPictureInPictureMode", token, params);
4002
4003 // If the activity is already in picture in picture mode, then just return early
4004 if (isInPictureInPictureMode(r)) {
4005 return true;
4006 }
4007
4008 // Activity supports picture-in-picture, now check that we can enter PiP at this
4009 // point, if it is
4010 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4011 false /* beforeStopping */)) {
4012 return false;
4013 }
4014
4015 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004016 synchronized (mGlobalLock) {
4017 // Only update the saved args from the args that are set
4018 r.pictureInPictureArgs.copyOnlySet(params);
4019 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4020 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4021 // Adjust the source bounds by the insets for the transition down
4022 final Rect sourceBounds = new Rect(
4023 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004024 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004025 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004026 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004027 stack.setPictureInPictureAspectRatio(aspectRatio);
4028 stack.setPictureInPictureActions(actions);
4029 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4030 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4031 logPictureInPictureArgs(params);
4032 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 };
4034
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004035 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 // If the keyguard is showing or occluded, then try and dismiss it before
4037 // entering picture-in-picture (this will prompt the user to authenticate if the
4038 // device is currently locked).
4039 dismissKeyguard(token, new KeyguardDismissCallback() {
4040 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 public void onDismissSucceeded() {
4042 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 }
4044 }, null /* message */);
4045 } else {
4046 // Enter picture in picture immediately otherwise
4047 enterPipRunnable.run();
4048 }
4049 return true;
4050 }
4051 } finally {
4052 Binder.restoreCallingIdentity(origId);
4053 }
4054 }
4055
4056 @Override
4057 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4058 final long origId = Binder.clearCallingIdentity();
4059 try {
4060 synchronized (mGlobalLock) {
4061 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4062 "setPictureInPictureParams", token, params);
4063
4064 // Only update the saved args from the args that are set
4065 r.pictureInPictureArgs.copyOnlySet(params);
4066 if (r.inPinnedWindowingMode()) {
4067 // If the activity is already in picture-in-picture, update the pinned stack now
4068 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4069 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004070 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 if (!stack.isAnimatingBoundsToFullscreen()) {
4072 stack.setPictureInPictureAspectRatio(
4073 r.pictureInPictureArgs.getAspectRatio());
4074 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4075 }
4076 }
4077 logPictureInPictureArgs(params);
4078 }
4079 } finally {
4080 Binder.restoreCallingIdentity(origId);
4081 }
4082 }
4083
4084 @Override
4085 public int getMaxNumPictureInPictureActions(IBinder token) {
4086 // Currently, this is a static constant, but later, we may change this to be dependent on
4087 // the context of the activity
4088 return 3;
4089 }
4090
4091 private void logPictureInPictureArgs(PictureInPictureParams params) {
4092 if (params.hasSetActions()) {
4093 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4094 params.getActions().size());
4095 }
4096 if (params.hasSetAspectRatio()) {
4097 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4098 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4099 MetricsLogger.action(lm);
4100 }
4101 }
4102
4103 /**
4104 * Checks the state of the system and the activity associated with the given {@param token} to
4105 * verify that picture-in-picture is supported for that activity.
4106 *
4107 * @return the activity record for the given {@param token} if all the checks pass.
4108 */
4109 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4110 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004111 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004112 throw new IllegalStateException(caller
4113 + ": Device doesn't support picture-in-picture mode.");
4114 }
4115
4116 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4117 if (r == null) {
4118 throw new IllegalStateException(caller
4119 + ": Can't find activity for token=" + token);
4120 }
4121
4122 if (!r.supportsPictureInPicture()) {
4123 throw new IllegalStateException(caller
4124 + ": Current activity does not support picture-in-picture.");
4125 }
4126
4127 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004128 && !mWindowManager.isValidPictureInPictureAspectRatio(
4129 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 final float minAspectRatio = mContext.getResources().getFloat(
4131 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4132 final float maxAspectRatio = mContext.getResources().getFloat(
4133 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4134 throw new IllegalArgumentException(String.format(caller
4135 + ": Aspect ratio is too extreme (must be between %f and %f).",
4136 minAspectRatio, maxAspectRatio));
4137 }
4138
4139 // Truncate the number of actions if necessary
4140 params.truncateActions(getMaxNumPictureInPictureActions(token));
4141
4142 return r;
4143 }
4144
4145 @Override
4146 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 synchronized (mGlobalLock) {
4149 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4150 if (r == null) {
4151 throw new IllegalArgumentException("Activity does not exist; token="
4152 + activityToken);
4153 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004154 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 }
4156 }
4157
4158 @Override
4159 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4160 Rect tempDockedTaskInsetBounds,
4161 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004162 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 long ident = Binder.clearCallingIdentity();
4164 try {
4165 synchronized (mGlobalLock) {
4166 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4167 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4168 PRESERVE_WINDOWS);
4169 }
4170 } finally {
4171 Binder.restoreCallingIdentity(ident);
4172 }
4173 }
4174
4175 @Override
4176 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004177 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 final long ident = Binder.clearCallingIdentity();
4179 try {
4180 synchronized (mGlobalLock) {
4181 mStackSupervisor.setSplitScreenResizing(resizing);
4182 }
4183 } finally {
4184 Binder.restoreCallingIdentity(ident);
4185 }
4186 }
4187
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 /**
4189 * Check that we have the features required for VR-related API calls, and throw an exception if
4190 * not.
4191 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004192 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004193 if (!mContext.getPackageManager().hasSystemFeature(
4194 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4195 throw new UnsupportedOperationException("VR mode not supported on this device!");
4196 }
4197 }
4198
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004199 @Override
4200 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004201 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202
4203 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4204
4205 ActivityRecord r;
4206 synchronized (mGlobalLock) {
4207 r = ActivityRecord.isInStackLocked(token);
4208 }
4209
4210 if (r == null) {
4211 throw new IllegalArgumentException();
4212 }
4213
4214 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004215 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004216 VrManagerInternal.NO_ERROR) {
4217 return err;
4218 }
4219
4220 // Clear the binder calling uid since this path may call moveToTask().
4221 final long callingId = Binder.clearCallingIdentity();
4222 try {
4223 synchronized (mGlobalLock) {
4224 r.requestedVrComponent = (enabled) ? packageName : null;
4225
4226 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004227 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004228 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 }
4230 return 0;
4231 }
4232 } finally {
4233 Binder.restoreCallingIdentity(callingId);
4234 }
4235 }
4236
4237 @Override
4238 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4239 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4240 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004241 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4243 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4244 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004245 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 || activity.voiceSession != null) {
4247 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4248 return;
4249 }
4250 if (activity.pendingVoiceInteractionStart) {
4251 Slog.w(TAG, "Pending start of voice interaction already.");
4252 return;
4253 }
4254 activity.pendingVoiceInteractionStart = true;
4255 }
4256 LocalServices.getService(VoiceInteractionManagerInternal.class)
4257 .startLocalVoiceInteraction(callingActivity, options);
4258 }
4259
4260 @Override
4261 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4262 LocalServices.getService(VoiceInteractionManagerInternal.class)
4263 .stopLocalVoiceInteraction(callingActivity);
4264 }
4265
4266 @Override
4267 public boolean supportsLocalVoiceInteraction() {
4268 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4269 .supportsLocalVoiceInteraction();
4270 }
4271
4272 /** Notifies all listeners when the pinned stack animation starts. */
4273 @Override
4274 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004275 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 }
4277
4278 /** Notifies all listeners when the pinned stack animation ends. */
4279 @Override
4280 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004281 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282 }
4283
4284 @Override
4285 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004286 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 final long ident = Binder.clearCallingIdentity();
4288 try {
4289 synchronized (mGlobalLock) {
4290 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4291 }
4292 } finally {
4293 Binder.restoreCallingIdentity(ident);
4294 }
4295 }
4296
4297 @Override
4298 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300
4301 synchronized (mGlobalLock) {
4302 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004303 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 // Call might come when display is not yet added or has already been removed.
4305 if (DEBUG_CONFIGURATION) {
4306 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4307 + displayId);
4308 }
4309 return false;
4310 }
4311
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004312 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004314 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 }
4316
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004317 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004318 final Message msg = PooledLambda.obtainMessage(
4319 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4320 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004321 }
4322
4323 final long origId = Binder.clearCallingIdentity();
4324 try {
4325 if (values != null) {
4326 Settings.System.clearConfiguration(values);
4327 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004328 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4330 return mTmpUpdateConfigurationResult.changes != 0;
4331 } finally {
4332 Binder.restoreCallingIdentity(origId);
4333 }
4334 }
4335 }
4336
4337 @Override
4338 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004339 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340
4341 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004342 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004344 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 }
4346
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004348 final Message msg = PooledLambda.obtainMessage(
4349 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4350 DEFAULT_DISPLAY);
4351 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 }
4353
4354 final long origId = Binder.clearCallingIdentity();
4355 try {
4356 if (values != null) {
4357 Settings.System.clearConfiguration(values);
4358 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 UserHandle.USER_NULL, false /* deferResume */,
4361 mTmpUpdateConfigurationResult);
4362 return mTmpUpdateConfigurationResult.changes != 0;
4363 } finally {
4364 Binder.restoreCallingIdentity(origId);
4365 }
4366 }
4367 }
4368
4369 @Override
4370 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4371 CharSequence message) {
4372 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004373 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004374 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4375 }
4376 final long callingId = Binder.clearCallingIdentity();
4377 try {
4378 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004379 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 }
4381 } finally {
4382 Binder.restoreCallingIdentity(callingId);
4383 }
4384 }
4385
4386 @Override
4387 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 "cancelTaskWindowTransition()");
4390 final long ident = Binder.clearCallingIdentity();
4391 try {
4392 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004393 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 MATCH_TASK_IN_STACKS_ONLY);
4395 if (task == null) {
4396 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4397 return;
4398 }
4399 task.cancelWindowTransition();
4400 }
4401 } finally {
4402 Binder.restoreCallingIdentity(ident);
4403 }
4404 }
4405
4406 @Override
4407 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004408 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 final long ident = Binder.clearCallingIdentity();
4410 try {
4411 final TaskRecord task;
4412 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004413 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4415 if (task == null) {
4416 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4417 return null;
4418 }
4419 }
4420 // Don't call this while holding the lock as this operation might hit the disk.
4421 return task.getSnapshot(reducedResolution);
4422 } finally {
4423 Binder.restoreCallingIdentity(ident);
4424 }
4425 }
4426
4427 @Override
4428 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4429 synchronized (mGlobalLock) {
4430 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4431 if (r == null) {
4432 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4433 + token);
4434 return;
4435 }
4436 final long origId = Binder.clearCallingIdentity();
4437 try {
4438 r.setDisablePreviewScreenshots(disable);
4439 } finally {
4440 Binder.restoreCallingIdentity(origId);
4441 }
4442 }
4443 }
4444
4445 /** Return the user id of the last resumed activity. */
4446 @Override
4447 public @UserIdInt
4448 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004449 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004450 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4451 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004452 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004455 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 }
4457 }
4458
4459 @Override
4460 public void updateLockTaskFeatures(int userId, int flags) {
4461 final int callingUid = Binder.getCallingUid();
4462 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004463 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464 "updateLockTaskFeatures()");
4465 }
4466 synchronized (mGlobalLock) {
4467 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4468 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004469 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004470 }
4471 }
4472
4473 @Override
4474 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4475 synchronized (mGlobalLock) {
4476 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4477 if (r == null) {
4478 return;
4479 }
4480 final long origId = Binder.clearCallingIdentity();
4481 try {
4482 r.setShowWhenLocked(showWhenLocked);
4483 } finally {
4484 Binder.restoreCallingIdentity(origId);
4485 }
4486 }
4487 }
4488
4489 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004490 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4491 synchronized (mGlobalLock) {
4492 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4493 if (r == null) {
4494 return;
4495 }
4496 final long origId = Binder.clearCallingIdentity();
4497 try {
4498 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4499 } finally {
4500 Binder.restoreCallingIdentity(origId);
4501 }
4502 }
4503 }
4504
4505 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4507 synchronized (mGlobalLock) {
4508 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4509 if (r == null) {
4510 return;
4511 }
4512 final long origId = Binder.clearCallingIdentity();
4513 try {
4514 r.setTurnScreenOn(turnScreenOn);
4515 } finally {
4516 Binder.restoreCallingIdentity(origId);
4517 }
4518 }
4519 }
4520
4521 @Override
4522 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004523 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004524 "registerRemoteAnimations");
4525 definition.setCallingPid(Binder.getCallingPid());
4526 synchronized (mGlobalLock) {
4527 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4528 if (r == null) {
4529 return;
4530 }
4531 final long origId = Binder.clearCallingIdentity();
4532 try {
4533 r.registerRemoteAnimations(definition);
4534 } finally {
4535 Binder.restoreCallingIdentity(origId);
4536 }
4537 }
4538 }
4539
4540 @Override
4541 public void registerRemoteAnimationForNextActivityStart(String packageName,
4542 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004543 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 "registerRemoteAnimationForNextActivityStart");
4545 adapter.setCallingPid(Binder.getCallingPid());
4546 synchronized (mGlobalLock) {
4547 final long origId = Binder.clearCallingIdentity();
4548 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004549 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004550 packageName, adapter);
4551 } finally {
4552 Binder.restoreCallingIdentity(origId);
4553 }
4554 }
4555 }
4556
Evan Rosky966759f2019-01-15 10:33:58 -08004557 @Override
4558 public void registerRemoteAnimationsForDisplay(int displayId,
4559 RemoteAnimationDefinition definition) {
4560 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4561 "registerRemoteAnimations");
4562 definition.setCallingPid(Binder.getCallingPid());
4563 synchronized (mGlobalLock) {
4564 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4565 if (display == null) {
4566 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4567 return;
4568 }
4569 final long origId = Binder.clearCallingIdentity();
4570 try {
4571 display.mDisplayContent.registerRemoteAnimations(definition);
4572 } finally {
4573 Binder.restoreCallingIdentity(origId);
4574 }
4575 }
4576 }
4577
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4579 @Override
4580 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4581 synchronized (mGlobalLock) {
4582 final long origId = Binder.clearCallingIdentity();
4583 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004584 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 } finally {
4586 Binder.restoreCallingIdentity(origId);
4587 }
4588 }
4589 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004590
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004591 @Override
4592 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004593 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004594 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004595 final int pid = Binder.getCallingPid();
4596 final WindowProcessController wpc = mPidMap.get(pid);
4597 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004598 }
4599 }
4600
4601 @Override
4602 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004603 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004604 != PERMISSION_GRANTED) {
4605 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4606 + Binder.getCallingPid()
4607 + ", uid=" + Binder.getCallingUid()
4608 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4609 Slog.w(TAG, msg);
4610 throw new SecurityException(msg);
4611 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004612 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004613 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004614 final int pid = Binder.getCallingPid();
4615 final WindowProcessController proc = mPidMap.get(pid);
4616 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004617 }
4618 }
4619
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004620 @Override
4621 public void stopAppSwitches() {
4622 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4623 synchronized (mGlobalLock) {
4624 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4625 mDidAppSwitch = false;
4626 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4627 }
4628 }
4629
4630 @Override
4631 public void resumeAppSwitches() {
4632 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4633 synchronized (mGlobalLock) {
4634 // Note that we don't execute any pending app switches... we will
4635 // let those wait until either the timeout, or the next start
4636 // activity request.
4637 mAppSwitchesAllowedTime = 0;
4638 }
4639 }
4640
4641 void onStartActivitySetDidAppSwitch() {
4642 if (mDidAppSwitch) {
4643 // This is the second allowed switch since we stopped switches, so now just generally
4644 // allow switches. Use case:
4645 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4646 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4647 // anyone to switch again).
4648 mAppSwitchesAllowedTime = 0;
4649 } else {
4650 mDidAppSwitch = true;
4651 }
4652 }
4653
4654 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004655 boolean shouldDisableNonVrUiLocked() {
4656 return mVrController.shouldDisableNonVrUiLocked();
4657 }
4658
Wale Ogunwale53783742018-09-16 10:21:51 -07004659 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004660 // VR apps are expected to run in a main display. If an app is turning on VR for
4661 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4662 // fullscreen stack before enabling VR Mode.
4663 // TODO: The goal of this code is to keep the VR app on the main display. When the
4664 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4665 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4666 // option would be a better choice here.
4667 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4668 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4669 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004670 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004671 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004672 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004673 }
4674 mH.post(() -> {
4675 if (!mVrController.onVrModeChanged(r)) {
4676 return;
4677 }
4678 synchronized (mGlobalLock) {
4679 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4680 mWindowManager.disableNonVrUi(disableNonVrUi);
4681 if (disableNonVrUi) {
4682 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4683 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004684 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004685 }
4686 }
4687 });
4688 }
4689
Wale Ogunwale53783742018-09-16 10:21:51 -07004690 @Override
4691 public int getPackageScreenCompatMode(String packageName) {
4692 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4693 synchronized (mGlobalLock) {
4694 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4695 }
4696 }
4697
4698 @Override
4699 public void setPackageScreenCompatMode(String packageName, int mode) {
4700 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4701 "setPackageScreenCompatMode");
4702 synchronized (mGlobalLock) {
4703 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4704 }
4705 }
4706
4707 @Override
4708 public boolean getPackageAskScreenCompat(String packageName) {
4709 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4710 synchronized (mGlobalLock) {
4711 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4712 }
4713 }
4714
4715 @Override
4716 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4717 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4718 "setPackageAskScreenCompat");
4719 synchronized (mGlobalLock) {
4720 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4721 }
4722 }
4723
Wale Ogunwale64258362018-10-16 15:13:37 -07004724 public static String relaunchReasonToString(int relaunchReason) {
4725 switch (relaunchReason) {
4726 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4727 return "window_resize";
4728 case RELAUNCH_REASON_FREE_RESIZE:
4729 return "free_resize";
4730 default:
4731 return null;
4732 }
4733 }
4734
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004735 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004736 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004737 }
4738
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004739 /** Pokes the task persister. */
4740 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4741 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4742 }
4743
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 boolean isKeyguardLocked() {
4745 return mKeyguardController.isKeyguardLocked();
4746 }
4747
Garfield Tan01548632018-11-27 10:15:48 -08004748 /**
4749 * Clears launch params for the given package.
4750 * @param packageNames the names of the packages of which the launch params are to be cleared
4751 */
4752 @Override
4753 public void clearLaunchParamsForPackages(List<String> packageNames) {
4754 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4755 "clearLaunchParamsForPackages");
4756 synchronized (mGlobalLock) {
4757 for (int i = 0; i < packageNames.size(); ++i) {
4758 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4759 }
4760 }
4761 }
4762
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004763 /**
4764 * Makes the display with the given id a single task instance display. I.e the display can only
4765 * contain one task.
4766 */
4767 @Override
4768 public void setDisplayToSingleTaskInstance(int displayId) {
4769 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4770 "setDisplayToSingleTaskInstance");
4771 final long origId = Binder.clearCallingIdentity();
4772 try {
4773 final ActivityDisplay display =
4774 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4775 if (display != null) {
4776 display.setDisplayToSingleTaskInstance();
4777 }
4778 } finally {
4779 Binder.restoreCallingIdentity(origId);
4780 }
4781 }
4782
Wale Ogunwale31913b52018-10-13 08:29:31 -07004783 void dumpLastANRLocked(PrintWriter pw) {
4784 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4785 if (mLastANRState == null) {
4786 pw.println(" <no ANR has occurred since boot>");
4787 } else {
4788 pw.println(mLastANRState);
4789 }
4790 }
4791
4792 void dumpLastANRTracesLocked(PrintWriter pw) {
4793 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4794
4795 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4796 if (ArrayUtils.isEmpty(files)) {
4797 pw.println(" <no ANR has occurred since boot>");
4798 return;
4799 }
4800 // Find the latest file.
4801 File latest = null;
4802 for (File f : files) {
4803 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4804 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004805 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004806 }
4807 pw.print("File: ");
4808 pw.print(latest.getName());
4809 pw.println();
4810 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4811 String line;
4812 while ((line = in.readLine()) != null) {
4813 pw.println(line);
4814 }
4815 } catch (IOException e) {
4816 pw.print("Unable to read: ");
4817 pw.print(e);
4818 pw.println();
4819 }
4820 }
4821
4822 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4823 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4824 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4825 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4826 }
4827
4828 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4829 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4830 pw.println(header);
4831
Wale Ogunwaled32da472018-11-16 07:19:28 -08004832 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004833 dumpPackage);
4834 boolean needSep = printedAnything;
4835
4836 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004837 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004838 " ResumedActivity: ");
4839 if (printed) {
4840 printedAnything = true;
4841 needSep = false;
4842 }
4843
4844 if (dumpPackage == null) {
4845 if (needSep) {
4846 pw.println();
4847 }
4848 printedAnything = true;
4849 mStackSupervisor.dump(pw, " ");
4850 }
4851
4852 if (!printedAnything) {
4853 pw.println(" (nothing)");
4854 }
4855 }
4856
4857 void dumpActivityContainersLocked(PrintWriter pw) {
4858 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004859 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004860 pw.println(" ");
4861 }
4862
4863 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4864 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4865 getActivityStartController().dump(pw, "", dumpPackage);
4866 }
4867
4868 /**
4869 * There are three things that cmd can be:
4870 * - a flattened component name that matches an existing activity
4871 * - the cmd arg isn't the flattened component name of an existing activity:
4872 * dump all activity whose component contains the cmd as a substring
4873 * - A hex number of the ActivityRecord object instance.
4874 *
4875 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4876 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4877 */
4878 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4879 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4880 ArrayList<ActivityRecord> activities;
4881
4882 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004883 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004884 dumpFocusedStackOnly);
4885 }
4886
4887 if (activities.size() <= 0) {
4888 return false;
4889 }
4890
4891 String[] newArgs = new String[args.length - opti];
4892 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4893
4894 TaskRecord lastTask = null;
4895 boolean needSep = false;
4896 for (int i = activities.size() - 1; i >= 0; i--) {
4897 ActivityRecord r = activities.get(i);
4898 if (needSep) {
4899 pw.println();
4900 }
4901 needSep = true;
4902 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004903 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004904 if (lastTask != task) {
4905 lastTask = task;
4906 pw.print("TASK "); pw.print(lastTask.affinity);
4907 pw.print(" id="); pw.print(lastTask.taskId);
4908 pw.print(" userId="); pw.println(lastTask.userId);
4909 if (dumpAll) {
4910 lastTask.dump(pw, " ");
4911 }
4912 }
4913 }
4914 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4915 }
4916 return true;
4917 }
4918
4919 /**
4920 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4921 * there is a thread associated with the activity.
4922 */
4923 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4924 final ActivityRecord r, String[] args, boolean dumpAll) {
4925 String innerPrefix = prefix + " ";
4926 synchronized (mGlobalLock) {
4927 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4928 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4929 pw.print(" pid=");
4930 if (r.hasProcess()) pw.println(r.app.getPid());
4931 else pw.println("(not running)");
4932 if (dumpAll) {
4933 r.dump(pw, innerPrefix);
4934 }
4935 }
4936 if (r.attachedToProcess()) {
4937 // flush anything that is already in the PrintWriter since the thread is going
4938 // to write to the file descriptor directly
4939 pw.flush();
4940 try {
4941 TransferPipe tp = new TransferPipe();
4942 try {
4943 r.app.getThread().dumpActivity(tp.getWriteFd(),
4944 r.appToken, innerPrefix, args);
4945 tp.go(fd);
4946 } finally {
4947 tp.kill();
4948 }
4949 } catch (IOException e) {
4950 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4951 } catch (RemoteException e) {
4952 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4953 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004954 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004955 }
4956
sanryhuang498e77e2018-12-06 14:57:01 +08004957 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4958 boolean testPssMode) {
4959 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4960 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4961 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004962 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004963 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4964 st.toString());
4965 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004966 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4967 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4968 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004969 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4970 testPssMode);
4971 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004972 }
4973
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004974 int getCurrentUserId() {
4975 return mAmInternal.getCurrentUserId();
4976 }
4977
4978 private void enforceNotIsolatedCaller(String caller) {
4979 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4980 throw new SecurityException("Isolated process not allowed to call " + caller);
4981 }
4982 }
4983
Wale Ogunwalef6733932018-06-27 05:14:34 -07004984 public Configuration getConfiguration() {
4985 Configuration ci;
4986 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004987 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004988 ci.userSetLocale = false;
4989 }
4990 return ci;
4991 }
4992
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004993 /**
4994 * Current global configuration information. Contains general settings for the entire system,
4995 * also corresponds to the merged configuration of the default display.
4996 */
4997 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004998 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004999 }
5000
5001 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5002 boolean initLocale) {
5003 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5004 }
5005
5006 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5007 boolean initLocale, boolean deferResume) {
5008 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5009 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5010 UserHandle.USER_NULL, deferResume);
5011 }
5012
Wale Ogunwale59507092018-10-29 09:00:30 -07005013 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005014 final long origId = Binder.clearCallingIdentity();
5015 try {
5016 synchronized (mGlobalLock) {
5017 updateConfigurationLocked(values, null, false, true, userId,
5018 false /* deferResume */);
5019 }
5020 } finally {
5021 Binder.restoreCallingIdentity(origId);
5022 }
5023 }
5024
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005025 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5026 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5027 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5028 deferResume, null /* result */);
5029 }
5030
5031 /**
5032 * Do either or both things: (1) change the current configuration, and (2)
5033 * make sure the given activity is running with the (now) current
5034 * configuration. Returns true if the activity has been left running, or
5035 * false if <var>starting</var> is being destroyed to match the new
5036 * configuration.
5037 *
5038 * @param userId is only used when persistent parameter is set to true to persist configuration
5039 * for that particular user
5040 */
5041 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5042 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5043 ActivityTaskManagerService.UpdateConfigurationResult result) {
5044 int changes = 0;
5045 boolean kept = true;
5046
5047 if (mWindowManager != null) {
5048 mWindowManager.deferSurfaceLayout();
5049 }
5050 try {
5051 if (values != null) {
5052 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5053 deferResume);
5054 }
5055
5056 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5057 } finally {
5058 if (mWindowManager != null) {
5059 mWindowManager.continueSurfaceLayout();
5060 }
5061 }
5062
5063 if (result != null) {
5064 result.changes = changes;
5065 result.activityRelaunched = !kept;
5066 }
5067 return kept;
5068 }
5069
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005070 /** Update default (global) configuration and notify listeners about changes. */
5071 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5072 boolean persistent, int userId, boolean deferResume) {
5073 mTempConfig.setTo(getGlobalConfiguration());
5074 final int changes = mTempConfig.updateFrom(values);
5075 if (changes == 0) {
5076 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5077 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5078 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5079 // (even if there are no actual changes) to unfreeze the window.
5080 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5081 return 0;
5082 }
5083
5084 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5085 "Updating global configuration to: " + values);
5086
5087 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5088 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5089 values.colorMode,
5090 values.densityDpi,
5091 values.fontScale,
5092 values.hardKeyboardHidden,
5093 values.keyboard,
5094 values.keyboardHidden,
5095 values.mcc,
5096 values.mnc,
5097 values.navigation,
5098 values.navigationHidden,
5099 values.orientation,
5100 values.screenHeightDp,
5101 values.screenLayout,
5102 values.screenWidthDp,
5103 values.smallestScreenWidthDp,
5104 values.touchscreen,
5105 values.uiMode);
5106
5107
5108 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5109 final LocaleList locales = values.getLocales();
5110 int bestLocaleIndex = 0;
5111 if (locales.size() > 1) {
5112 if (mSupportedSystemLocales == null) {
5113 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5114 }
5115 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5116 }
5117 SystemProperties.set("persist.sys.locale",
5118 locales.get(bestLocaleIndex).toLanguageTag());
5119 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005120
5121 final Message m = PooledLambda.obtainMessage(
5122 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5123 locales.get(bestLocaleIndex));
5124 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005125 }
5126
Yunfan Chen75157d72018-07-27 14:47:21 +09005127 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128
5129 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005130 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131
5132 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5133 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005134 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135
5136 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005137 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005138
5139 AttributeCache ac = AttributeCache.instance();
5140 if (ac != null) {
5141 ac.updateConfiguration(mTempConfig);
5142 }
5143
5144 // Make sure all resources in our process are updated right now, so that anyone who is going
5145 // to retrieve resource values after we return will be sure to get the new ones. This is
5146 // especially important during boot, where the first config change needs to guarantee all
5147 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005148 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005149
5150 // We need another copy of global config because we're scheduling some calls instead of
5151 // running them in place. We need to be sure that object we send will be handled unchanged.
5152 final Configuration configCopy = new Configuration(mTempConfig);
5153 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005154 final Message msg = PooledLambda.obtainMessage(
5155 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5156 this, userId, configCopy);
5157 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005158 }
5159
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005160 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005161 final int pid = mPidMap.keyAt(i);
5162 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005163 if (DEBUG_CONFIGURATION) {
5164 Slog.v(TAG_CONFIGURATION, "Update process config of "
5165 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005166 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005167 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005168 }
5169
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005170 final Message msg = PooledLambda.obtainMessage(
5171 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5172 mAmInternal, changes, initLocale);
5173 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005174
5175 // Override configuration of the default display duplicates global config, so we need to
5176 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005177 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178 DEFAULT_DISPLAY);
5179
5180 return changes;
5181 }
5182
5183 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5184 boolean deferResume, int displayId) {
5185 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5186 displayId, null /* result */);
5187 }
5188
5189 /**
5190 * Updates override configuration specific for the selected display. If no config is provided,
5191 * new one will be computed in WM based on current display info.
5192 */
5193 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5194 ActivityRecord starting, boolean deferResume, int displayId,
5195 ActivityTaskManagerService.UpdateConfigurationResult result) {
5196 int changes = 0;
5197 boolean kept = true;
5198
5199 if (mWindowManager != null) {
5200 mWindowManager.deferSurfaceLayout();
5201 }
5202 try {
5203 if (values != null) {
5204 if (displayId == DEFAULT_DISPLAY) {
5205 // Override configuration of the default display duplicates global config, so
5206 // we're calling global config update instead for default display. It will also
5207 // apply the correct override config.
5208 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5209 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5210 } else {
5211 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5212 }
5213 }
5214
5215 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5216 } finally {
5217 if (mWindowManager != null) {
5218 mWindowManager.continueSurfaceLayout();
5219 }
5220 }
5221
5222 if (result != null) {
5223 result.changes = changes;
5224 result.activityRelaunched = !kept;
5225 }
5226 return kept;
5227 }
5228
5229 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5230 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005231 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232 final int changes = mTempConfig.updateFrom(values);
5233 if (changes != 0) {
5234 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5235 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005236 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237
5238 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5239 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005240 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241
Wale Ogunwale5c918702018-10-18 11:06:33 -07005242 // Post message to start process to avoid possible deadlock of calling into AMS with
5243 // the ATMS lock held.
5244 final Message msg = PooledLambda.obtainMessage(
5245 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005246 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005247 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248 }
5249 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250 return changes;
5251 }
5252
Wale Ogunwalef6733932018-06-27 05:14:34 -07005253 private void updateEventDispatchingLocked(boolean booted) {
5254 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5255 }
5256
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005257 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5258 final ContentResolver resolver = mContext.getContentResolver();
5259 Settings.System.putConfigurationForUser(resolver, config, userId);
5260 }
5261
5262 private void sendLocaleToMountDaemonMsg(Locale l) {
5263 try {
5264 IBinder service = ServiceManager.getService("mount");
5265 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5266 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5267 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5268 } catch (RemoteException e) {
5269 Log.e(TAG, "Error storing locale for decryption UI", e);
5270 }
5271 }
5272
Alison Cichowlas3e340502018-08-07 17:15:01 -04005273 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5274 mStartActivitySources.remove(permissionToken);
5275 mExpiredStartAsCallerTokens.add(permissionToken);
5276 }
5277
5278 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5279 mExpiredStartAsCallerTokens.remove(permissionToken);
5280 }
5281
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005282 boolean isActivityStartsLoggingEnabled() {
5283 return mAmInternal.isActivityStartsLoggingEnabled();
5284 }
5285
Michal Karpinski8596ded2018-11-14 14:43:48 +00005286 boolean isBackgroundActivityStartsEnabled() {
5287 return mAmInternal.isBackgroundActivityStartsEnabled();
5288 }
5289
Michal Karpinski666631b2019-02-26 16:59:11 +00005290 boolean isPackageNameWhitelistedForBgActivityStarts(String packageName) {
5291 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5292 }
5293
Wale Ogunwalef6733932018-06-27 05:14:34 -07005294 void enableScreenAfterBoot(boolean booted) {
5295 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5296 SystemClock.uptimeMillis());
5297 mWindowManager.enableScreenAfterBoot();
5298
5299 synchronized (mGlobalLock) {
5300 updateEventDispatchingLocked(booted);
5301 }
5302 }
5303
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005304 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5305 if (r == null || !r.hasProcess()) {
5306 return KEY_DISPATCHING_TIMEOUT_MS;
5307 }
5308 return getInputDispatchingTimeoutLocked(r.app);
5309 }
5310
5311 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005312 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005313 }
5314
Wale Ogunwalef6733932018-06-27 05:14:34 -07005315 /**
5316 * Decide based on the configuration whether we should show the ANR,
5317 * crash, etc dialogs. The idea is that if there is no affordance to
5318 * press the on-screen buttons, or the user experience would be more
5319 * greatly impacted than the crash itself, we shouldn't show the dialog.
5320 *
5321 * A thought: SystemUI might also want to get told about this, the Power
5322 * dialog / global actions also might want different behaviors.
5323 */
5324 private void updateShouldShowDialogsLocked(Configuration config) {
5325 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5326 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5327 && config.navigation == Configuration.NAVIGATION_NONAV);
5328 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5329 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5330 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5331 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5332 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5333 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5334 HIDE_ERROR_DIALOGS, 0) != 0;
5335 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5336 }
5337
5338 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5339 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5340 FONT_SCALE, 1.0f, userId);
5341
5342 synchronized (this) {
5343 if (getGlobalConfiguration().fontScale == scaleFactor) {
5344 return;
5345 }
5346
5347 final Configuration configuration
5348 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5349 configuration.fontScale = scaleFactor;
5350 updatePersistentConfiguration(configuration, userId);
5351 }
5352 }
5353
5354 // Actually is sleeping or shutting down or whatever else in the future
5355 // is an inactive state.
5356 boolean isSleepingOrShuttingDownLocked() {
5357 return isSleepingLocked() || mShuttingDown;
5358 }
5359
5360 boolean isSleepingLocked() {
5361 return mSleeping;
5362 }
5363
Riddle Hsu16567132018-08-16 21:37:47 +08005364 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005365 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005366 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005367 if (task.isActivityTypeStandard()) {
5368 if (mCurAppTimeTracker != r.appTimeTracker) {
5369 // We are switching app tracking. Complete the current one.
5370 if (mCurAppTimeTracker != null) {
5371 mCurAppTimeTracker.stop();
5372 mH.obtainMessage(
5373 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005374 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005375 mCurAppTimeTracker = null;
5376 }
5377 if (r.appTimeTracker != null) {
5378 mCurAppTimeTracker = r.appTimeTracker;
5379 startTimeTrackingFocusedActivityLocked();
5380 }
5381 } else {
5382 startTimeTrackingFocusedActivityLocked();
5383 }
5384 } else {
5385 r.appTimeTracker = null;
5386 }
5387 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5388 // TODO: Probably not, because we don't want to resume voice on switching
5389 // back to this activity
5390 if (task.voiceInteractor != null) {
5391 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5392 } else {
5393 finishRunningVoiceLocked();
5394
5395 if (mLastResumedActivity != null) {
5396 final IVoiceInteractionSession session;
5397
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005398 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005399 if (lastResumedActivityTask != null
5400 && lastResumedActivityTask.voiceSession != null) {
5401 session = lastResumedActivityTask.voiceSession;
5402 } else {
5403 session = mLastResumedActivity.voiceSession;
5404 }
5405
5406 if (session != null) {
5407 // We had been in a voice interaction session, but now focused has
5408 // move to something different. Just finish the session, we can't
5409 // return to it and retain the proper state and synchronization with
5410 // the voice interaction service.
5411 finishVoiceTask(session);
5412 }
5413 }
5414 }
5415
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005416 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5417 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 }
5419 updateResumedAppTrace(r);
5420 mLastResumedActivity = r;
5421
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005422 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005423
5424 applyUpdateLockStateLocked(r);
5425 applyUpdateVrModeLocked(r);
5426
5427 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005428 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005429 r == null ? "NULL" : r.shortComponentName,
5430 reason);
5431 }
5432
5433 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5434 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005435 final ActivityTaskManagerInternal.SleepToken token =
5436 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 updateSleepIfNeededLocked();
5438 return token;
5439 }
5440 }
5441
5442 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005443 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005444 final boolean wasSleeping = mSleeping;
5445 boolean updateOomAdj = false;
5446
5447 if (!shouldSleep) {
5448 // If wasSleeping is true, we need to wake up activity manager state from when
5449 // we started sleeping. In either case, we need to apply the sleep tokens, which
5450 // will wake up stacks or put them to sleep as appropriate.
5451 if (wasSleeping) {
5452 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005453 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5454 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 startTimeTrackingFocusedActivityLocked();
5456 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5457 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5458 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005459 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005460 if (wasSleeping) {
5461 updateOomAdj = true;
5462 }
5463 } else if (!mSleeping && shouldSleep) {
5464 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005465 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5466 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005467 if (mCurAppTimeTracker != null) {
5468 mCurAppTimeTracker.stop();
5469 }
5470 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5471 mStackSupervisor.goingToSleepLocked();
5472 updateResumedAppTrace(null /* resumed */);
5473 updateOomAdj = true;
5474 }
5475 if (updateOomAdj) {
5476 mH.post(mAmInternal::updateOomAdj);
5477 }
5478 }
5479
5480 void updateOomAdj() {
5481 mH.post(mAmInternal::updateOomAdj);
5482 }
5483
Wale Ogunwale53783742018-09-16 10:21:51 -07005484 void updateCpuStats() {
5485 mH.post(mAmInternal::updateCpuStats);
5486 }
5487
Hui Yu03d12402018-12-06 18:00:37 -08005488 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5489 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005490 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5491 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005492 mH.sendMessage(m);
5493 }
5494
Hui Yu03d12402018-12-06 18:00:37 -08005495 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005496 ComponentName taskRoot = null;
5497 final TaskRecord task = activity.getTaskRecord();
5498 if (task != null) {
5499 final ActivityRecord rootActivity = task.getRootActivity();
5500 if (rootActivity != null) {
5501 taskRoot = rootActivity.mActivityComponent;
5502 }
5503 }
5504
Hui Yu03d12402018-12-06 18:00:37 -08005505 final Message m = PooledLambda.obtainMessage(
5506 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005507 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005508 mH.sendMessage(m);
5509 }
5510
Wale Ogunwale53783742018-09-16 10:21:51 -07005511 void setBooting(boolean booting) {
5512 mAmInternal.setBooting(booting);
5513 }
5514
5515 boolean isBooting() {
5516 return mAmInternal.isBooting();
5517 }
5518
5519 void setBooted(boolean booted) {
5520 mAmInternal.setBooted(booted);
5521 }
5522
5523 boolean isBooted() {
5524 return mAmInternal.isBooted();
5525 }
5526
5527 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5528 mH.post(() -> {
5529 if (finishBooting) {
5530 mAmInternal.finishBooting();
5531 }
5532 if (enableScreen) {
5533 mInternal.enableScreenAfterBoot(isBooted());
5534 }
5535 });
5536 }
5537
5538 void setHeavyWeightProcess(ActivityRecord root) {
5539 mHeavyWeightProcess = root.app;
5540 final Message m = PooledLambda.obtainMessage(
5541 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005542 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005543 mH.sendMessage(m);
5544 }
5545
5546 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5547 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5548 return;
5549 }
5550
5551 mHeavyWeightProcess = null;
5552 final Message m = PooledLambda.obtainMessage(
5553 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5554 proc.mUserId);
5555 mH.sendMessage(m);
5556 }
5557
5558 private void cancelHeavyWeightProcessNotification(int userId) {
5559 final INotificationManager inm = NotificationManager.getService();
5560 if (inm == null) {
5561 return;
5562 }
5563 try {
5564 inm.cancelNotificationWithTag("android", null,
5565 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5566 } catch (RuntimeException e) {
5567 Slog.w(TAG, "Error canceling notification for service", e);
5568 } catch (RemoteException e) {
5569 }
5570
5571 }
5572
5573 private void postHeavyWeightProcessNotification(
5574 WindowProcessController proc, Intent intent, int userId) {
5575 if (proc == null) {
5576 return;
5577 }
5578
5579 final INotificationManager inm = NotificationManager.getService();
5580 if (inm == null) {
5581 return;
5582 }
5583
5584 try {
5585 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5586 String text = mContext.getString(R.string.heavy_weight_notification,
5587 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5588 Notification notification =
5589 new Notification.Builder(context,
5590 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5591 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5592 .setWhen(0)
5593 .setOngoing(true)
5594 .setTicker(text)
5595 .setColor(mContext.getColor(
5596 com.android.internal.R.color.system_notification_accent_color))
5597 .setContentTitle(text)
5598 .setContentText(
5599 mContext.getText(R.string.heavy_weight_notification_detail))
5600 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5601 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5602 new UserHandle(userId)))
5603 .build();
5604 try {
5605 inm.enqueueNotificationWithTag("android", "android", null,
5606 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5607 } catch (RuntimeException e) {
5608 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5609 } catch (RemoteException e) {
5610 }
5611 } catch (PackageManager.NameNotFoundException e) {
5612 Slog.w(TAG, "Unable to create context for heavy notification", e);
5613 }
5614
5615 }
5616
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005617 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5618 IBinder token, String resultWho, int requestCode, Intent[] intents,
5619 String[] resolvedTypes, int flags, Bundle bOptions) {
5620
5621 ActivityRecord activity = null;
5622 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5623 activity = ActivityRecord.isInStackLocked(token);
5624 if (activity == null) {
5625 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5626 return null;
5627 }
5628 if (activity.finishing) {
5629 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5630 return null;
5631 }
5632 }
5633
5634 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5635 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5636 bOptions);
5637 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5638 if (noCreate) {
5639 return rec;
5640 }
5641 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5642 if (activity.pendingResults == null) {
5643 activity.pendingResults = new HashSet<>();
5644 }
5645 activity.pendingResults.add(rec.ref);
5646 }
5647 return rec;
5648 }
5649
Andrii Kulian52d255c2018-07-13 11:32:19 -07005650 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005651 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005652 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005653 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5654 mCurAppTimeTracker.start(resumedActivity.packageName);
5655 }
5656 }
5657
5658 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5659 if (mTracedResumedActivity != null) {
5660 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5661 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5662 }
5663 if (resumed != null) {
5664 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5665 constructResumedTraceName(resumed.packageName), 0);
5666 }
5667 mTracedResumedActivity = resumed;
5668 }
5669
5670 private String constructResumedTraceName(String packageName) {
5671 return "focused app: " + packageName;
5672 }
5673
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005674 /** Applies latest configuration and/or visibility updates if needed. */
5675 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5676 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005677 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005678 // mainStack is null during startup.
5679 if (mainStack != null) {
5680 if (changes != 0 && starting == null) {
5681 // If the configuration changed, and the caller is not already
5682 // in the process of starting an activity, then find the top
5683 // activity to check if its configuration needs to change.
5684 starting = mainStack.topRunningActivityLocked();
5685 }
5686
5687 if (starting != null) {
5688 kept = starting.ensureActivityConfiguration(changes,
5689 false /* preserveWindow */);
5690 // And we need to make sure at this point that all other activities
5691 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005692 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005693 !PRESERVE_WINDOWS);
5694 }
5695 }
5696
5697 return kept;
5698 }
5699
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005700 void scheduleAppGcsLocked() {
5701 mH.post(() -> mAmInternal.scheduleAppGcs());
5702 }
5703
Wale Ogunwale53783742018-09-16 10:21:51 -07005704 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5705 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5706 }
5707
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005708 /**
5709 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5710 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5711 * on demand.
5712 */
5713 IPackageManager getPackageManager() {
5714 return AppGlobals.getPackageManager();
5715 }
5716
5717 PackageManagerInternal getPackageManagerInternalLocked() {
5718 if (mPmInternal == null) {
5719 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5720 }
5721 return mPmInternal;
5722 }
5723
Wale Ogunwale008163e2018-07-23 23:11:08 -07005724 AppWarnings getAppWarningsLocked() {
5725 return mAppWarnings;
5726 }
5727
Wale Ogunwale214f3482018-10-04 11:00:47 -07005728 Intent getHomeIntent() {
5729 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5730 intent.setComponent(mTopComponent);
5731 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5732 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5733 intent.addCategory(Intent.CATEGORY_HOME);
5734 }
5735 return intent;
5736 }
5737
Chilun2ef71f72018-11-16 17:57:15 +08005738 /**
5739 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5740 * activities.
5741 *
5742 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5743 * component defined in config_secondaryHomeComponent.
5744 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5745 */
5746 Intent getSecondaryHomeIntent(String preferredPackage) {
5747 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5748 if (preferredPackage == null) {
5749 // Using the component stored in config if no package name.
5750 final String secondaryHomeComponent = mContext.getResources().getString(
5751 com.android.internal.R.string.config_secondaryHomeComponent);
5752 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5753 } else {
5754 intent.setPackage(preferredPackage);
5755 }
5756 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5757 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5758 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5759 }
5760 return intent;
5761 }
5762
Wale Ogunwale214f3482018-10-04 11:00:47 -07005763 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5764 if (info == null) return null;
5765 ApplicationInfo newInfo = new ApplicationInfo(info);
5766 newInfo.initForUser(userId);
5767 return newInfo;
5768 }
5769
Wale Ogunwale9c103022018-10-18 07:44:54 -07005770 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005771 if (uid == SYSTEM_UID) {
5772 // The system gets to run in any process. If there are multiple processes with the same
5773 // uid, just pick the first (this should never happen).
5774 final SparseArray<WindowProcessController> procs =
5775 mProcessNames.getMap().get(processName);
5776 if (procs == null) return null;
5777 final int procCount = procs.size();
5778 for (int i = 0; i < procCount; i++) {
5779 final int procUid = procs.keyAt(i);
5780 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5781 // Don't use an app process or different user process for system component.
5782 continue;
5783 }
5784 return procs.valueAt(i);
5785 }
5786 }
5787
5788 return mProcessNames.get(processName, uid);
5789 }
5790
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005791 WindowProcessController getProcessController(IApplicationThread thread) {
5792 if (thread == null) {
5793 return null;
5794 }
5795
5796 final IBinder threadBinder = thread.asBinder();
5797 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5798 for (int i = pmap.size()-1; i >= 0; i--) {
5799 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5800 for (int j = procs.size() - 1; j >= 0; j--) {
5801 final WindowProcessController proc = procs.valueAt(j);
5802 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5803 return proc;
5804 }
5805 }
5806 }
5807
5808 return null;
5809 }
5810
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005811 WindowProcessController getProcessController(int pid, int uid) {
5812 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5813 for (int i = pmap.size()-1; i >= 0; i--) {
5814 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5815 for (int j = procs.size() - 1; j >= 0; j--) {
5816 final WindowProcessController proc = procs.valueAt(j);
5817 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5818 return proc;
5819 }
5820 }
5821 }
5822 return null;
5823 }
5824
Riddle Hsua0536432019-02-16 00:38:59 +08005825 int getUidState(int uid) {
5826 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005827 }
5828
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005829 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005830 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005831 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5832 }
5833
Michal Karpinski4026cae2019-02-12 11:51:47 +00005834 boolean isDeviceOwner(String packageName) {
5835 if (packageName == null) {
5836 return false;
5837 }
5838 return packageName.equals(mDeviceOwnerPackageName);
5839 }
5840
5841 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5842 mDeviceOwnerPackageName = deviceOwnerPkg;
5843 }
5844
Wale Ogunwale9de19442018-10-18 19:05:03 -07005845 /**
5846 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5847 * the whitelist
5848 */
5849 String getPendingTempWhitelistTagForUidLocked(int uid) {
5850 return mPendingTempWhitelist.get(uid);
5851 }
5852
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005853 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5854 if (true || Build.IS_USER) {
5855 return;
5856 }
5857
5858 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5859 StrictMode.allowThreadDiskWrites();
5860 try {
5861 File tracesDir = new File("/data/anr");
5862 File tracesFile = null;
5863 try {
5864 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5865
5866 StringBuilder sb = new StringBuilder();
5867 Time tobj = new Time();
5868 tobj.set(System.currentTimeMillis());
5869 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5870 sb.append(": ");
5871 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5872 sb.append(" since ");
5873 sb.append(msg);
5874 FileOutputStream fos = new FileOutputStream(tracesFile);
5875 fos.write(sb.toString().getBytes());
5876 if (app == null) {
5877 fos.write("\n*** No application process!".getBytes());
5878 }
5879 fos.close();
5880 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5881 } catch (IOException e) {
5882 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5883 return;
5884 }
5885
5886 if (app != null && app.getPid() > 0) {
5887 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5888 firstPids.add(app.getPid());
5889 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5890 }
5891
5892 File lastTracesFile = null;
5893 File curTracesFile = null;
5894 for (int i=9; i>=0; i--) {
5895 String name = String.format(Locale.US, "slow%02d.txt", i);
5896 curTracesFile = new File(tracesDir, name);
5897 if (curTracesFile.exists()) {
5898 if (lastTracesFile != null) {
5899 curTracesFile.renameTo(lastTracesFile);
5900 } else {
5901 curTracesFile.delete();
5902 }
5903 }
5904 lastTracesFile = curTracesFile;
5905 }
5906 tracesFile.renameTo(curTracesFile);
5907 } finally {
5908 StrictMode.setThreadPolicy(oldPolicy);
5909 }
5910 }
5911
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005912 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005913 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005914
5915
Wale Ogunwale98875612018-10-12 07:53:02 -07005916 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5917 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005918
Riddle Hsud93a6c42018-11-29 21:50:06 +08005919 H(Looper looper) {
5920 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005921 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005922
5923 @Override
5924 public void handleMessage(Message msg) {
5925 switch (msg.what) {
5926 case REPORT_TIME_TRACKER_MSG: {
5927 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5928 tracker.deliverResult(mContext);
5929 } break;
5930 }
5931 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005932 }
5933
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005934 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005935 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005936
5937 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005938 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005939 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005940
5941 @Override
5942 public void handleMessage(Message msg) {
5943 switch (msg.what) {
5944 case DISMISS_DIALOG_UI_MSG: {
5945 final Dialog d = (Dialog) msg.obj;
5946 d.dismiss();
5947 break;
5948 }
5949 }
5950 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005951 }
5952
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005953 final class LocalService extends ActivityTaskManagerInternal {
5954 @Override
5955 public SleepToken acquireSleepToken(String tag, int displayId) {
5956 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005957 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005958 }
5959
5960 @Override
5961 public ComponentName getHomeActivityForUser(int userId) {
5962 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005963 final ActivityRecord homeActivity =
5964 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005965 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005966 }
5967 }
5968
5969 @Override
5970 public void onLocalVoiceInteractionStarted(IBinder activity,
5971 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5972 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005973 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005974 }
5975 }
5976
5977 @Override
5978 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5979 synchronized (mGlobalLock) {
5980 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5981 reasons, timestamp);
5982 }
5983 }
5984
5985 @Override
5986 public void notifyAppTransitionFinished() {
5987 synchronized (mGlobalLock) {
5988 mStackSupervisor.notifyAppTransitionDone();
5989 }
5990 }
5991
5992 @Override
5993 public void notifyAppTransitionCancelled() {
5994 synchronized (mGlobalLock) {
5995 mStackSupervisor.notifyAppTransitionDone();
5996 }
5997 }
5998
5999 @Override
6000 public List<IBinder> getTopVisibleActivities() {
6001 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006002 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 }
6004 }
6005
6006 @Override
6007 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6008 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006009 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006010 }
6011 }
6012
6013 @Override
6014 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6015 Bundle bOptions) {
6016 Preconditions.checkNotNull(intents, "intents");
6017 final String[] resolvedTypes = new String[intents.length];
6018
6019 // UID of the package on user userId.
6020 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6021 // packageUid may not be initialized.
6022 int packageUid = 0;
6023 final long ident = Binder.clearCallingIdentity();
6024
6025 try {
6026 for (int i = 0; i < intents.length; i++) {
6027 resolvedTypes[i] =
6028 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6029 }
6030
6031 packageUid = AppGlobals.getPackageManager().getPackageUid(
6032 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6033 } catch (RemoteException e) {
6034 // Shouldn't happen.
6035 } finally {
6036 Binder.restoreCallingIdentity(ident);
6037 }
6038
Riddle Hsu591bf612019-02-14 17:55:31 +08006039 return getActivityStartController().startActivitiesInPackage(
6040 packageUid, packageName,
6041 intents, resolvedTypes, null /* resultTo */,
6042 SafeActivityOptions.fromBundle(bOptions), userId,
6043 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6044 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046
6047 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006048 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6049 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6050 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6051 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006052 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006053 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006054 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6055 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6056 userId, validateIncomingUser, originatingPendingIntent,
6057 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006058 }
6059 }
6060
6061 @Override
6062 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6063 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6064 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6065 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006066 PendingIntentRecord originatingPendingIntent,
6067 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006068 synchronized (mGlobalLock) {
6069 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6070 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6071 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006072 validateIncomingUser, originatingPendingIntent,
6073 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006074 }
6075 }
6076
6077 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006078 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6079 Intent intent, Bundle options, int userId) {
6080 return ActivityTaskManagerService.this.startActivityAsUser(
6081 caller, callerPacakge, intent,
6082 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6083 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6084 false /*validateIncomingUser*/);
6085 }
6086
6087 @Override
lumark588a3e82018-07-20 18:53:54 +08006088 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006089 synchronized (mGlobalLock) {
6090
6091 // We might change the visibilities here, so prepare an empty app transition which
6092 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006093 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006094 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006095 if (activityDisplay == null) {
6096 return;
6097 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006098 final DisplayContent dc = activityDisplay.mDisplayContent;
6099 final boolean wasTransitionSet =
6100 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006101 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006102 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006103 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006104 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006105
6106 // If there was a transition set already we don't want to interfere with it as we
6107 // might be starting it too early.
6108 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006109 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 }
6111 }
6112 if (callback != null) {
6113 callback.run();
6114 }
6115 }
6116
6117 @Override
6118 public void notifyKeyguardTrustedChanged() {
6119 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006120 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006121 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006122 }
6123 }
6124 }
6125
6126 /**
6127 * Called after virtual display Id is updated by
6128 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6129 * {@param vrVr2dDisplayId}.
6130 */
6131 @Override
6132 public void setVr2dDisplayId(int vr2dDisplayId) {
6133 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6134 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006135 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006136 }
6137 }
6138
6139 @Override
6140 public void setFocusedActivity(IBinder token) {
6141 synchronized (mGlobalLock) {
6142 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6143 if (r == null) {
6144 throw new IllegalArgumentException(
6145 "setFocusedActivity: No activity record matching token=" + token);
6146 }
Louis Chang19443452018-10-09 12:10:21 +08006147 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006148 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006149 }
6150 }
6151 }
6152
6153 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006155 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006156 }
6157
6158 @Override
6159 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006160 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162
6163 @Override
6164 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006165 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167
6168 @Override
6169 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6170 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6171 }
6172
6173 @Override
6174 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006175 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006177
6178 @Override
6179 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6180 synchronized (mGlobalLock) {
6181 mActiveVoiceInteractionServiceComponent = component;
6182 }
6183 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006184
6185 @Override
6186 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6187 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6188 return;
6189 }
6190 synchronized (mGlobalLock) {
6191 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6192 if (types == null) {
6193 if (uid < 0) {
6194 return;
6195 }
6196 types = new ArrayMap<>();
6197 mAllowAppSwitchUids.put(userId, types);
6198 }
6199 if (uid < 0) {
6200 types.remove(type);
6201 } else {
6202 types.put(type, uid);
6203 }
6204 }
6205 }
6206
6207 @Override
6208 public void onUserStopped(int userId) {
6209 synchronized (mGlobalLock) {
6210 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6211 mAllowAppSwitchUids.remove(userId);
6212 }
6213 }
6214
6215 @Override
6216 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6217 synchronized (mGlobalLock) {
6218 return ActivityTaskManagerService.this.isGetTasksAllowed(
6219 caller, callingPid, callingUid);
6220 }
6221 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006222
Riddle Hsua0536432019-02-16 00:38:59 +08006223 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006224 @Override
6225 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006226 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006227 mProcessNames.put(proc.mName, proc.mUid, proc);
6228 }
6229 }
6230
Riddle Hsua0536432019-02-16 00:38:59 +08006231 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006232 @Override
6233 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006234 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006235 mProcessNames.remove(name, uid);
6236 }
6237 }
6238
Riddle Hsua0536432019-02-16 00:38:59 +08006239 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006240 @Override
6241 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006242 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006243 if (proc == mHomeProcess) {
6244 mHomeProcess = null;
6245 }
6246 if (proc == mPreviousProcess) {
6247 mPreviousProcess = null;
6248 }
6249 }
6250 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006251
Riddle Hsua0536432019-02-16 00:38:59 +08006252 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006253 @Override
6254 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006255 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006256 return mTopProcessState;
6257 }
6258 }
6259
Riddle Hsua0536432019-02-16 00:38:59 +08006260 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006261 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006262 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006263 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006264 return proc == mHeavyWeightProcess;
6265 }
6266 }
6267
Riddle Hsua0536432019-02-16 00:38:59 +08006268 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006269 @Override
6270 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006271 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006272 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6273 }
6274 }
6275
6276 @Override
6277 public void finishHeavyWeightApp() {
6278 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006279 if (mHeavyWeightProcess != null) {
6280 mHeavyWeightProcess.finishActivities();
6281 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006282 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6283 mHeavyWeightProcess);
6284 }
6285 }
6286
Riddle Hsua0536432019-02-16 00:38:59 +08006287 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006288 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006289 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006290 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006291 return isSleepingLocked();
6292 }
6293 }
6294
6295 @Override
6296 public boolean isShuttingDown() {
6297 synchronized (mGlobalLock) {
6298 return mShuttingDown;
6299 }
6300 }
6301
6302 @Override
6303 public boolean shuttingDown(boolean booted, int timeout) {
6304 synchronized (mGlobalLock) {
6305 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006306 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006307 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006308 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006309 return mStackSupervisor.shutdownLocked(timeout);
6310 }
6311 }
6312
6313 @Override
6314 public void enableScreenAfterBoot(boolean booted) {
6315 synchronized (mGlobalLock) {
6316 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6317 SystemClock.uptimeMillis());
6318 mWindowManager.enableScreenAfterBoot();
6319 updateEventDispatchingLocked(booted);
6320 }
6321 }
6322
6323 @Override
6324 public boolean showStrictModeViolationDialog() {
6325 synchronized (mGlobalLock) {
6326 return mShowDialogs && !mSleeping && !mShuttingDown;
6327 }
6328 }
6329
6330 @Override
6331 public void showSystemReadyErrorDialogsIfNeeded() {
6332 synchronized (mGlobalLock) {
6333 try {
6334 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6335 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6336 + " data partition or your device will be unstable.");
6337 mUiHandler.post(() -> {
6338 if (mShowDialogs) {
6339 AlertDialog d = new BaseErrorDialog(mUiContext);
6340 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6341 d.setCancelable(false);
6342 d.setTitle(mUiContext.getText(R.string.android_system_label));
6343 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6344 d.setButton(DialogInterface.BUTTON_POSITIVE,
6345 mUiContext.getText(R.string.ok),
6346 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6347 d.show();
6348 }
6349 });
6350 }
6351 } catch (RemoteException e) {
6352 }
6353
6354 if (!Build.isBuildConsistent()) {
6355 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6356 mUiHandler.post(() -> {
6357 if (mShowDialogs) {
6358 AlertDialog d = new BaseErrorDialog(mUiContext);
6359 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6360 d.setCancelable(false);
6361 d.setTitle(mUiContext.getText(R.string.android_system_label));
6362 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6363 d.setButton(DialogInterface.BUTTON_POSITIVE,
6364 mUiContext.getText(R.string.ok),
6365 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6366 d.show();
6367 }
6368 });
6369 }
6370 }
6371 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006372
6373 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006374 public void onProcessMapped(int pid, WindowProcessController proc) {
6375 synchronized (mGlobalLock) {
6376 mPidMap.put(pid, proc);
6377 }
6378 }
6379
6380 @Override
6381 public void onProcessUnMapped(int pid) {
6382 synchronized (mGlobalLock) {
6383 mPidMap.remove(pid);
6384 }
6385 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006386
6387 @Override
6388 public void onPackageDataCleared(String name) {
6389 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006390 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006391 mAppWarnings.onPackageDataCleared(name);
6392 }
6393 }
6394
6395 @Override
6396 public void onPackageUninstalled(String name) {
6397 synchronized (mGlobalLock) {
6398 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006399 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006400 }
6401 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006402
6403 @Override
6404 public void onPackageAdded(String name, boolean replacing) {
6405 synchronized (mGlobalLock) {
6406 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6407 }
6408 }
6409
6410 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006411 public void onPackageReplaced(ApplicationInfo aInfo) {
6412 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006413 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006414 }
6415 }
6416
6417 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006418 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6419 synchronized (mGlobalLock) {
6420 return compatibilityInfoForPackageLocked(ai);
6421 }
6422 }
6423
Yunfan Chen75157d72018-07-27 14:47:21 +09006424 /**
6425 * Set the corresponding display information for the process global configuration. To be
6426 * called when we need to show IME on a different display.
6427 *
6428 * @param pid The process id associated with the IME window.
6429 * @param displayId The ID of the display showing the IME.
6430 */
6431 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006432 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006433 if (pid == MY_PID || pid < 0) {
6434 if (DEBUG_CONFIGURATION) {
6435 Slog.w(TAG,
6436 "Trying to update display configuration for system/invalid process.");
6437 }
6438 return;
6439 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006440 synchronized (mGlobalLock) {
6441 final ActivityDisplay activityDisplay =
6442 mRootActivityContainer.getActivityDisplay(displayId);
6443 if (activityDisplay == null) {
6444 // Call might come when display is not yet added or has been removed.
6445 if (DEBUG_CONFIGURATION) {
6446 Slog.w(TAG, "Trying to update display configuration for non-existing "
6447 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006448 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006449 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006450 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006451 final WindowProcessController process = mPidMap.get(pid);
6452 if (process == null) {
6453 if (DEBUG_CONFIGURATION) {
6454 Slog.w(TAG, "Trying to update display configuration for invalid "
6455 + "process, pid=" + pid);
6456 }
6457 return;
6458 }
6459 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6460 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006461 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006462
6463 @Override
6464 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6465 int requestCode, int resultCode, Intent data) {
6466 synchronized (mGlobalLock) {
6467 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006468 if (r != null && r.getActivityStack() != null) {
6469 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6470 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006471 }
6472 }
6473 }
6474
6475 @Override
6476 public void clearPendingResultForActivity(IBinder activityToken,
6477 WeakReference<PendingIntentRecord> pir) {
6478 synchronized (mGlobalLock) {
6479 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6480 if (r != null && r.pendingResults != null) {
6481 r.pendingResults.remove(pir);
6482 }
6483 }
6484 }
6485
6486 @Override
6487 public IIntentSender getIntentSender(int type, String packageName,
6488 int callingUid, int userId, IBinder token, String resultWho,
6489 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6490 Bundle bOptions) {
6491 synchronized (mGlobalLock) {
6492 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6493 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6494 }
6495 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006496
6497 @Override
6498 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6499 synchronized (mGlobalLock) {
6500 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6501 if (r == null) {
6502 return null;
6503 }
6504 if (r.mServiceConnectionsHolder == null) {
6505 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6506 ActivityTaskManagerService.this, r);
6507 }
6508
6509 return r.mServiceConnectionsHolder;
6510 }
6511 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006512
6513 @Override
6514 public Intent getHomeIntent() {
6515 synchronized (mGlobalLock) {
6516 return ActivityTaskManagerService.this.getHomeIntent();
6517 }
6518 }
6519
6520 @Override
6521 public boolean startHomeActivity(int userId, String reason) {
6522 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006523 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006524 }
6525 }
6526
6527 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006528 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006529 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006530 synchronized (mGlobalLock) {
6531 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006532 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006533 }
Chilun8b1f1be2019-03-13 17:14:36 +08006534 }
6535
6536 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006537 public boolean startHomeOnAllDisplays(int userId, String reason) {
6538 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006539 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006540 }
6541 }
6542
Riddle Hsua0536432019-02-16 00:38:59 +08006543 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006544 @Override
6545 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006546 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006547 if (mFactoryTest == FACTORY_TEST_OFF) {
6548 return false;
6549 }
6550 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6551 && wpc.mName.equals(mTopComponent.getPackageName())) {
6552 return true;
6553 }
6554 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6555 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6556 }
6557 }
6558
6559 @Override
6560 public void updateTopComponentForFactoryTest() {
6561 synchronized (mGlobalLock) {
6562 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6563 return;
6564 }
6565 final ResolveInfo ri = mContext.getPackageManager()
6566 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6567 final CharSequence errorMsg;
6568 if (ri != null) {
6569 final ActivityInfo ai = ri.activityInfo;
6570 final ApplicationInfo app = ai.applicationInfo;
6571 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6572 mTopAction = Intent.ACTION_FACTORY_TEST;
6573 mTopData = null;
6574 mTopComponent = new ComponentName(app.packageName, ai.name);
6575 errorMsg = null;
6576 } else {
6577 errorMsg = mContext.getResources().getText(
6578 com.android.internal.R.string.factorytest_not_system);
6579 }
6580 } else {
6581 errorMsg = mContext.getResources().getText(
6582 com.android.internal.R.string.factorytest_no_action);
6583 }
6584 if (errorMsg == null) {
6585 return;
6586 }
6587
6588 mTopAction = null;
6589 mTopData = null;
6590 mTopComponent = null;
6591 mUiHandler.post(() -> {
6592 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6593 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006594 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006595 });
6596 }
6597 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006598
Riddle Hsua0536432019-02-16 00:38:59 +08006599 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 @Override
6601 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6602 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006603 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006604 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006605 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006606
6607 wpc.clearRecentTasks();
6608 wpc.clearActivities();
6609
6610 if (wpc.isInstrumenting()) {
6611 finishInstrumentationCallback.run();
6612 }
6613
Jorim Jaggid0752812018-10-16 16:07:20 +02006614 if (!restarting && hasVisibleActivities) {
6615 mWindowManager.deferSurfaceLayout();
6616 try {
6617 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6618 // If there was nothing to resume, and we are not already restarting
6619 // this process, but there is a visible activity that is hosted by the
6620 // process...then make sure all visible activities are running, taking
6621 // care of restarting this process.
6622 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6623 !PRESERVE_WINDOWS);
6624 }
6625 } finally {
6626 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006627 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006628 }
6629 }
6630 }
6631
6632 @Override
6633 public void closeSystemDialogs(String reason) {
6634 enforceNotIsolatedCaller("closeSystemDialogs");
6635
6636 final int pid = Binder.getCallingPid();
6637 final int uid = Binder.getCallingUid();
6638 final long origId = Binder.clearCallingIdentity();
6639 try {
6640 synchronized (mGlobalLock) {
6641 // Only allow this from foreground processes, so that background
6642 // applications can't abuse it to prevent system UI from being shown.
6643 if (uid >= FIRST_APPLICATION_UID) {
6644 final WindowProcessController proc = mPidMap.get(pid);
6645 if (!proc.isPerceptible()) {
6646 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6647 + " from background process " + proc);
6648 return;
6649 }
6650 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006651 mWindowManager.closeSystemDialogs(reason);
6652
Wale Ogunwaled32da472018-11-16 07:19:28 -08006653 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006655 // Call into AM outside the synchronized block.
6656 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006657 } finally {
6658 Binder.restoreCallingIdentity(origId);
6659 }
6660 }
6661
6662 @Override
6663 public void cleanupDisabledPackageComponents(
6664 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6665 synchronized (mGlobalLock) {
6666 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006667 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006668 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006669 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006670 mStackSupervisor.scheduleIdleLocked();
6671 }
6672
6673 // Clean-up disabled tasks
6674 getRecentTasks().cleanupDisabledPackageTasksLocked(
6675 packageName, disabledClasses, userId);
6676 }
6677 }
6678
6679 @Override
6680 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6681 int userId) {
6682 synchronized (mGlobalLock) {
6683
6684 boolean didSomething =
6685 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006686 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006687 null, doit, evenPersistent, userId);
6688 return didSomething;
6689 }
6690 }
6691
6692 @Override
6693 public void resumeTopActivities(boolean scheduleIdle) {
6694 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006695 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006696 if (scheduleIdle) {
6697 mStackSupervisor.scheduleIdleLocked();
6698 }
6699 }
6700 }
6701
Riddle Hsua0536432019-02-16 00:38:59 +08006702 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006703 @Override
6704 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006705 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6707 }
6708 }
6709
Riddle Hsua0536432019-02-16 00:38:59 +08006710 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006711 @Override
6712 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006713 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006714 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006715 }
6716 }
6717
6718 @Override
6719 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6720 try {
6721 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6722 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6723 }
6724 } catch (RemoteException ex) {
6725 throw new SecurityException("Fail to check is caller a privileged app", ex);
6726 }
6727
6728 synchronized (mGlobalLock) {
6729 final long ident = Binder.clearCallingIdentity();
6730 try {
6731 if (mAmInternal.shouldConfirmCredentials(userId)) {
6732 if (mKeyguardController.isKeyguardLocked()) {
6733 // Showing launcher to avoid user entering credential twice.
6734 startHomeActivity(currentUserId, "notifyLockedProfile");
6735 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006736 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 }
6738 } finally {
6739 Binder.restoreCallingIdentity(ident);
6740 }
6741 }
6742 }
6743
6744 @Override
6745 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6746 mAmInternal.enforceCallingPermission(
6747 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6748
6749 synchronized (mGlobalLock) {
6750 final long ident = Binder.clearCallingIdentity();
6751 try {
6752 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6753 FLAG_ACTIVITY_TASK_ON_HOME);
6754 ActivityOptions activityOptions = options != null
6755 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006756 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006757 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006758 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006759 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006760 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6762 UserHandle.CURRENT);
6763 } finally {
6764 Binder.restoreCallingIdentity(ident);
6765 }
6766 }
6767 }
6768
6769 @Override
6770 public void writeActivitiesToProto(ProtoOutputStream proto) {
6771 synchronized (mGlobalLock) {
6772 // The output proto of "activity --proto activities"
6773 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006774 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006775 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6776 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777 }
6778 }
6779
6780 @Override
6781 public void saveANRState(String reason) {
6782 synchronized (mGlobalLock) {
6783 final StringWriter sw = new StringWriter();
6784 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6785 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6786 if (reason != null) {
6787 pw.println(" Reason: " + reason);
6788 }
6789 pw.println();
6790 getActivityStartController().dump(pw, " ", null);
6791 pw.println();
6792 pw.println("-------------------------------------------------------------------------------");
6793 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6794 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6795 "" /* header */);
6796 pw.println();
6797 pw.close();
6798
6799 mLastANRState = sw.toString();
6800 }
6801 }
6802
6803 @Override
6804 public void clearSavedANRState() {
6805 synchronized (mGlobalLock) {
6806 mLastANRState = null;
6807 }
6808 }
6809
6810 @Override
6811 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6812 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6813 synchronized (mGlobalLock) {
6814 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6815 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6816 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6817 dumpLastANRLocked(pw);
6818 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6819 dumpLastANRTracesLocked(pw);
6820 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6821 dumpActivityStarterLocked(pw, dumpPackage);
6822 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6823 dumpActivityContainersLocked(pw);
6824 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6825 if (getRecentTasks() != null) {
6826 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6827 }
6828 }
6829 }
6830 }
6831
6832 @Override
6833 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6834 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6835 int wakefulness) {
6836 synchronized (mGlobalLock) {
6837 if (mHomeProcess != null && (dumpPackage == null
6838 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6839 if (needSep) {
6840 pw.println();
6841 needSep = false;
6842 }
6843 pw.println(" mHomeProcess: " + mHomeProcess);
6844 }
6845 if (mPreviousProcess != null && (dumpPackage == null
6846 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6847 if (needSep) {
6848 pw.println();
6849 needSep = false;
6850 }
6851 pw.println(" mPreviousProcess: " + mPreviousProcess);
6852 }
6853 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6854 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6855 StringBuilder sb = new StringBuilder(128);
6856 sb.append(" mPreviousProcessVisibleTime: ");
6857 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6858 pw.println(sb);
6859 }
6860 if (mHeavyWeightProcess != null && (dumpPackage == null
6861 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6862 if (needSep) {
6863 pw.println();
6864 needSep = false;
6865 }
6866 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6867 }
6868 if (dumpPackage == null) {
6869 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006870 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 }
6872 if (dumpAll) {
6873 if (dumpPackage == null) {
6874 pw.println(" mConfigWillChange: "
6875 + getTopDisplayFocusedStack().mConfigWillChange);
6876 }
6877 if (mCompatModePackages.getPackages().size() > 0) {
6878 boolean printed = false;
6879 for (Map.Entry<String, Integer> entry
6880 : mCompatModePackages.getPackages().entrySet()) {
6881 String pkg = entry.getKey();
6882 int mode = entry.getValue();
6883 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6884 continue;
6885 }
6886 if (!printed) {
6887 pw.println(" mScreenCompatPackages:");
6888 printed = true;
6889 }
6890 pw.println(" " + pkg + ": " + mode);
6891 }
6892 }
6893 }
6894
6895 if (dumpPackage == null) {
6896 pw.println(" mWakefulness="
6897 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006898 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006899 if (mRunningVoice != null) {
6900 pw.println(" mRunningVoice=" + mRunningVoice);
6901 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6902 }
6903 pw.println(" mSleeping=" + mSleeping);
6904 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6905 pw.println(" mVrController=" + mVrController);
6906 }
6907 if (mCurAppTimeTracker != null) {
6908 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6909 }
6910 if (mAllowAppSwitchUids.size() > 0) {
6911 boolean printed = false;
6912 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6913 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6914 for (int j = 0; j < types.size(); j++) {
6915 if (dumpPackage == null ||
6916 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6917 if (needSep) {
6918 pw.println();
6919 needSep = false;
6920 }
6921 if (!printed) {
6922 pw.println(" mAllowAppSwitchUids:");
6923 printed = true;
6924 }
6925 pw.print(" User ");
6926 pw.print(mAllowAppSwitchUids.keyAt(i));
6927 pw.print(": Type ");
6928 pw.print(types.keyAt(j));
6929 pw.print(" = ");
6930 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6931 pw.println();
6932 }
6933 }
6934 }
6935 }
6936 if (dumpPackage == null) {
6937 if (mController != null) {
6938 pw.println(" mController=" + mController
6939 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6940 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006941 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6942 pw.println(" mLaunchingActivityWakeLock="
6943 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 }
6945
6946 return needSep;
6947 }
6948 }
6949
6950 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006951 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6952 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006953 synchronized (mGlobalLock) {
6954 if (dumpPackage == null) {
6955 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6956 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006957 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6958 if (mRunningVoice != null) {
6959 final long vrToken = proto.start(
6960 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6961 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6962 mRunningVoice.toString());
6963 mVoiceWakeLock.writeToProto(
6964 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6965 proto.end(vrToken);
6966 }
6967 mVrController.writeToProto(proto,
6968 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006969 if (mController != null) {
6970 final long token = proto.start(CONTROLLER);
6971 proto.write(CONTROLLER, mController.toString());
6972 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6973 proto.end(token);
6974 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006975 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6976 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6977 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 }
6979
6980 if (mHomeProcess != null && (dumpPackage == null
6981 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006982 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006983 }
6984
6985 if (mPreviousProcess != null && (dumpPackage == null
6986 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006987 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006988 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6989 }
6990
6991 if (mHeavyWeightProcess != null && (dumpPackage == null
6992 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006993 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 }
6995
6996 for (Map.Entry<String, Integer> entry
6997 : mCompatModePackages.getPackages().entrySet()) {
6998 String pkg = entry.getKey();
6999 int mode = entry.getValue();
7000 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7001 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7002 proto.write(PACKAGE, pkg);
7003 proto.write(MODE, mode);
7004 proto.end(compatToken);
7005 }
7006 }
7007
7008 if (mCurAppTimeTracker != null) {
7009 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7010 }
7011
7012 }
7013 }
7014
7015 @Override
7016 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7017 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7018 boolean dumpFocusedStackOnly) {
7019 synchronized (mGlobalLock) {
7020 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7021 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7022 }
7023 }
7024
7025 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007026 public void dumpForOom(PrintWriter pw) {
7027 synchronized (mGlobalLock) {
7028 pw.println(" mHomeProcess: " + mHomeProcess);
7029 pw.println(" mPreviousProcess: " + mPreviousProcess);
7030 if (mHeavyWeightProcess != null) {
7031 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7032 }
7033 }
7034 }
7035
7036 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007037 public boolean canGcNow() {
7038 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007039 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 }
7041 }
7042
Riddle Hsua0536432019-02-16 00:38:59 +08007043 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007044 @Override
7045 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007046 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007047 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 return top != null ? top.app : null;
7049 }
7050 }
7051
Riddle Hsua0536432019-02-16 00:38:59 +08007052 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007053 @Override
7054 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007055 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007056 if (mRootActivityContainer != null) {
7057 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007058 }
7059 }
7060 }
7061
7062 @Override
7063 public void scheduleDestroyAllActivities(String reason) {
7064 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007065 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007066 }
7067 }
7068
7069 @Override
7070 public void removeUser(int userId) {
7071 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007072 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 }
7074 }
7075
7076 @Override
7077 public boolean switchUser(int userId, UserState userState) {
7078 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007079 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007080 }
7081 }
7082
7083 @Override
7084 public void onHandleAppCrash(WindowProcessController wpc) {
7085 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007086 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007087 }
7088 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007089
7090 @Override
7091 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7092 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007093 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007094 }
7095 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007096
Riddle Hsua0536432019-02-16 00:38:59 +08007097 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007098 @Override
7099 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007100 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007101 }
7102
Riddle Hsua0536432019-02-16 00:38:59 +08007103 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007104 @Override
7105 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007106 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007107 }
7108
Riddle Hsua0536432019-02-16 00:38:59 +08007109 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007110 @Override
7111 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007112 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007113 }
7114
Riddle Hsua0536432019-02-16 00:38:59 +08007115 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007116 @Override
7117 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007118 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007119 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007120
7121 @Override
7122 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007123 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007124 mPendingTempWhitelist.put(uid, tag);
7125 }
7126 }
7127
7128 @Override
7129 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007130 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007131 mPendingTempWhitelist.remove(uid);
7132 }
7133 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007134
7135 @Override
7136 public boolean handleAppCrashInActivityController(String processName, int pid,
7137 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7138 Runnable killCrashingAppCallback) {
7139 synchronized (mGlobalLock) {
7140 if (mController == null) {
7141 return false;
7142 }
7143
7144 try {
7145 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7146 stackTrace)) {
7147 killCrashingAppCallback.run();
7148 return true;
7149 }
7150 } catch (RemoteException e) {
7151 mController = null;
7152 Watchdog.getInstance().setActivityController(null);
7153 }
7154 return false;
7155 }
7156 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007157
7158 @Override
7159 public void removeRecentTasksByPackageName(String packageName, int userId) {
7160 synchronized (mGlobalLock) {
7161 mRecentTasks.removeTasksByPackageName(packageName, userId);
7162 }
7163 }
7164
7165 @Override
7166 public void cleanupRecentTasksForUser(int userId) {
7167 synchronized (mGlobalLock) {
7168 mRecentTasks.cleanupLocked(userId);
7169 }
7170 }
7171
7172 @Override
7173 public void loadRecentTasksForUser(int userId) {
7174 synchronized (mGlobalLock) {
7175 mRecentTasks.loadUserRecentsLocked(userId);
7176 }
7177 }
7178
7179 @Override
7180 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7181 synchronized (mGlobalLock) {
7182 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7183 }
7184 }
7185
7186 @Override
7187 public void flushRecentTasks() {
7188 mRecentTasks.flush();
7189 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007190
7191 @Override
7192 public WindowProcessController getHomeProcess() {
7193 synchronized (mGlobalLock) {
7194 return mHomeProcess;
7195 }
7196 }
7197
7198 @Override
7199 public WindowProcessController getPreviousProcess() {
7200 synchronized (mGlobalLock) {
7201 return mPreviousProcess;
7202 }
7203 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007204
7205 @Override
7206 public void clearLockedTasks(String reason) {
7207 synchronized (mGlobalLock) {
7208 getLockTaskController().clearLockedTasks(reason);
7209 }
7210 }
7211
7212 @Override
7213 public void updateUserConfiguration() {
7214 synchronized (mGlobalLock) {
7215 final Configuration configuration = new Configuration(getGlobalConfiguration());
7216 final int currentUserId = mAmInternal.getCurrentUserId();
7217 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7218 configuration, currentUserId, Settings.System.canWrite(mContext));
7219 updateConfigurationLocked(configuration, null /* starting */,
7220 false /* initLocale */, false /* persistent */, currentUserId,
7221 false /* deferResume */);
7222 }
7223 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007224
7225 @Override
7226 public boolean canShowErrorDialogs() {
7227 synchronized (mGlobalLock) {
7228 return mShowDialogs && !mSleeping && !mShuttingDown
7229 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7230 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7231 mAmInternal.getCurrentUserId())
7232 && !(UserManager.isDeviceInDemoMode(mContext)
7233 && mAmInternal.getCurrentUser().isDemo());
7234 }
7235 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007236
7237 @Override
7238 public void setProfileApp(String profileApp) {
7239 synchronized (mGlobalLock) {
7240 mProfileApp = profileApp;
7241 }
7242 }
7243
7244 @Override
7245 public void setProfileProc(WindowProcessController wpc) {
7246 synchronized (mGlobalLock) {
7247 mProfileProc = wpc;
7248 }
7249 }
7250
7251 @Override
7252 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7253 synchronized (mGlobalLock) {
7254 mProfilerInfo = profilerInfo;
7255 }
7256 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007257
7258 @Override
7259 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7260 synchronized (mGlobalLock) {
7261 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7262 }
7263 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007264
7265 @Override
7266 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7267 synchronized (mGlobalLock) {
7268 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7269 }
7270 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007271
7272 @Override
7273 public boolean isUidForeground(int uid) {
7274 synchronized (mGlobalLock) {
7275 return ActivityTaskManagerService.this.isUidForeground(uid);
7276 }
7277 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007278
7279 @Override
7280 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7281 synchronized (mGlobalLock) {
7282 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7283 }
7284 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007285 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007286}