blob: 7e9979da80f760cf4b8538e20519e2187331012c [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;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
Michal Karpinski302dcec2019-02-01 11:48:25 +0000154import android.app.admin.DevicePolicyManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
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;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700276import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700278import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700279import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400281import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700284import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Map;
286import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287
288/**
289 * System service for managing activities and their containers (task, stacks, displays,... ).
290 *
291 * {@hide}
292 */
293public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700294 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700296 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
297 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
298 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
299 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
300 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700301 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700303 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700304 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 /** Used to indicate that an app transition should be animated. */
309 static final boolean ANIMATE = true;
310
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700311 /** Hardware-reported OpenGLES version. */
312 final int GL_ES_VERSION;
313
Wale Ogunwale31913b52018-10-13 08:29:31 -0700314 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
315 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
316 public static final String DUMP_LASTANR_CMD = "lastanr" ;
317 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
318 public static final String DUMP_STARTER_CMD = "starter" ;
319 public static final String DUMP_CONTAINERS_CMD = "containers" ;
320 public static final String DUMP_RECENTS_CMD = "recents" ;
321 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
322
Wale Ogunwale64258362018-10-16 15:13:37 -0700323 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
324 public static final int RELAUNCH_REASON_NONE = 0;
325 /** This activity is being relaunched due to windowing mode change. */
326 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
327 /** This activity is being relaunched due to a free-resize operation. */
328 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
329
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700330 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700331
Wale Ogunwalef6733932018-06-27 05:14:34 -0700332 /**
333 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
334 * change at runtime. Use mContext for non-UI purposes.
335 */
336 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700337 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700338 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700341 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700342 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800343 @VisibleForTesting
344 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 PowerManagerInternal mPowerManagerInternal;
346 private UsageStatsManagerInternal mUsageStatsInternal;
347
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700348 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 IntentFirewall mIntentFirewall;
350
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700351 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800352 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800353 /**
354 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
355 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
356 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
357 *
358 * @see WindowManagerThreadPriorityBooster
359 */
360 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700361 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800362 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700363 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700364 private UserManagerService mUserManager;
365 private AppOpsService mAppOpsService;
Michal Karpinski302dcec2019-02-01 11:48:25 +0000366 private DevicePolicyManager mDpm;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700367 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700368 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
369 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700370 /** All processes currently running that might have a window organized by name. */
371 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700372 /** All processes we currently have running mapped by pid */
373 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700374 /** This is the process holding what we currently consider to be the "home" activity. */
375 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700376 /** The currently running heavy-weight process, if any. */
377 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700378 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /**
380 * This is the process holding the activity the user last visited that is in a different process
381 * from the one they are currently in.
382 */
383 WindowProcessController mPreviousProcess;
384 /** The time at which the previous process was last visible. */
385 long mPreviousProcessVisibleTime;
386
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700387 /** List of intents that were used to start the most recent tasks. */
388 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700389 /** State of external calls telling us if the device is awake or asleep. */
390 private boolean mKeyguardShown = false;
391
392 // Wrapper around VoiceInteractionServiceManager
393 private AssistUtils mAssistUtils;
394
395 // VoiceInteraction session ID that changes for each new request except when
396 // being called for multi-window assist in a single session.
397 private int mViSessionId = 1000;
398
399 // How long to wait in getAssistContextExtras for the activity and foreground services
400 // to respond with the result.
401 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
402
403 // How long top wait when going through the modern assist (which doesn't need to block
404 // on getting this result before starting to launch its UI).
405 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
406
407 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
408 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
409
Alison Cichowlas3e340502018-08-07 17:15:01 -0400410 // Permission tokens are used to temporarily granted a trusted app the ability to call
411 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
412 // showing any appropriate error messages to the user.
413 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
414 10 * MINUTE_IN_MILLIS;
415
416 // How long before the service actually expires a token. This is slightly longer than
417 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
418 // expiration exception.
419 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
420 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
421
422 // How long the service will remember expired tokens, for the purpose of providing error
423 // messaging when a client uses an expired token.
424 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
425 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
426
427 // Activity tokens of system activities that are delegating their call to
428 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
429 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
430
431 // Permission tokens that have expired, but we remember for error reporting.
432 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
433
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700434 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
435
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700436 // Keeps track of the active voice interaction service component, notified from
437 // VoiceInteractionManagerService
438 ComponentName mActiveVoiceInteractionServiceComponent;
439
Wale Ogunwalee2172292018-10-25 10:11:10 -0700440 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700441 KeyguardController mKeyguardController;
442 private final ClientLifecycleManager mLifecycleManager;
443 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700444 /** The controller for all operations related to locktask. */
445 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700446 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 boolean mSuppressResizeConfigChanges;
449
450 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
451 new UpdateConfigurationResult();
452
453 static final class UpdateConfigurationResult {
454 // Configuration changes that were updated.
455 int changes;
456 // If the activity was relaunched to match the new configuration.
457 boolean activityRelaunched;
458
459 void reset() {
460 changes = 0;
461 activityRelaunched = false;
462 }
463 }
464
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700465 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700466 private int mConfigurationSeq;
467 // To cache the list of supported system locales
468 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700469
470 /**
471 * Temp object used when global and/or display override configuration is updated. It is also
472 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
473 * anyone...
474 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700475 private Configuration mTempConfig = new Configuration();
476
Wale Ogunwalef6733932018-06-27 05:14:34 -0700477 /** Temporary to avoid allocations. */
478 final StringBuilder mStringBuilder = new StringBuilder(256);
479
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 // Amount of time after a call to stopAppSwitches() during which we will
481 // prevent further untrusted switches from happening.
482 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
483
484 /**
485 * The time at which we will allow normal application switches again,
486 * after a call to {@link #stopAppSwitches()}.
487 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700488 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 /**
490 * This is set to true after the first switch after mAppSwitchesAllowedTime
491 * is set; any switches after that will clear the time.
492 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494
495 IActivityController mController = null;
496 boolean mControllerIsAMonkey = false;
497
Wale Ogunwale214f3482018-10-04 11:00:47 -0700498 final int mFactoryTest;
499
500 /** Used to control how we initialize the service. */
501 ComponentName mTopComponent;
502 String mTopAction = Intent.ACTION_MAIN;
503 String mTopData;
504
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800505 /** Profiling app information. */
506 String mProfileApp = null;
507 WindowProcessController mProfileProc = null;
508 ProfilerInfo mProfilerInfo = null;
509
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700511 * Dump of the activity state at the time of the last ANR. Cleared after
512 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
513 */
514 String mLastANRState;
515
516 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 * Used to retain an update lock when the foreground activity is in
518 * immersive mode.
519 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700520 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521
522 /**
523 * Packages that are being allowed to perform unrestricted app switches. Mapping is
524 * User -> Type -> uid.
525 */
526 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
527
528 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700529 private int mThumbnailWidth;
530 private int mThumbnailHeight;
531 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532
533 /**
534 * Flag that indicates if multi-window is enabled.
535 *
536 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
537 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
538 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
539 * At least one of the forms of multi-window must be enabled in order for this flag to be
540 * initialized to 'true'.
541 *
542 * @see #mSupportsSplitScreenMultiWindow
543 * @see #mSupportsFreeformWindowManagement
544 * @see #mSupportsPictureInPicture
545 * @see #mSupportsMultiDisplay
546 */
547 boolean mSupportsMultiWindow;
548 boolean mSupportsSplitScreenMultiWindow;
549 boolean mSupportsFreeformWindowManagement;
550 boolean mSupportsPictureInPicture;
551 boolean mSupportsMultiDisplay;
552 boolean mForceResizableActivities;
553
554 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
555
556 // VR Vr2d Display Id.
557 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700558
Wale Ogunwalef6733932018-06-27 05:14:34 -0700559 /**
560 * Set while we are wanting to sleep, to prevent any
561 * activities from being started/resumed.
562 *
563 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
564 *
565 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
566 * while in the sleep state until there is a pending transition out of sleep, in which case
567 * mSleeping is set to false, and remains false while awake.
568 *
569 * Whether mSleeping can quickly toggled between true/false without the device actually
570 * display changing states is undefined.
571 */
572 private boolean mSleeping = false;
573
574 /**
575 * The process state used for processes that are running the top activities.
576 * This changes between TOP and TOP_SLEEPING to following mSleeping.
577 */
578 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
579
580 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
581 // automatically. Important for devices without direct input devices.
582 private boolean mShowDialogs = true;
583
584 /** Set if we are shutting down the system, similar to sleeping. */
585 boolean mShuttingDown = false;
586
587 /**
588 * We want to hold a wake lock while running a voice interaction session, since
589 * this may happen with the screen off and we need to keep the CPU running to
590 * be able to continue to interact with the user.
591 */
592 PowerManager.WakeLock mVoiceWakeLock;
593
594 /**
595 * Set while we are running a voice interaction. This overrides sleeping while it is active.
596 */
597 IVoiceInteractionSession mRunningVoice;
598
599 /**
600 * The last resumed activity. This is identical to the current resumed activity most
601 * of the time but could be different when we're pausing one activity before we resume
602 * another activity.
603 */
604 ActivityRecord mLastResumedActivity;
605
606 /**
607 * The activity that is currently being traced as the active resumed activity.
608 *
609 * @see #updateResumedAppTrace
610 */
611 private @Nullable ActivityRecord mTracedResumedActivity;
612
613 /** If non-null, we are tracking the time the user spends in the currently focused app. */
614 AppTimeTracker mCurAppTimeTracker;
615
Wale Ogunwale008163e2018-07-23 23:11:08 -0700616 private AppWarnings mAppWarnings;
617
Wale Ogunwale53783742018-09-16 10:21:51 -0700618 /**
619 * Packages that the user has asked to have run in screen size
620 * compatibility mode instead of filling the screen.
621 */
622 CompatModePackages mCompatModePackages;
623
Wale Ogunwalef6733932018-06-27 05:14:34 -0700624 private FontScaleSettingObserver mFontScaleSettingObserver;
625
626 private final class FontScaleSettingObserver extends ContentObserver {
627 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
628 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
629
630 public FontScaleSettingObserver() {
631 super(mH);
632 final ContentResolver resolver = mContext.getContentResolver();
633 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
634 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
635 UserHandle.USER_ALL);
636 }
637
638 @Override
639 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
640 if (mFontScaleUri.equals(uri)) {
641 updateFontScaleIfNeeded(userId);
642 } else if (mHideErrorDialogsUri.equals(uri)) {
643 synchronized (mGlobalLock) {
644 updateShouldShowDialogsLocked(getGlobalConfiguration());
645 }
646 }
647 }
648 }
649
Charles Chen8d98dd22018-12-26 17:36:54 +0800650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
651 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700652 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700653 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700654 mSystemThread = ActivityThread.currentActivityThread();
655 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800657 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700658 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700659 }
660
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 public void onSystemReady() {
662 synchronized (mGlobalLock) {
663 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
664 PackageManager.FEATURE_CANT_SAVE_STATE);
665 mAssistUtils = new AssistUtils(mContext);
666 mVrController.onSystemReady();
667 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700668 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700669 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void onInitPowerManagement() {
673 synchronized (mGlobalLock) {
674 mStackSupervisor.initPowerManagement();
675 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
676 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
677 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
678 mVoiceWakeLock.setReferenceCounted(false);
679 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700680 }
681
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700682 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700683 mFontScaleSettingObserver = new FontScaleSettingObserver();
684 }
685
Wale Ogunwale59507092018-10-29 09:00:30 -0700686 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean freeformWindowManagement =
688 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
689 || Settings.Global.getInt(
690 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
691
692 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
693 final boolean supportsPictureInPicture = supportsMultiWindow &&
694 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
695 final boolean supportsSplitScreenMultiWindow =
696 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
697 final boolean supportsMultiDisplay = mContext.getPackageManager()
698 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700699 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
700 final boolean forceResizable = Settings.Global.getInt(
701 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700702 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700703
704 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900705 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706
707 final Configuration configuration = new Configuration();
708 Settings.System.getConfiguration(resolver, configuration);
709 if (forceRtl) {
710 // This will take care of setting the correct layout direction flags
711 configuration.setLayoutDirection(configuration.locale);
712 }
713
714 synchronized (mGlobalLock) {
715 mForceResizableActivities = forceResizable;
716 final boolean multiWindowFormEnabled = freeformWindowManagement
717 || supportsSplitScreenMultiWindow
718 || supportsPictureInPicture
719 || supportsMultiDisplay;
720 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
721 mSupportsMultiWindow = true;
722 mSupportsFreeformWindowManagement = freeformWindowManagement;
723 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
724 mSupportsPictureInPicture = supportsPictureInPicture;
725 mSupportsMultiDisplay = supportsMultiDisplay;
726 } else {
727 mSupportsMultiWindow = false;
728 mSupportsFreeformWindowManagement = false;
729 mSupportsSplitScreenMultiWindow = false;
730 mSupportsPictureInPicture = false;
731 mSupportsMultiDisplay = false;
732 }
733 mWindowManager.setForceResizableTasks(mForceResizableActivities);
734 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700735 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
736 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737 // This happens before any activities are started, so we can change global configuration
738 // in-place.
739 updateConfigurationLocked(configuration, null, true);
740 final Configuration globalConfig = getGlobalConfiguration();
741 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
742
743 // Load resources only after the current configuration has been set.
744 final Resources res = mContext.getResources();
745 mThumbnailWidth = res.getDimensionPixelSize(
746 com.android.internal.R.dimen.thumbnail_width);
747 mThumbnailHeight = res.getDimensionPixelSize(
748 com.android.internal.R.dimen.thumbnail_height);
749
750 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
751 mFullscreenThumbnailScale = (float) res
752 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
753 (float) globalConfig.screenWidthDp;
754 } else {
755 mFullscreenThumbnailScale = res.getFraction(
756 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
757 }
758 }
759 }
760
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800761 public WindowManagerGlobalLock getGlobalLock() {
762 return mGlobalLock;
763 }
764
Riddle Hsud93a6c42018-11-29 21:50:06 +0800765 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
766 Looper looper) {
767 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700769 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700770 final File systemDir = SystemServiceManager.ensureSystemDir();
771 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
772 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700773 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774
775 mTempConfig.setToDefaults();
776 mTempConfig.setLocales(LocaleList.getDefault());
777 mConfigurationSeq = mTempConfig.seq = 1;
778 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800779 mRootActivityContainer = new RootActivityContainer(this);
780 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700781
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700782 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700784 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700785 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700786 mRecentTasks = createRecentTasks();
787 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700788 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700789 mKeyguardController = mStackSupervisor.getKeyguardController();
790 }
791
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700792 public void onActivityManagerInternalAdded() {
793 synchronized (mGlobalLock) {
794 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
795 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
796 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700797 }
798
Yunfan Chen75157d72018-07-27 14:47:21 +0900799 int increaseConfigurationSeqLocked() {
800 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
801 return mConfigurationSeq;
802 }
803
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804 protected ActivityStackSupervisor createStackSupervisor() {
805 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
806 supervisor.initialize();
807 return supervisor;
808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setWindowManager(WindowManagerService wm) {
811 synchronized (mGlobalLock) {
812 mWindowManager = wm;
813 mLockTaskController.setWindowManager(wm);
814 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700816 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700817 }
818
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700819 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
820 synchronized (mGlobalLock) {
821 mUsageStatsInternal = usageStatsManager;
822 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 }
824
Wale Ogunwalef6733932018-06-27 05:14:34 -0700825 UserManagerService getUserManager() {
826 if (mUserManager == null) {
827 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
828 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
829 }
830 return mUserManager;
831 }
832
833 AppOpsService getAppOpsService() {
834 if (mAppOpsService == null) {
835 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
836 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
837 }
838 return mAppOpsService;
839 }
840
Michal Karpinski302dcec2019-02-01 11:48:25 +0000841 DevicePolicyManager getDevicePolicyManager() {
842 if (mDpm == null) {
843 mDpm = mContext.getSystemService(DevicePolicyManager.class);
844 }
845 return mDpm;
846 }
847
Wale Ogunwalef6733932018-06-27 05:14:34 -0700848 boolean hasUserRestriction(String restriction, int userId) {
849 return getUserManager().hasUserRestriction(restriction, userId);
850 }
851
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700852 protected RecentTasks createRecentTasks() {
853 return new RecentTasks(this, mStackSupervisor);
854 }
855
856 RecentTasks getRecentTasks() {
857 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700858 }
859
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700860 ClientLifecycleManager getLifecycleManager() {
861 return mLifecycleManager;
862 }
863
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700864 ActivityStartController getActivityStartController() {
865 return mActivityStartController;
866 }
867
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700868 TaskChangeNotificationController getTaskChangeNotificationController() {
869 return mTaskChangeNotificationController;
870 }
871
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700872 LockTaskController getLockTaskController() {
873 return mLockTaskController;
874 }
875
Yunfan Chen75157d72018-07-27 14:47:21 +0900876 /**
877 * Return the global configuration used by the process corresponding to the input pid. This is
878 * usually the global configuration with some overrides specific to that process.
879 */
880 Configuration getGlobalConfigurationForCallingPid() {
881 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800882 return getGlobalConfigurationForPid(pid);
883 }
884
885 /**
886 * Return the global configuration used by the process corresponding to the given pid.
887 */
888 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900889 if (pid == MY_PID || pid < 0) {
890 return getGlobalConfiguration();
891 }
892 synchronized (mGlobalLock) {
893 final WindowProcessController app = mPidMap.get(pid);
894 return app != null ? app.getConfiguration() : getGlobalConfiguration();
895 }
896 }
897
898 /**
899 * Return the device configuration info used by the process corresponding to the input pid.
900 * The value is consistent with the global configuration for the process.
901 */
902 @Override
903 public ConfigurationInfo getDeviceConfigurationInfo() {
904 ConfigurationInfo config = new ConfigurationInfo();
905 synchronized (mGlobalLock) {
906 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
907 config.reqTouchScreen = globalConfig.touchscreen;
908 config.reqKeyboardType = globalConfig.keyboard;
909 config.reqNavigation = globalConfig.navigation;
910 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
911 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
912 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
913 }
914 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
915 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
916 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
917 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700918 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900919 }
920 return config;
921 }
922
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700923 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700924 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700925 }
926
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700927 public static final class Lifecycle extends SystemService {
928 private final ActivityTaskManagerService mService;
929
930 public Lifecycle(Context context) {
931 super(context);
932 mService = new ActivityTaskManagerService(context);
933 }
934
935 @Override
936 public void onStart() {
937 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700938 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700939 }
940
Garfield Tan891146c2018-10-09 12:14:00 -0700941 @Override
942 public void onUnlockUser(int userId) {
943 synchronized (mService.getGlobalLock()) {
944 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
945 }
946 }
947
948 @Override
949 public void onCleanupUser(int userId) {
950 synchronized (mService.getGlobalLock()) {
951 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
952 }
953 }
954
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700955 public ActivityTaskManagerService getService() {
956 return mService;
957 }
958 }
959
960 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700961 public final int startActivity(IApplicationThread caller, String callingPackage,
962 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
963 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
964 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
965 resultWho, requestCode, startFlags, profilerInfo, bOptions,
966 UserHandle.getCallingUserId());
967 }
968
969 @Override
970 public final int startActivities(IApplicationThread caller, String callingPackage,
971 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
972 int userId) {
973 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700974 enforceNotIsolatedCaller(reason);
975 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700976 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000977 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
978 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
979 reason, null /* originatingPendingIntent */,
980 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700981 }
982
983 @Override
984 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
985 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
986 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
987 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
988 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
989 true /*validateIncomingUser*/);
990 }
991
992 int startActivityAsUser(IApplicationThread caller, String callingPackage,
993 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
994 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
995 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700996 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700998 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700999 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1000
1001 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001002 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001003 .setCaller(caller)
1004 .setCallingPackage(callingPackage)
1005 .setResolvedType(resolvedType)
1006 .setResultTo(resultTo)
1007 .setResultWho(resultWho)
1008 .setRequestCode(requestCode)
1009 .setStartFlags(startFlags)
1010 .setProfilerInfo(profilerInfo)
1011 .setActivityOptions(bOptions)
1012 .setMayWait(userId)
1013 .execute();
1014
1015 }
1016
1017 @Override
1018 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1019 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001020 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1021 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 // Refuse possible leaked file descriptors
1023 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1024 throw new IllegalArgumentException("File descriptors passed in Intent");
1025 }
1026
1027 if (!(target instanceof PendingIntentRecord)) {
1028 throw new IllegalArgumentException("Bad PendingIntent object");
1029 }
1030
1031 PendingIntentRecord pir = (PendingIntentRecord)target;
1032
1033 synchronized (mGlobalLock) {
1034 // If this is coming from the currently resumed activity, it is
1035 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001036 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 if (stack.mResumedActivity != null &&
1038 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001039 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 }
1041 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001042 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 }
1045
1046 @Override
1047 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1048 Bundle bOptions) {
1049 // Refuse possible leaked file descriptors
1050 if (intent != null && intent.hasFileDescriptors()) {
1051 throw new IllegalArgumentException("File descriptors passed in Intent");
1052 }
1053 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1054
1055 synchronized (mGlobalLock) {
1056 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1057 if (r == null) {
1058 SafeActivityOptions.abort(options);
1059 return false;
1060 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001061 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 // The caller is not running... d'oh!
1063 SafeActivityOptions.abort(options);
1064 return false;
1065 }
1066 intent = new Intent(intent);
1067 // The caller is not allowed to change the data.
1068 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1069 // And we are resetting to find the next component...
1070 intent.setComponent(null);
1071
1072 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1073
1074 ActivityInfo aInfo = null;
1075 try {
1076 List<ResolveInfo> resolves =
1077 AppGlobals.getPackageManager().queryIntentActivities(
1078 intent, r.resolvedType,
1079 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1080 UserHandle.getCallingUserId()).getList();
1081
1082 // Look for the original activity in the list...
1083 final int N = resolves != null ? resolves.size() : 0;
1084 for (int i=0; i<N; i++) {
1085 ResolveInfo rInfo = resolves.get(i);
1086 if (rInfo.activityInfo.packageName.equals(r.packageName)
1087 && rInfo.activityInfo.name.equals(r.info.name)) {
1088 // We found the current one... the next matching is
1089 // after it.
1090 i++;
1091 if (i<N) {
1092 aInfo = resolves.get(i).activityInfo;
1093 }
1094 if (debug) {
1095 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1096 + "/" + r.info.name);
1097 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1098 ? "null" : aInfo.packageName + "/" + aInfo.name));
1099 }
1100 break;
1101 }
1102 }
1103 } catch (RemoteException e) {
1104 }
1105
1106 if (aInfo == null) {
1107 // Nobody who is next!
1108 SafeActivityOptions.abort(options);
1109 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1110 return false;
1111 }
1112
1113 intent.setComponent(new ComponentName(
1114 aInfo.applicationInfo.packageName, aInfo.name));
1115 intent.setFlags(intent.getFlags()&~(
1116 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1117 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1118 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1119 FLAG_ACTIVITY_NEW_TASK));
1120
1121 // Okay now we need to start the new activity, replacing the currently running activity.
1122 // This is a little tricky because we want to start the new one as if the current one is
1123 // finished, but not finish the current one first so that there is no flicker.
1124 // And thus...
1125 final boolean wasFinishing = r.finishing;
1126 r.finishing = true;
1127
1128 // Propagate reply information over to the new activity.
1129 final ActivityRecord resultTo = r.resultTo;
1130 final String resultWho = r.resultWho;
1131 final int requestCode = r.requestCode;
1132 r.resultTo = null;
1133 if (resultTo != null) {
1134 resultTo.removeResultsLocked(r, resultWho, requestCode);
1135 }
1136
1137 final long origId = Binder.clearCallingIdentity();
1138 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001139 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001140 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001141 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001142 .setResolvedType(r.resolvedType)
1143 .setActivityInfo(aInfo)
1144 .setResultTo(resultTo != null ? resultTo.appToken : null)
1145 .setResultWho(resultWho)
1146 .setRequestCode(requestCode)
1147 .setCallingPid(-1)
1148 .setCallingUid(r.launchedFromUid)
1149 .setCallingPackage(r.launchedFromPackage)
1150 .setRealCallingPid(-1)
1151 .setRealCallingUid(r.launchedFromUid)
1152 .setActivityOptions(options)
1153 .execute();
1154 Binder.restoreCallingIdentity(origId);
1155
1156 r.finishing = wasFinishing;
1157 if (res != ActivityManager.START_SUCCESS) {
1158 return false;
1159 }
1160 return true;
1161 }
1162 }
1163
1164 @Override
1165 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1166 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1167 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1168 final WaitResult res = new WaitResult();
1169 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001170 enforceNotIsolatedCaller("startActivityAndWait");
1171 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1172 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001173 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001174 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 .setCaller(caller)
1176 .setCallingPackage(callingPackage)
1177 .setResolvedType(resolvedType)
1178 .setResultTo(resultTo)
1179 .setResultWho(resultWho)
1180 .setRequestCode(requestCode)
1181 .setStartFlags(startFlags)
1182 .setActivityOptions(bOptions)
1183 .setMayWait(userId)
1184 .setProfilerInfo(profilerInfo)
1185 .setWaitResult(res)
1186 .execute();
1187 }
1188 return res;
1189 }
1190
1191 @Override
1192 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1193 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1194 int startFlags, Configuration config, Bundle bOptions, int userId) {
1195 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001196 enforceNotIsolatedCaller("startActivityWithConfig");
1197 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1198 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001199 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001200 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001201 .setCaller(caller)
1202 .setCallingPackage(callingPackage)
1203 .setResolvedType(resolvedType)
1204 .setResultTo(resultTo)
1205 .setResultWho(resultWho)
1206 .setRequestCode(requestCode)
1207 .setStartFlags(startFlags)
1208 .setGlobalConfiguration(config)
1209 .setActivityOptions(bOptions)
1210 .setMayWait(userId)
1211 .execute();
1212 }
1213 }
1214
Alison Cichowlas3e340502018-08-07 17:15:01 -04001215
1216 @Override
1217 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1218 int callingUid = Binder.getCallingUid();
1219 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1220 throw new SecurityException("Only the system process can request a permission token, "
1221 + "received request from uid: " + callingUid);
1222 }
1223 IBinder permissionToken = new Binder();
1224 synchronized (mGlobalLock) {
1225 mStartActivitySources.put(permissionToken, delegatorToken);
1226 }
1227
1228 Message expireMsg = PooledLambda.obtainMessage(
1229 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1230 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1231
1232 Message forgetMsg = PooledLambda.obtainMessage(
1233 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1234 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1235
1236 return permissionToken;
1237 }
1238
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 @Override
1240 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1241 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001242 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1243 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001245 // permission grants) as any app that may launch one of your own activities. So we only
1246 // allow this in two cases:
1247 // 1) The caller is an activity that is part of the core framework, and then only when it
1248 // is running as the system.
1249 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1250 // can only be requested by a system activity, which may then delegate this call to
1251 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001252 final ActivityRecord sourceRecord;
1253 final int targetUid;
1254 final String targetPackage;
1255 final boolean isResolver;
1256 synchronized (mGlobalLock) {
1257 if (resultTo == null) {
1258 throw new SecurityException("Must be called from an activity");
1259 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260 final IBinder sourceToken;
1261 if (permissionToken != null) {
1262 // To even attempt to use a permissionToken, an app must also have this signature
1263 // permission.
1264 mAmInternal.enforceCallingPermission(
1265 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1266 "startActivityAsCaller");
1267 // If called with a permissionToken, we want the sourceRecord from the delegator
1268 // activity that requested this token.
1269 sourceToken = mStartActivitySources.remove(permissionToken);
1270 if (sourceToken == null) {
1271 // Invalid permissionToken, check if it recently expired.
1272 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1273 throw new SecurityException("Called with expired permission token: "
1274 + permissionToken);
1275 } else {
1276 throw new SecurityException("Called with invalid permission token: "
1277 + permissionToken);
1278 }
1279 }
1280 } else {
1281 // This method was called directly by the source.
1282 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001283 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001284
Wale Ogunwaled32da472018-11-16 07:19:28 -08001285 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001286 if (sourceRecord == null) {
1287 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 }
1289 if (sourceRecord.app == null) {
1290 throw new SecurityException("Called without a process attached to activity");
1291 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001292
1293 // Whether called directly or from a delegate, the source activity must be from the
1294 // android package.
1295 if (!sourceRecord.info.packageName.equals("android")) {
1296 throw new SecurityException("Must be called from an activity that is "
1297 + "declared in the android package");
1298 }
1299
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001300 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 // This is still okay, as long as this activity is running under the
1302 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001303 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001305 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 + " must be system uid or original calling uid "
1307 + sourceRecord.launchedFromUid);
1308 }
1309 }
1310 if (ignoreTargetSecurity) {
1311 if (intent.getComponent() == null) {
1312 throw new SecurityException(
1313 "Component must be specified with ignoreTargetSecurity");
1314 }
1315 if (intent.getSelector() != null) {
1316 throw new SecurityException(
1317 "Selector not allowed with ignoreTargetSecurity");
1318 }
1319 }
1320 targetUid = sourceRecord.launchedFromUid;
1321 targetPackage = sourceRecord.launchedFromPackage;
1322 isResolver = sourceRecord.isResolverOrChildActivity();
1323 }
1324
1325 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001326 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 }
1328
1329 // TODO: Switch to user app stacks here.
1330 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001331 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001332 .setCallingUid(targetUid)
1333 .setCallingPackage(targetPackage)
1334 .setResolvedType(resolvedType)
1335 .setResultTo(resultTo)
1336 .setResultWho(resultWho)
1337 .setRequestCode(requestCode)
1338 .setStartFlags(startFlags)
1339 .setActivityOptions(bOptions)
1340 .setMayWait(userId)
1341 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1342 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1343 .execute();
1344 } catch (SecurityException e) {
1345 // XXX need to figure out how to propagate to original app.
1346 // A SecurityException here is generally actually a fault of the original
1347 // calling activity (such as a fairly granting permissions), so propagate it
1348 // back to them.
1349 /*
1350 StringBuilder msg = new StringBuilder();
1351 msg.append("While launching");
1352 msg.append(intent.toString());
1353 msg.append(": ");
1354 msg.append(e.getMessage());
1355 */
1356 throw e;
1357 }
1358 }
1359
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001360 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1361 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1362 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1363 }
1364
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 @Override
1366 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1367 Intent intent, String resolvedType, IVoiceInteractionSession session,
1368 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1369 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001370 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 if (session == null || interactor == null) {
1372 throw new NullPointerException("null session or interactor");
1373 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001374 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001376 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 .setCallingUid(callingUid)
1378 .setCallingPackage(callingPackage)
1379 .setResolvedType(resolvedType)
1380 .setVoiceSession(session)
1381 .setVoiceInteractor(interactor)
1382 .setStartFlags(startFlags)
1383 .setProfilerInfo(profilerInfo)
1384 .setActivityOptions(bOptions)
1385 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001386 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 .execute();
1388 }
1389
1390 @Override
1391 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1392 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001393 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1394 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001396 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 .setCallingUid(callingUid)
1398 .setCallingPackage(callingPackage)
1399 .setResolvedType(resolvedType)
1400 .setActivityOptions(bOptions)
1401 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001402 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 .execute();
1404 }
1405
1406 @Override
1407 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1408 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 final int callingPid = Binder.getCallingPid();
1411 final long origId = Binder.clearCallingIdentity();
1412 try {
1413 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001414 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1415 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416
1417 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1419 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1421 recentsUid, assistDataReceiver);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(origId);
1425 }
1426 }
1427
1428 @Override
1429 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 "startActivityFromRecents()");
1432
1433 final int callingPid = Binder.getCallingPid();
1434 final int callingUid = Binder.getCallingUid();
1435 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1436 final long origId = Binder.clearCallingIdentity();
1437 try {
1438 synchronized (mGlobalLock) {
1439 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1440 safeOptions);
1441 }
1442 } finally {
1443 Binder.restoreCallingIdentity(origId);
1444 }
1445 }
1446
1447 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001448 * Public API to check if the client is allowed to start an activity on specified display.
1449 *
1450 * If the target display is private or virtual, some restrictions will apply.
1451 *
1452 * @param displayId Target display id.
1453 * @param intent Intent used to launch the activity.
1454 * @param resolvedType The MIME type of the intent.
1455 * @param userId The id of the user for whom the call is made.
1456 * @return {@code true} if a call to start an activity on the target display should succeed and
1457 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1458 */
1459 @Override
1460 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1461 String resolvedType, int userId) {
1462 final int callingUid = Binder.getCallingUid();
1463 final int callingPid = Binder.getCallingPid();
1464 final long origId = Binder.clearCallingIdentity();
1465
1466 try {
1467 // Collect information about the target of the Intent.
1468 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1469 0 /* startFlags */, null /* profilerInfo */, userId,
1470 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1471 UserHandle.USER_NULL));
1472 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1473
1474 synchronized (mGlobalLock) {
1475 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1476 aInfo);
1477 }
1478 } finally {
1479 Binder.restoreCallingIdentity(origId);
1480 }
1481 }
1482
1483 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 * This is the internal entry point for handling Activity.finish().
1485 *
1486 * @param token The Binder token referencing the Activity we want to finish.
1487 * @param resultCode Result code, if any, from this Activity.
1488 * @param resultData Result data (Intent), if any, from this Activity.
1489 * @param finishTask Whether to finish the task associated with this Activity.
1490 *
1491 * @return Returns true if the activity successfully finished, or false if it is still running.
1492 */
1493 @Override
1494 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1495 int finishTask) {
1496 // Refuse possible leaked file descriptors
1497 if (resultData != null && resultData.hasFileDescriptors()) {
1498 throw new IllegalArgumentException("File descriptors passed in Intent");
1499 }
1500
1501 synchronized (mGlobalLock) {
1502 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1503 if (r == null) {
1504 return true;
1505 }
1506 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001507 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 ActivityRecord rootR = tr.getRootActivity();
1509 if (rootR == null) {
1510 Slog.w(TAG, "Finishing task with all activities already finished");
1511 }
1512 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1513 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001514 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001515 return false;
1516 }
1517
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001518 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1519 // We should consolidate.
1520 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001522 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 if (next != null) {
1524 // ask watcher if this is allowed
1525 boolean resumeOK = true;
1526 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001527 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001529 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530 Watchdog.getInstance().setActivityController(null);
1531 }
1532
1533 if (!resumeOK) {
1534 Slog.i(TAG, "Not finishing activity because controller resumed");
1535 return false;
1536 }
1537 }
1538 }
1539 final long origId = Binder.clearCallingIdentity();
1540 try {
1541 boolean res;
1542 final boolean finishWithRootActivity =
1543 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1544 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1545 || (finishWithRootActivity && r == rootR)) {
1546 // If requested, remove the task that is associated to this activity only if it
1547 // was the root activity in the task. The result code and data is ignored
1548 // because we don't support returning them across task boundaries. Also, to
1549 // keep backwards compatibility we remove the task from recents when finishing
1550 // task with root activity.
1551 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1552 finishWithRootActivity, "finish-activity");
1553 if (!res) {
1554 Slog.i(TAG, "Removing task failed to finish activity");
1555 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001556 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001557 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 } else {
1559 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1560 resultData, "app-request", true);
1561 if (!res) {
1562 Slog.i(TAG, "Failed to finish by app-request");
1563 }
1564 }
1565 return res;
1566 } finally {
1567 Binder.restoreCallingIdentity(origId);
1568 }
1569 }
1570 }
1571
1572 @Override
1573 public boolean finishActivityAffinity(IBinder token) {
1574 synchronized (mGlobalLock) {
1575 final long origId = Binder.clearCallingIdentity();
1576 try {
1577 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1578 if (r == null) {
1579 return false;
1580 }
1581
1582 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1583 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001584 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001585 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 return false;
1587 }
1588 return task.getStack().finishActivityAffinityLocked(r);
1589 } finally {
1590 Binder.restoreCallingIdentity(origId);
1591 }
1592 }
1593 }
1594
1595 @Override
1596 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1597 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001598 try {
1599 WindowProcessController proc = null;
1600 synchronized (mGlobalLock) {
1601 ActivityStack stack = ActivityRecord.getStackLocked(token);
1602 if (stack == null) {
1603 return;
1604 }
1605 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1606 false /* fromTimeout */, false /* processPausingActivities */, config);
1607 if (r != null) {
1608 proc = r.app;
1609 }
1610 if (stopProfiling && proc != null) {
1611 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001612 }
1613 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001614 } finally {
1615 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 }
1618
1619 @Override
1620 public final void activityResumed(IBinder token) {
1621 final long origId = Binder.clearCallingIdentity();
1622 synchronized (mGlobalLock) {
1623 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001624 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 }
1626 Binder.restoreCallingIdentity(origId);
1627 }
1628
1629 @Override
1630 public final void activityPaused(IBinder token) {
1631 final long origId = Binder.clearCallingIdentity();
1632 synchronized (mGlobalLock) {
1633 ActivityStack stack = ActivityRecord.getStackLocked(token);
1634 if (stack != null) {
1635 stack.activityPausedLocked(token, false);
1636 }
1637 }
1638 Binder.restoreCallingIdentity(origId);
1639 }
1640
1641 @Override
1642 public final void activityStopped(IBinder token, Bundle icicle,
1643 PersistableBundle persistentState, CharSequence description) {
1644 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1645
1646 // Refuse possible leaked file descriptors
1647 if (icicle != null && icicle.hasFileDescriptors()) {
1648 throw new IllegalArgumentException("File descriptors passed in Bundle");
1649 }
1650
1651 final long origId = Binder.clearCallingIdentity();
1652
1653 synchronized (mGlobalLock) {
1654 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r != null) {
1656 r.activityStoppedLocked(icicle, persistentState, description);
1657 }
1658 }
1659
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001660 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661
1662 Binder.restoreCallingIdentity(origId);
1663 }
1664
1665 @Override
1666 public final void activityDestroyed(IBinder token) {
1667 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1668 synchronized (mGlobalLock) {
1669 ActivityStack stack = ActivityRecord.getStackLocked(token);
1670 if (stack != null) {
1671 stack.activityDestroyedLocked(token, "activityDestroyed");
1672 }
1673 }
1674 }
1675
1676 @Override
1677 public final void activityRelaunched(IBinder token) {
1678 final long origId = Binder.clearCallingIdentity();
1679 synchronized (mGlobalLock) {
1680 mStackSupervisor.activityRelaunchedLocked(token);
1681 }
1682 Binder.restoreCallingIdentity(origId);
1683 }
1684
1685 public final void activitySlept(IBinder token) {
1686 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1687
1688 final long origId = Binder.clearCallingIdentity();
1689
1690 synchronized (mGlobalLock) {
1691 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1692 if (r != null) {
1693 mStackSupervisor.activitySleptLocked(r);
1694 }
1695 }
1696
1697 Binder.restoreCallingIdentity(origId);
1698 }
1699
1700 @Override
1701 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1702 synchronized (mGlobalLock) {
1703 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1704 if (r == null) {
1705 return;
1706 }
1707 final long origId = Binder.clearCallingIdentity();
1708 try {
1709 r.setRequestedOrientation(requestedOrientation);
1710 } finally {
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713 }
1714 }
1715
1716 @Override
1717 public int getRequestedOrientation(IBinder token) {
1718 synchronized (mGlobalLock) {
1719 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1720 if (r == null) {
1721 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1722 }
1723 return r.getRequestedOrientation();
1724 }
1725 }
1726
1727 @Override
1728 public void setImmersive(IBinder token, boolean immersive) {
1729 synchronized (mGlobalLock) {
1730 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1731 if (r == null) {
1732 throw new IllegalArgumentException();
1733 }
1734 r.immersive = immersive;
1735
1736 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001737 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001739 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 }
1741 }
1742 }
1743
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001744 void applyUpdateLockStateLocked(ActivityRecord r) {
1745 // Modifications to the UpdateLock state are done on our handler, outside
1746 // the activity manager's locks. The new state is determined based on the
1747 // state *now* of the relevant activity record. The object is passed to
1748 // the handler solely for logging detail, not to be consulted/modified.
1749 final boolean nextState = r != null && r.immersive;
1750 mH.post(() -> {
1751 if (mUpdateLock.isHeld() != nextState) {
1752 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1753 "Applying new update lock state '" + nextState + "' for " + r);
1754 if (nextState) {
1755 mUpdateLock.acquire();
1756 } else {
1757 mUpdateLock.release();
1758 }
1759 }
1760 });
1761 }
1762
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 @Override
1764 public boolean isImmersive(IBinder token) {
1765 synchronized (mGlobalLock) {
1766 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1767 if (r == null) {
1768 throw new IllegalArgumentException();
1769 }
1770 return r.immersive;
1771 }
1772 }
1773
1774 @Override
1775 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001776 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001778 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 return (r != null) ? r.immersive : false;
1780 }
1781 }
1782
1783 @Override
1784 public void overridePendingTransition(IBinder token, String packageName,
1785 int enterAnim, int exitAnim) {
1786 synchronized (mGlobalLock) {
1787 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1788 if (self == null) {
1789 return;
1790 }
1791
1792 final long origId = Binder.clearCallingIdentity();
1793
1794 if (self.isState(
1795 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001796 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001797 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001798 }
1799
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802 }
1803
1804 @Override
1805 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001806 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001808 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001809 if (r == null) {
1810 return ActivityManager.COMPAT_MODE_UNKNOWN;
1811 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001812 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 }
1814 }
1815
1816 @Override
1817 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001818 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001820 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001822 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001823 if (r == null) {
1824 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1825 return;
1826 }
1827 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001828 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001829 }
1830 }
1831
1832 @Override
1833 public int getLaunchedFromUid(IBinder activityToken) {
1834 ActivityRecord srec;
1835 synchronized (mGlobalLock) {
1836 srec = ActivityRecord.forTokenLocked(activityToken);
1837 }
1838 if (srec == null) {
1839 return -1;
1840 }
1841 return srec.launchedFromUid;
1842 }
1843
1844 @Override
1845 public String getLaunchedFromPackage(IBinder activityToken) {
1846 ActivityRecord srec;
1847 synchronized (mGlobalLock) {
1848 srec = ActivityRecord.forTokenLocked(activityToken);
1849 }
1850 if (srec == null) {
1851 return null;
1852 }
1853 return srec.launchedFromPackage;
1854 }
1855
1856 @Override
1857 public boolean convertFromTranslucent(IBinder token) {
1858 final long origId = Binder.clearCallingIdentity();
1859 try {
1860 synchronized (mGlobalLock) {
1861 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1862 if (r == null) {
1863 return false;
1864 }
1865 final boolean translucentChanged = r.changeWindowTranslucency(true);
1866 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001867 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 return translucentChanged;
1871 }
1872 } finally {
1873 Binder.restoreCallingIdentity(origId);
1874 }
1875 }
1876
1877 @Override
1878 public boolean convertToTranslucent(IBinder token, Bundle options) {
1879 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1880 final long origId = Binder.clearCallingIdentity();
1881 try {
1882 synchronized (mGlobalLock) {
1883 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1884 if (r == null) {
1885 return false;
1886 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001887 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 int index = task.mActivities.lastIndexOf(r);
1889 if (index > 0) {
1890 ActivityRecord under = task.mActivities.get(index - 1);
1891 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1892 }
1893 final boolean translucentChanged = r.changeWindowTranslucency(false);
1894 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001895 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001897 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 return translucentChanged;
1900 }
1901 } finally {
1902 Binder.restoreCallingIdentity(origId);
1903 }
1904 }
1905
1906 @Override
1907 public void notifyActivityDrawn(IBinder token) {
1908 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1909 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001910 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001912 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914 }
1915 }
1916
1917 @Override
1918 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1919 synchronized (mGlobalLock) {
1920 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1921 if (r == null) {
1922 return;
1923 }
1924 r.reportFullyDrawnLocked(restoredFromBundle);
1925 }
1926 }
1927
1928 @Override
1929 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1930 synchronized (mGlobalLock) {
1931 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1932 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1933 return stack.mDisplayId;
1934 }
1935 return DEFAULT_DISPLAY;
1936 }
1937 }
1938
1939 @Override
1940 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001941 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 long ident = Binder.clearCallingIdentity();
1943 try {
1944 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001945 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001947 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 }
1949 return null;
1950 }
1951 } finally {
1952 Binder.restoreCallingIdentity(ident);
1953 }
1954 }
1955
1956 @Override
1957 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001958 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1960 final long callingId = Binder.clearCallingIdentity();
1961 try {
1962 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 if (stack == null) {
1965 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1966 return;
1967 }
1968 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001969 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001970 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 }
1972 }
1973 } finally {
1974 Binder.restoreCallingIdentity(callingId);
1975 }
1976 }
1977
1978 @Override
1979 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001980 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1982 final long callingId = Binder.clearCallingIdentity();
1983 try {
1984 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001985 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001986 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001987 if (task == null) {
1988 return;
1989 }
1990 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001991 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001992 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 }
1994 }
1995 } finally {
1996 Binder.restoreCallingIdentity(callingId);
1997 }
1998 }
1999
2000 @Override
2001 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002002 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 synchronized (mGlobalLock) {
2004 final long ident = Binder.clearCallingIdentity();
2005 try {
2006 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2007 "remove-task");
2008 } finally {
2009 Binder.restoreCallingIdentity(ident);
2010 }
2011 }
2012 }
2013
2014 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002015 public void removeAllVisibleRecentTasks() {
2016 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2017 synchronized (mGlobalLock) {
2018 final long ident = Binder.clearCallingIdentity();
2019 try {
2020 getRecentTasks().removeAllVisibleTasks();
2021 } finally {
2022 Binder.restoreCallingIdentity(ident);
2023 }
2024 }
2025 }
2026
2027 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2029 synchronized (mGlobalLock) {
2030 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2031 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002032 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 }
2034 }
2035 return false;
2036 }
2037
2038 @Override
2039 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2040 Intent resultData) {
2041
2042 synchronized (mGlobalLock) {
2043 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2044 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002045 return r.getActivityStack().navigateUpToLocked(
2046 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 }
2048 return false;
2049 }
2050 }
2051
2052 /**
2053 * Attempts to move a task backwards in z-order (the order of activities within the task is
2054 * unchanged).
2055 *
2056 * There are several possible results of this call:
2057 * - if the task is locked, then we will show the lock toast
2058 * - if there is a task behind the provided task, then that task is made visible and resumed as
2059 * this task is moved to the back
2060 * - otherwise, if there are no other tasks in the stack:
2061 * - if this task is in the pinned stack, then we remove the stack completely, which will
2062 * have the effect of moving the task to the top or bottom of the fullscreen stack
2063 * (depending on whether it is visible)
2064 * - otherwise, we simply return home and hide this task
2065 *
2066 * @param token A reference to the activity we wish to move
2067 * @param nonRoot If false then this only works if the activity is the root
2068 * of a task; if true it will work for any activity in a task.
2069 * @return Returns true if the move completed, false if not.
2070 */
2071 @Override
2072 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002073 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 synchronized (mGlobalLock) {
2075 final long origId = Binder.clearCallingIdentity();
2076 try {
2077 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002078 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (task != null) {
2080 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(origId);
2084 }
2085 }
2086 return false;
2087 }
2088
2089 @Override
2090 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002091 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 long ident = Binder.clearCallingIdentity();
2093 Rect rect = new Rect();
2094 try {
2095 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002096 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2098 if (task == null) {
2099 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2100 return rect;
2101 }
2102 if (task.getStack() != null) {
2103 // Return the bounds from window manager since it will be adjusted for various
2104 // things like the presense of a docked stack for tasks that aren't resizeable.
2105 task.getWindowContainerBounds(rect);
2106 } else {
2107 // Task isn't in window manager yet since it isn't associated with a stack.
2108 // Return the persist value from activity manager
2109 if (!task.matchParentBounds()) {
2110 rect.set(task.getBounds());
2111 } else if (task.mLastNonFullscreenBounds != null) {
2112 rect.set(task.mLastNonFullscreenBounds);
2113 }
2114 }
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(ident);
2118 }
2119 return rect;
2120 }
2121
2122 @Override
2123 public ActivityManager.TaskDescription getTaskDescription(int id) {
2124 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002125 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002127 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2129 if (tr != null) {
2130 return tr.lastTaskDescription;
2131 }
2132 }
2133 return null;
2134 }
2135
2136 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002137 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2138 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2139 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2140 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2141 return;
2142 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002143 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002144 synchronized (mGlobalLock) {
2145 final long ident = Binder.clearCallingIdentity();
2146 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002147 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002148 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002149 if (task == null) {
2150 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2151 return;
2152 }
2153
2154 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2155 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2156
2157 if (!task.isActivityTypeStandardOrUndefined()) {
2158 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2159 + " non-standard task " + taskId + " to windowing mode="
2160 + windowingMode);
2161 }
2162
2163 final ActivityStack stack = task.getStack();
2164 if (toTop) {
2165 stack.moveToFront("setTaskWindowingMode", task);
2166 }
2167 stack.setWindowingMode(windowingMode);
2168 } finally {
2169 Binder.restoreCallingIdentity(ident);
2170 }
2171 }
2172 }
2173
2174 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002176 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 ActivityRecord r = getCallingRecordLocked(token);
2178 return r != null ? r.info.packageName : null;
2179 }
2180 }
2181
2182 @Override
2183 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002184 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 ActivityRecord r = getCallingRecordLocked(token);
2186 return r != null ? r.intent.getComponent() : null;
2187 }
2188 }
2189
2190 private ActivityRecord getCallingRecordLocked(IBinder token) {
2191 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2192 if (r == null) {
2193 return null;
2194 }
2195 return r.resultTo;
2196 }
2197
2198 @Override
2199 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201
2202 synchronized (mGlobalLock) {
2203 final long origId = Binder.clearCallingIdentity();
2204 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002205 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 } finally {
2207 Binder.restoreCallingIdentity(origId);
2208 }
2209 }
2210 }
2211
2212 /**
2213 * TODO: Add mController hook
2214 */
2215 @Override
2216 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002217 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218
2219 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2220 synchronized (mGlobalLock) {
2221 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2222 false /* fromRecents */);
2223 }
2224 }
2225
2226 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2227 boolean fromRecents) {
2228
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002229 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 Binder.getCallingUid(), -1, -1, "Task to front")) {
2231 SafeActivityOptions.abort(options);
2232 return;
2233 }
2234 final long origId = Binder.clearCallingIdentity();
2235 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002236 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 if (task == null) {
2238 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002239 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 return;
2241 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002242 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002244 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 return;
2246 }
2247 ActivityOptions realOptions = options != null
2248 ? options.getOptions(mStackSupervisor)
2249 : null;
2250 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2251 false /* forceNonResizable */);
2252
2253 final ActivityRecord topActivity = task.getTopActivity();
2254 if (topActivity != null) {
2255
2256 // We are reshowing a task, use a starting window to hide the initial draw delay
2257 // so the transition can start earlier.
2258 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2259 true /* taskSwitch */, fromRecents);
2260 }
2261 } finally {
2262 Binder.restoreCallingIdentity(origId);
2263 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002264 }
2265
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002266 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2267 int callingPid, int callingUid, String name) {
2268 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2269 return true;
2270 }
2271
2272 if (getRecentTasks().isCallerRecents(sourceUid)) {
2273 return true;
2274 }
2275
2276 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2277 if (perm == PackageManager.PERMISSION_GRANTED) {
2278 return true;
2279 }
2280 if (checkAllowAppSwitchUid(sourceUid)) {
2281 return true;
2282 }
2283
2284 // If the actual IPC caller is different from the logical source, then
2285 // also see if they are allowed to control app switches.
2286 if (callingUid != -1 && callingUid != sourceUid) {
2287 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2288 if (perm == PackageManager.PERMISSION_GRANTED) {
2289 return true;
2290 }
2291 if (checkAllowAppSwitchUid(callingUid)) {
2292 return true;
2293 }
2294 }
2295
2296 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2297 return false;
2298 }
2299
2300 private boolean checkAllowAppSwitchUid(int uid) {
2301 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2302 if (types != null) {
2303 for (int i = types.size() - 1; i >= 0; i--) {
2304 if (types.valueAt(i).intValue() == uid) {
2305 return true;
2306 }
2307 }
2308 }
2309 return false;
2310 }
2311
2312 @Override
2313 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2314 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2315 "setActivityController()");
2316 synchronized (mGlobalLock) {
2317 mController = controller;
2318 mControllerIsAMonkey = imAMonkey;
2319 Watchdog.getInstance().setActivityController(controller);
2320 }
2321 }
2322
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002323 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002324 synchronized (mGlobalLock) {
2325 return mController != null && mControllerIsAMonkey;
2326 }
2327 }
2328
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 @Override
2330 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2331 synchronized (mGlobalLock) {
2332 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2333 }
2334 }
2335
2336 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002337 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2338 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2339 }
2340
2341 @Override
2342 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2343 @WindowConfiguration.ActivityType int ignoreActivityType,
2344 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2345 final int callingUid = Binder.getCallingUid();
2346 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2347
2348 synchronized (mGlobalLock) {
2349 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2350
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002351 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002352 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002353 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002354 ignoreWindowingMode, callingUid, allowed);
2355 }
2356
2357 return list;
2358 }
2359
2360 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002361 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2362 synchronized (mGlobalLock) {
2363 final long origId = Binder.clearCallingIdentity();
2364 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2365 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002366 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 }
2368 Binder.restoreCallingIdentity(origId);
2369 }
2370 }
2371
2372 @Override
2373 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002374 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 ActivityStack stack = ActivityRecord.getStackLocked(token);
2376 if (stack != null) {
2377 return stack.willActivityBeVisibleLocked(token);
2378 }
2379 return false;
2380 }
2381 }
2382
2383 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002384 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002385 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002386 synchronized (mGlobalLock) {
2387 final long ident = Binder.clearCallingIdentity();
2388 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002389 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002390 if (task == null) {
2391 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2392 return;
2393 }
2394
2395 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2396 + " to stackId=" + stackId + " toTop=" + toTop);
2397
Wale Ogunwaled32da472018-11-16 07:19:28 -08002398 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002399 if (stack == null) {
2400 throw new IllegalStateException(
2401 "moveTaskToStack: No stack for stackId=" + stackId);
2402 }
2403 if (!stack.isActivityTypeStandardOrUndefined()) {
2404 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2405 + taskId + " to stack " + stackId);
2406 }
2407 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002408 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002409 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2410 }
2411 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2412 "moveTaskToStack");
2413 } finally {
2414 Binder.restoreCallingIdentity(ident);
2415 }
2416 }
2417 }
2418
2419 @Override
2420 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2421 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002422 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002423
2424 final long ident = Binder.clearCallingIdentity();
2425 try {
2426 synchronized (mGlobalLock) {
2427 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002428 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002429 if (stack == null) {
2430 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2431 return;
2432 }
2433 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2434 throw new IllegalArgumentException("Stack: " + stackId
2435 + " doesn't support animated resize.");
2436 }
2437 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2438 animationDuration, false /* fromFullscreen */);
2439 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002440 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002441 if (stack == null) {
2442 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2443 return;
2444 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002445 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002446 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2447 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2448 }
2449 }
2450 } finally {
2451 Binder.restoreCallingIdentity(ident);
2452 }
2453 }
2454
wilsonshih5c4cf522019-01-25 09:03:47 +08002455 @Override
2456 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2457 int animationDuration) {
2458 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2459
2460 final long ident = Binder.clearCallingIdentity();
2461 try {
2462 synchronized (mGlobalLock) {
2463 if (xOffset == 0 && yOffset == 0) {
2464 return;
2465 }
2466 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2467 if (stack == null) {
2468 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2469 return;
2470 }
2471 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2472 throw new IllegalArgumentException("Stack: " + stackId
2473 + " doesn't support animated resize.");
2474 }
2475 final Rect destBounds = new Rect();
2476 stack.getAnimationOrCurrentBounds(destBounds);
2477 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2478 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2479 return;
2480 }
2481 destBounds.offset(xOffset, yOffset);
2482 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2483 animationDuration, false /* fromFullscreen */);
2484 }
2485 } finally {
2486 Binder.restoreCallingIdentity(ident);
2487 }
2488 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002489 /**
2490 * Moves the specified task to the primary-split-screen stack.
2491 *
2492 * @param taskId Id of task to move.
2493 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2494 * exist already. See
2495 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2496 * and
2497 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2498 * @param toTop If the task and stack should be moved to the top.
2499 * @param animate Whether we should play an animation for the moving the task.
2500 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2501 * stack. Pass {@code null} to use default bounds.
2502 * @param showRecents If the recents activity should be shown on the other side of the task
2503 * going into split-screen mode.
2504 */
2505 @Override
2506 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2507 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002508 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002509 "setTaskWindowingModeSplitScreenPrimary()");
2510 synchronized (mGlobalLock) {
2511 final long ident = Binder.clearCallingIdentity();
2512 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002513 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002514 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002515 if (task == null) {
2516 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2517 return false;
2518 }
2519 if (DEBUG_STACK) Slog.d(TAG_STACK,
2520 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2521 + " to createMode=" + createMode + " toTop=" + toTop);
2522 if (!task.isActivityTypeStandardOrUndefined()) {
2523 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2524 + " non-standard task " + taskId + " to split-screen windowing mode");
2525 }
2526
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002528 final int windowingMode = task.getWindowingMode();
2529 final ActivityStack stack = task.getStack();
2530 if (toTop) {
2531 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2532 }
2533 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002534 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2535 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002536 return windowingMode != task.getWindowingMode();
2537 } finally {
2538 Binder.restoreCallingIdentity(ident);
2539 }
2540 }
2541 }
2542
2543 /**
2544 * Removes stacks in the input windowing modes from the system if they are of activity type
2545 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2546 */
2547 @Override
2548 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002549 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002550 "removeStacksInWindowingModes()");
2551
2552 synchronized (mGlobalLock) {
2553 final long ident = Binder.clearCallingIdentity();
2554 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002555 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002556 } finally {
2557 Binder.restoreCallingIdentity(ident);
2558 }
2559 }
2560 }
2561
2562 @Override
2563 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002564 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 "removeStacksWithActivityTypes()");
2566
2567 synchronized (mGlobalLock) {
2568 final long ident = Binder.clearCallingIdentity();
2569 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002570 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 } finally {
2572 Binder.restoreCallingIdentity(ident);
2573 }
2574 }
2575 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576
2577 @Override
2578 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2579 int userId) {
2580 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2582 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002584 final boolean detailed = checkGetTasksPermission(
2585 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2586 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002587 == PackageManager.PERMISSION_GRANTED;
2588
2589 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002590 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 callingUid);
2592 }
2593 }
2594
2595 @Override
2596 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 long ident = Binder.clearCallingIdentity();
2599 try {
2600 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002601 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002602 }
2603 } finally {
2604 Binder.restoreCallingIdentity(ident);
2605 }
2606 }
2607
2608 @Override
2609 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002610 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002611 long ident = Binder.clearCallingIdentity();
2612 try {
2613 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002614 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002615 }
2616 } finally {
2617 Binder.restoreCallingIdentity(ident);
2618 }
2619 }
2620
2621 @Override
2622 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002623 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002624 final long callingUid = Binder.getCallingUid();
2625 final long origId = Binder.clearCallingIdentity();
2626 try {
2627 synchronized (mGlobalLock) {
2628 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002629 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002630 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2631 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2632 }
2633 } finally {
2634 Binder.restoreCallingIdentity(origId);
2635 }
2636 }
2637
2638 @Override
2639 public void startLockTaskModeByToken(IBinder token) {
2640 synchronized (mGlobalLock) {
2641 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2642 if (r == null) {
2643 return;
2644 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002645 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 }
2647 }
2648
2649 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002650 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002651 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002652 // This makes inner call to look as if it was initiated by system.
2653 long ident = Binder.clearCallingIdentity();
2654 try {
2655 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002656 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002657 MATCH_TASK_IN_STACKS_ONLY);
2658 if (task == null) {
2659 return;
2660 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661
2662 // When starting lock task mode the stack must be in front and focused
2663 task.getStack().moveToFront("startSystemLockTaskMode");
2664 startLockTaskModeLocked(task, true /* isSystemCaller */);
2665 }
2666 } finally {
2667 Binder.restoreCallingIdentity(ident);
2668 }
2669 }
2670
2671 @Override
2672 public void stopLockTaskModeByToken(IBinder token) {
2673 synchronized (mGlobalLock) {
2674 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2675 if (r == null) {
2676 return;
2677 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002678 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002679 }
2680 }
2681
2682 /**
2683 * This API should be called by SystemUI only when user perform certain action to dismiss
2684 * lock task mode. We should only dismiss pinned lock task mode in this case.
2685 */
2686 @Override
2687 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002688 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002689 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2690 }
2691
2692 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2693 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2694 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2695 return;
2696 }
2697
Wale Ogunwaled32da472018-11-16 07:19:28 -08002698 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002699 if (stack == null || task != stack.topTask()) {
2700 throw new IllegalArgumentException("Invalid task, not in foreground");
2701 }
2702
2703 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2704 // system or a specific app.
2705 // * System-initiated requests will only start the pinned mode (screen pinning)
2706 // * App-initiated requests
2707 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2708 // - will start the pinned mode, otherwise
2709 final int callingUid = Binder.getCallingUid();
2710 long ident = Binder.clearCallingIdentity();
2711 try {
2712 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002713 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002714
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002715 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002716 } finally {
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720
2721 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2722 final int callingUid = Binder.getCallingUid();
2723 long ident = Binder.clearCallingIdentity();
2724 try {
2725 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002726 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002727 }
2728 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2729 // task and jumping straight into a call in the case of emergency call back.
2730 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2731 if (tm != null) {
2732 tm.showInCallScreen(false);
2733 }
2734 } finally {
2735 Binder.restoreCallingIdentity(ident);
2736 }
2737 }
2738
2739 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002740 public void updateLockTaskPackages(int userId, String[] packages) {
2741 final int callingUid = Binder.getCallingUid();
2742 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2743 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2744 "updateLockTaskPackages()");
2745 }
2746 synchronized (this) {
2747 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2748 + Arrays.toString(packages));
2749 getLockTaskController().updateLockTaskPackages(userId, packages);
2750 }
2751 }
2752
2753 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 public boolean isInLockTaskMode() {
2755 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2756 }
2757
2758 @Override
2759 public int getLockTaskModeState() {
2760 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002761 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 }
2763 }
2764
2765 @Override
2766 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2767 synchronized (mGlobalLock) {
2768 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2769 if (r != null) {
2770 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002771 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002773 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 }
2775 }
2776 }
2777
2778 @Override
2779 public Bundle getActivityOptions(IBinder token) {
2780 final long origId = Binder.clearCallingIdentity();
2781 try {
2782 synchronized (mGlobalLock) {
2783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2784 if (r != null) {
2785 final ActivityOptions activityOptions = r.takeOptionsLocked();
2786 return activityOptions == null ? null : activityOptions.toBundle();
2787 }
2788 return null;
2789 }
2790 } finally {
2791 Binder.restoreCallingIdentity(origId);
2792 }
2793 }
2794
2795 @Override
2796 public List<IBinder> getAppTasks(String callingPackage) {
2797 int callingUid = Binder.getCallingUid();
2798 long ident = Binder.clearCallingIdentity();
2799 try {
2800 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002801 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 }
2803 } finally {
2804 Binder.restoreCallingIdentity(ident);
2805 }
2806 }
2807
2808 @Override
2809 public void finishVoiceTask(IVoiceInteractionSession session) {
2810 synchronized (mGlobalLock) {
2811 final long origId = Binder.clearCallingIdentity();
2812 try {
2813 // TODO: VI Consider treating local voice interactions and voice tasks
2814 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002815 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 } finally {
2817 Binder.restoreCallingIdentity(origId);
2818 }
2819 }
2820
2821 }
2822
2823 @Override
2824 public boolean isTopOfTask(IBinder token) {
2825 synchronized (mGlobalLock) {
2826 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002827 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 }
2829 }
2830
2831 @Override
2832 public void notifyLaunchTaskBehindComplete(IBinder token) {
2833 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2834 }
2835
2836 @Override
2837 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002838 mH.post(() -> {
2839 synchronized (mGlobalLock) {
2840 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002841 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002842 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002843 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002844 } catch (RemoteException e) {
2845 }
2846 }
2847 }
2848
2849 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 }
2851
2852 /** Called from an app when assist data is ready. */
2853 @Override
2854 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2855 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002856 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 synchronized (pae) {
2858 pae.result = extras;
2859 pae.structure = structure;
2860 pae.content = content;
2861 if (referrer != null) {
2862 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2863 }
2864 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002865 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002866 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2867 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 structure.setHomeActivity(pae.isHome);
2869 }
2870 pae.haveResult = true;
2871 pae.notifyAll();
2872 if (pae.intent == null && pae.receiver == null) {
2873 // Caller is just waiting for the result.
2874 return;
2875 }
2876 }
2877 // We are now ready to launch the assist activity.
2878 IAssistDataReceiver sendReceiver = null;
2879 Bundle sendBundle = null;
2880 synchronized (mGlobalLock) {
2881 buildAssistBundleLocked(pae, extras);
2882 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002883 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 if (!exists) {
2885 // Timed out.
2886 return;
2887 }
2888
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002889 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 // Caller wants result sent back to them.
2891 sendBundle = new Bundle();
2892 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2893 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2894 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2895 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2896 }
2897 }
2898 if (sendReceiver != null) {
2899 try {
2900 sendReceiver.onHandleAssistData(sendBundle);
2901 } catch (RemoteException e) {
2902 }
2903 return;
2904 }
2905
2906 final long ident = Binder.clearCallingIdentity();
2907 try {
2908 if (TextUtils.equals(pae.intent.getAction(),
2909 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2910 pae.intent.putExtras(pae.extras);
2911 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2912 } else {
2913 pae.intent.replaceExtras(pae.extras);
2914 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2915 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2916 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002917 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918
2919 try {
2920 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2921 } catch (ActivityNotFoundException e) {
2922 Slog.w(TAG, "No activity to handle assist action.", e);
2923 }
2924 }
2925 } finally {
2926 Binder.restoreCallingIdentity(ident);
2927 }
2928 }
2929
2930 @Override
2931 public int addAppTask(IBinder activityToken, Intent intent,
2932 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2933 final int callingUid = Binder.getCallingUid();
2934 final long callingIdent = Binder.clearCallingIdentity();
2935
2936 try {
2937 synchronized (mGlobalLock) {
2938 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2939 if (r == null) {
2940 throw new IllegalArgumentException("Activity does not exist; token="
2941 + activityToken);
2942 }
2943 ComponentName comp = intent.getComponent();
2944 if (comp == null) {
2945 throw new IllegalArgumentException("Intent " + intent
2946 + " must specify explicit component");
2947 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002948 if (thumbnail.getWidth() != mThumbnailWidth
2949 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 throw new IllegalArgumentException("Bad thumbnail size: got "
2951 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002952 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 }
2954 if (intent.getSelector() != null) {
2955 intent.setSelector(null);
2956 }
2957 if (intent.getSourceBounds() != null) {
2958 intent.setSourceBounds(null);
2959 }
2960 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2961 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2962 // The caller has added this as an auto-remove task... that makes no
2963 // sense, so turn off auto-remove.
2964 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2965 }
2966 }
2967 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2968 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2969 if (ainfo.applicationInfo.uid != callingUid) {
2970 throw new SecurityException(
2971 "Can't add task for another application: target uid="
2972 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2973 }
2974
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002975 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002976 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002977 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002979 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 // The app has too many tasks already and we can't add any more
2981 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2982 return INVALID_TASK_ID;
2983 }
2984 task.lastTaskDescription.copyFrom(description);
2985
2986 // TODO: Send the thumbnail to WM to store it.
2987
2988 return task.taskId;
2989 }
2990 } finally {
2991 Binder.restoreCallingIdentity(callingIdent);
2992 }
2993 }
2994
2995 @Override
2996 public Point getAppTaskThumbnailSize() {
2997 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002998 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 }
3000 }
3001
3002 @Override
3003 public void setTaskResizeable(int taskId, int resizeableMode) {
3004 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003005 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3007 if (task == null) {
3008 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3009 return;
3010 }
3011 task.setResizeMode(resizeableMode);
3012 }
3013 }
3014
3015 @Override
3016 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003017 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 long ident = Binder.clearCallingIdentity();
3019 try {
3020 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003021 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003022 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 if (task == null) {
3024 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3025 return;
3026 }
3027 // Place the task in the right stack if it isn't there already based on
3028 // the requested bounds.
3029 // The stack transition logic is:
3030 // - a null bounds on a freeform task moves that task to fullscreen
3031 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3032 // that task to freeform
3033 // - otherwise the task is not moved
3034 ActivityStack stack = task.getStack();
3035 if (!task.getWindowConfiguration().canResizeTask()) {
3036 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3037 }
3038 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3039 stack = stack.getDisplay().getOrCreateStack(
3040 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3041 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3042 stack = stack.getDisplay().getOrCreateStack(
3043 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3044 }
3045
3046 // Reparent the task to the right stack if necessary
3047 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3048 if (stack != task.getStack()) {
3049 // Defer resume until the task is resized below
3050 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3051 DEFER_RESUME, "resizeTask");
3052 preserveWindow = false;
3053 }
3054
3055 // After reparenting (which only resizes the task to the stack bounds), resize the
3056 // task to the actual bounds provided
3057 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3058 }
3059 } finally {
3060 Binder.restoreCallingIdentity(ident);
3061 }
3062 }
3063
3064 @Override
3065 public boolean releaseActivityInstance(IBinder token) {
3066 synchronized (mGlobalLock) {
3067 final long origId = Binder.clearCallingIdentity();
3068 try {
3069 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3070 if (r == null) {
3071 return false;
3072 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003073 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003074 } finally {
3075 Binder.restoreCallingIdentity(origId);
3076 }
3077 }
3078 }
3079
3080 @Override
3081 public void releaseSomeActivities(IApplicationThread appInt) {
3082 synchronized (mGlobalLock) {
3083 final long origId = Binder.clearCallingIdentity();
3084 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003085 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003086 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087 } finally {
3088 Binder.restoreCallingIdentity(origId);
3089 }
3090 }
3091 }
3092
3093 @Override
3094 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003095 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003096 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 != PackageManager.PERMISSION_GRANTED) {
3098 throw new SecurityException("Requires permission "
3099 + android.Manifest.permission.DEVICE_POWER);
3100 }
3101
3102 synchronized (mGlobalLock) {
3103 long ident = Binder.clearCallingIdentity();
3104 if (mKeyguardShown != keyguardShowing) {
3105 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003106 final Message msg = PooledLambda.obtainMessage(
3107 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3108 keyguardShowing);
3109 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110 }
3111 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003112 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003113 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 } finally {
3115 Binder.restoreCallingIdentity(ident);
3116 }
3117 }
3118
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003119 mH.post(() -> {
3120 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3121 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3122 }
3123 });
3124 }
3125
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003126 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003127 mH.post(() -> {
3128 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3129 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3130 }
3131 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003132 }
3133
3134 @Override
3135 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003136 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3137 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138
3139 final File passedIconFile = new File(filePath);
3140 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3141 passedIconFile.getName());
3142 if (!legitIconFile.getPath().equals(filePath)
3143 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3144 throw new IllegalArgumentException("Bad file path: " + filePath
3145 + " passed for userId " + userId);
3146 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003147 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 }
3149
3150 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003151 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3153 final ActivityOptions activityOptions = safeOptions != null
3154 ? safeOptions.getOptions(mStackSupervisor)
3155 : null;
3156 if (activityOptions == null
3157 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3158 || activityOptions.getCustomInPlaceResId() == 0) {
3159 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3160 "with valid animation");
3161 }
lumark588a3e82018-07-20 18:53:54 +08003162 // Get top display of front most application.
3163 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3164 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003165 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3166 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3167 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003168 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003169 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003170 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 }
3172
3173 @Override
3174 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003175 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 synchronized (mGlobalLock) {
3177 final long ident = Binder.clearCallingIdentity();
3178 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003179 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 if (stack == null) {
3181 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3182 return;
3183 }
3184 if (!stack.isActivityTypeStandardOrUndefined()) {
3185 throw new IllegalArgumentException(
3186 "Removing non-standard stack is not allowed.");
3187 }
3188 mStackSupervisor.removeStack(stack);
3189 } finally {
3190 Binder.restoreCallingIdentity(ident);
3191 }
3192 }
3193 }
3194
3195 @Override
3196 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003197 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198
3199 synchronized (mGlobalLock) {
3200 final long ident = Binder.clearCallingIdentity();
3201 try {
3202 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3203 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003204 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 } finally {
3206 Binder.restoreCallingIdentity(ident);
3207 }
3208 }
3209 }
3210
3211 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 public void exitFreeformMode(IBinder token) {
3213 synchronized (mGlobalLock) {
3214 long ident = Binder.clearCallingIdentity();
3215 try {
3216 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3217 if (r == null) {
3218 throw new IllegalArgumentException(
3219 "exitFreeformMode: No activity record matching token=" + token);
3220 }
3221
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003222 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003223 if (stack == null || !stack.inFreeformWindowingMode()) {
3224 throw new IllegalStateException(
3225 "exitFreeformMode: You can only go fullscreen from freeform.");
3226 }
3227
3228 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3229 } finally {
3230 Binder.restoreCallingIdentity(ident);
3231 }
3232 }
3233 }
3234
3235 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3236 @Override
3237 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003238 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003239 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003240 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 }
3242
3243 /** Unregister a task stack listener so that it stops receiving callbacks. */
3244 @Override
3245 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003246 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003248 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 }
3250
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 @Override
3252 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3253 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3254 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3255 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3256 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3257 }
3258
3259 @Override
3260 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3261 IBinder activityToken, int flags) {
3262 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3263 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3264 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3265 }
3266
3267 @Override
3268 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3269 Bundle args) {
3270 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3271 true /* focused */, true /* newSessionId */, userHandle, args,
3272 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3273 }
3274
3275 @Override
3276 public Bundle getAssistContextExtras(int requestType) {
3277 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3278 null, null, true /* focused */, true /* newSessionId */,
3279 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3280 if (pae == null) {
3281 return null;
3282 }
3283 synchronized (pae) {
3284 while (!pae.haveResult) {
3285 try {
3286 pae.wait();
3287 } catch (InterruptedException e) {
3288 }
3289 }
3290 }
3291 synchronized (mGlobalLock) {
3292 buildAssistBundleLocked(pae, pae.result);
3293 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003294 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 }
3296 return pae.extras;
3297 }
3298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003299 /**
3300 * Binder IPC calls go through the public entry point.
3301 * This can be called with or without the global lock held.
3302 */
3303 private static int checkCallingPermission(String permission) {
3304 return checkPermission(
3305 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3306 }
3307
3308 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003309 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003310 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3311 mAmInternal.enforceCallingPermission(permission, func);
3312 }
3313 }
3314
3315 @VisibleForTesting
3316 int checkGetTasksPermission(String permission, int pid, int uid) {
3317 return checkPermission(permission, pid, uid);
3318 }
3319
3320 static int checkPermission(String permission, int pid, int uid) {
3321 if (permission == null) {
3322 return PackageManager.PERMISSION_DENIED;
3323 }
3324 return checkComponentPermission(permission, pid, uid, -1, true);
3325 }
3326
Wale Ogunwale214f3482018-10-04 11:00:47 -07003327 public static int checkComponentPermission(String permission, int pid, int uid,
3328 int owningUid, boolean exported) {
3329 return ActivityManagerService.checkComponentPermission(
3330 permission, pid, uid, owningUid, exported);
3331 }
3332
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003333 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3334 if (getRecentTasks().isCallerRecents(callingUid)) {
3335 // Always allow the recents component to get tasks
3336 return true;
3337 }
3338
3339 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3340 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3341 if (!allowed) {
3342 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3343 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3344 // Temporary compatibility: some existing apps on the system image may
3345 // still be requesting the old permission and not switched to the new
3346 // one; if so, we'll still allow them full access. This means we need
3347 // to see if they are holding the old permission and are a system app.
3348 try {
3349 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3350 allowed = true;
3351 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3352 + " is using old GET_TASKS but privileged; allowing");
3353 }
3354 } catch (RemoteException e) {
3355 }
3356 }
3357 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3358 + " does not hold REAL_GET_TASKS; limiting output");
3359 }
3360 return allowed;
3361 }
3362
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3364 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3365 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3366 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003367 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 "enqueueAssistContext()");
3369
3370 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003371 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 if (activity == null) {
3373 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3374 return null;
3375 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003376 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3378 return null;
3379 }
3380 if (focused) {
3381 if (activityToken != null) {
3382 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3383 if (activity != caller) {
3384 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3385 + " is not current top " + activity);
3386 return null;
3387 }
3388 }
3389 } else {
3390 activity = ActivityRecord.forTokenLocked(activityToken);
3391 if (activity == null) {
3392 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3393 + " couldn't be found");
3394 return null;
3395 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003396 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3398 return null;
3399 }
3400 }
3401
3402 PendingAssistExtras pae;
3403 Bundle extras = new Bundle();
3404 if (args != null) {
3405 extras.putAll(args);
3406 }
3407 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003408 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409
3410 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3411 userHandle);
3412 pae.isHome = activity.isActivityTypeHome();
3413
3414 // Increment the sessionId if necessary
3415 if (newSessionId) {
3416 mViSessionId++;
3417 }
3418 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003419 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3420 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003422 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 } catch (RemoteException e) {
3424 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3425 return null;
3426 }
3427 return pae;
3428 }
3429 }
3430
3431 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3432 if (result != null) {
3433 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3434 }
3435 if (pae.hint != null) {
3436 pae.extras.putBoolean(pae.hint, true);
3437 }
3438 }
3439
3440 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3441 IAssistDataReceiver receiver;
3442 synchronized (mGlobalLock) {
3443 mPendingAssistExtras.remove(pae);
3444 receiver = pae.receiver;
3445 }
3446 if (receiver != null) {
3447 // Caller wants result sent back to them.
3448 Bundle sendBundle = new Bundle();
3449 // At least return the receiver extras
3450 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3451 try {
3452 pae.receiver.onHandleAssistData(sendBundle);
3453 } catch (RemoteException e) {
3454 }
3455 }
3456 }
3457
3458 public class PendingAssistExtras extends Binder implements Runnable {
3459 public final ActivityRecord activity;
3460 public boolean isHome;
3461 public final Bundle extras;
3462 public final Intent intent;
3463 public final String hint;
3464 public final IAssistDataReceiver receiver;
3465 public final int userHandle;
3466 public boolean haveResult = false;
3467 public Bundle result = null;
3468 public AssistStructure structure = null;
3469 public AssistContent content = null;
3470 public Bundle receiverExtras;
3471
3472 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3473 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3474 int _userHandle) {
3475 activity = _activity;
3476 extras = _extras;
3477 intent = _intent;
3478 hint = _hint;
3479 receiver = _receiver;
3480 receiverExtras = _receiverExtras;
3481 userHandle = _userHandle;
3482 }
3483
3484 @Override
3485 public void run() {
3486 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3487 synchronized (this) {
3488 haveResult = true;
3489 notifyAll();
3490 }
3491 pendingAssistExtrasTimedOut(this);
3492 }
3493 }
3494
3495 @Override
3496 public boolean isAssistDataAllowedOnCurrentActivity() {
3497 int userId;
3498 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003499 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003500 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3501 return false;
3502 }
3503
3504 final ActivityRecord activity = focusedStack.getTopActivity();
3505 if (activity == null) {
3506 return false;
3507 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003508 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3511 }
3512
3513 @Override
3514 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3515 long ident = Binder.clearCallingIdentity();
3516 try {
3517 synchronized (mGlobalLock) {
3518 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003519 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003520 if (top != caller) {
3521 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3522 + " is not current top " + top);
3523 return false;
3524 }
3525 if (!top.nowVisible) {
3526 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3527 + " is not visible");
3528 return false;
3529 }
3530 }
3531 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3532 token);
3533 } finally {
3534 Binder.restoreCallingIdentity(ident);
3535 }
3536 }
3537
3538 @Override
3539 public boolean isRootVoiceInteraction(IBinder token) {
3540 synchronized (mGlobalLock) {
3541 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3542 if (r == null) {
3543 return false;
3544 }
3545 return r.rootVoiceInteraction;
3546 }
3547 }
3548
Wale Ogunwalef6733932018-06-27 05:14:34 -07003549 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3550 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3551 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3552 if (activityToCallback == null) return;
3553 activityToCallback.setVoiceSessionLocked(voiceSession);
3554
3555 // Inform the activity
3556 try {
3557 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3558 voiceInteractor);
3559 long token = Binder.clearCallingIdentity();
3560 try {
3561 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3562 } finally {
3563 Binder.restoreCallingIdentity(token);
3564 }
3565 // TODO: VI Should we cache the activity so that it's easier to find later
3566 // rather than scan through all the stacks and activities?
3567 } catch (RemoteException re) {
3568 activityToCallback.clearVoiceSessionLocked();
3569 // TODO: VI Should this terminate the voice session?
3570 }
3571 }
3572
3573 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3574 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3575 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3576 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3577 boolean wasRunningVoice = mRunningVoice != null;
3578 mRunningVoice = session;
3579 if (!wasRunningVoice) {
3580 mVoiceWakeLock.acquire();
3581 updateSleepIfNeededLocked();
3582 }
3583 }
3584 }
3585
3586 void finishRunningVoiceLocked() {
3587 if (mRunningVoice != null) {
3588 mRunningVoice = null;
3589 mVoiceWakeLock.release();
3590 updateSleepIfNeededLocked();
3591 }
3592 }
3593
3594 @Override
3595 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3596 synchronized (mGlobalLock) {
3597 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3598 if (keepAwake) {
3599 mVoiceWakeLock.acquire();
3600 } else {
3601 mVoiceWakeLock.release();
3602 }
3603 }
3604 }
3605 }
3606
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 @Override
3608 public ComponentName getActivityClassForToken(IBinder token) {
3609 synchronized (mGlobalLock) {
3610 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3611 if (r == null) {
3612 return null;
3613 }
3614 return r.intent.getComponent();
3615 }
3616 }
3617
3618 @Override
3619 public String getPackageForToken(IBinder token) {
3620 synchronized (mGlobalLock) {
3621 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3622 if (r == null) {
3623 return null;
3624 }
3625 return r.packageName;
3626 }
3627 }
3628
3629 @Override
3630 public void showLockTaskEscapeMessage(IBinder token) {
3631 synchronized (mGlobalLock) {
3632 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3633 if (r == null) {
3634 return;
3635 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003636 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003637 }
3638 }
3639
3640 @Override
3641 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003642 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 final long token = Binder.clearCallingIdentity();
3644 try {
3645 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003646 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003647 }
3648 } finally {
3649 Binder.restoreCallingIdentity(token);
3650 }
3651 }
3652
3653 /**
3654 * Try to place task to provided position. The final position might be different depending on
3655 * current user and stacks state. The task will be moved to target stack if it's currently in
3656 * different stack.
3657 */
3658 @Override
3659 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003660 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003661 synchronized (mGlobalLock) {
3662 long ident = Binder.clearCallingIdentity();
3663 try {
3664 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3665 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003666 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003667 if (task == null) {
3668 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3669 + taskId);
3670 }
3671
Wale Ogunwaled32da472018-11-16 07:19:28 -08003672 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003673
3674 if (stack == null) {
3675 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3676 + stackId);
3677 }
3678 if (!stack.isActivityTypeStandardOrUndefined()) {
3679 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3680 + " the position of task " + taskId + " in/to non-standard stack");
3681 }
3682
3683 // TODO: Have the callers of this API call a separate reparent method if that is
3684 // what they intended to do vs. having this method also do reparenting.
3685 if (task.getStack() == stack) {
3686 // Change position in current stack.
3687 stack.positionChildAt(task, position);
3688 } else {
3689 // Reparent to new stack.
3690 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3691 !DEFER_RESUME, "positionTaskInStack");
3692 }
3693 } finally {
3694 Binder.restoreCallingIdentity(ident);
3695 }
3696 }
3697 }
3698
3699 @Override
3700 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3701 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3702 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3703 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3704 synchronized (mGlobalLock) {
3705 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3706 if (record == null) {
3707 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3708 + "found for: " + token);
3709 }
3710 record.setSizeConfigurations(horizontalSizeConfiguration,
3711 verticalSizeConfigurations, smallestSizeConfigurations);
3712 }
3713 }
3714
3715 /**
3716 * Dismisses split-screen multi-window mode.
3717 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3718 */
3719 @Override
3720 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003721 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3723 final long ident = Binder.clearCallingIdentity();
3724 try {
3725 synchronized (mGlobalLock) {
3726 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003727 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003728 if (stack == null) {
3729 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3730 return;
3731 }
3732
3733 if (toTop) {
3734 // Caller wants the current split-screen primary stack to be the top stack after
3735 // it goes fullscreen, so move it to the front.
3736 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003737 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 // In this case the current split-screen primary stack shouldn't be the top
3739 // stack after it goes fullscreen, but it current has focus, so we move the
3740 // focus to the top-most split-screen secondary stack next to it.
3741 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3742 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3743 if (otherStack != null) {
3744 otherStack.moveToFront("dismissSplitScreenMode_other");
3745 }
3746 }
3747
Evan Rosky10475742018-09-05 19:02:48 -07003748 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 }
3750 } finally {
3751 Binder.restoreCallingIdentity(ident);
3752 }
3753 }
3754
3755 /**
3756 * Dismisses Pip
3757 * @param animate True if the dismissal should be animated.
3758 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3759 * default animation duration should be used.
3760 */
3761 @Override
3762 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003763 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003764 final long ident = Binder.clearCallingIdentity();
3765 try {
3766 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003767 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003768 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003769 if (stack == null) {
3770 Slog.w(TAG, "dismissPip: pinned stack not found.");
3771 return;
3772 }
3773 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3774 throw new IllegalArgumentException("Stack: " + stack
3775 + " doesn't support animated resize.");
3776 }
3777 if (animate) {
3778 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3779 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3780 } else {
3781 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3782 }
3783 }
3784 } finally {
3785 Binder.restoreCallingIdentity(ident);
3786 }
3787 }
3788
3789 @Override
3790 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003791 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 synchronized (mGlobalLock) {
3793 mSuppressResizeConfigChanges = suppress;
3794 }
3795 }
3796
3797 /**
3798 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3799 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3800 * activity and clearing the task at the same time.
3801 */
3802 @Override
3803 // TODO: API should just be about changing windowing modes...
3804 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003805 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 "moveTasksToFullscreenStack()");
3807 synchronized (mGlobalLock) {
3808 final long origId = Binder.clearCallingIdentity();
3809 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003810 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003811 if (stack != null){
3812 if (!stack.isActivityTypeStandardOrUndefined()) {
3813 throw new IllegalArgumentException(
3814 "You can't move tasks from non-standard stacks.");
3815 }
3816 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3817 }
3818 } finally {
3819 Binder.restoreCallingIdentity(origId);
3820 }
3821 }
3822 }
3823
3824 /**
3825 * Moves the top activity in the input stackId to the pinned stack.
3826 *
3827 * @param stackId Id of stack to move the top activity to pinned stack.
3828 * @param bounds Bounds to use for pinned stack.
3829 *
3830 * @return True if the top activity of the input stack was successfully moved to the pinned
3831 * stack.
3832 */
3833 @Override
3834 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003835 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 "moveTopActivityToPinnedStack()");
3837 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003838 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3840 + "Device doesn't support picture-in-picture mode");
3841 }
3842
3843 long ident = Binder.clearCallingIdentity();
3844 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003845 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 } finally {
3847 Binder.restoreCallingIdentity(ident);
3848 }
3849 }
3850 }
3851
3852 @Override
3853 public boolean isInMultiWindowMode(IBinder token) {
3854 final long origId = Binder.clearCallingIdentity();
3855 try {
3856 synchronized (mGlobalLock) {
3857 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3858 if (r == null) {
3859 return false;
3860 }
3861 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3862 return r.inMultiWindowMode();
3863 }
3864 } finally {
3865 Binder.restoreCallingIdentity(origId);
3866 }
3867 }
3868
3869 @Override
3870 public boolean isInPictureInPictureMode(IBinder token) {
3871 final long origId = Binder.clearCallingIdentity();
3872 try {
3873 synchronized (mGlobalLock) {
3874 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3875 }
3876 } finally {
3877 Binder.restoreCallingIdentity(origId);
3878 }
3879 }
3880
3881 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003882 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3883 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884 return false;
3885 }
3886
3887 // If we are animating to fullscreen then we have already dispatched the PIP mode
3888 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003889 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3890 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 }
3892
3893 @Override
3894 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3895 final long origId = Binder.clearCallingIdentity();
3896 try {
3897 synchronized (mGlobalLock) {
3898 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3899 "enterPictureInPictureMode", token, params);
3900
3901 // If the activity is already in picture in picture mode, then just return early
3902 if (isInPictureInPictureMode(r)) {
3903 return true;
3904 }
3905
3906 // Activity supports picture-in-picture, now check that we can enter PiP at this
3907 // point, if it is
3908 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3909 false /* beforeStopping */)) {
3910 return false;
3911 }
3912
3913 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003914 synchronized (mGlobalLock) {
3915 // Only update the saved args from the args that are set
3916 r.pictureInPictureArgs.copyOnlySet(params);
3917 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3918 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3919 // Adjust the source bounds by the insets for the transition down
3920 final Rect sourceBounds = new Rect(
3921 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003922 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003923 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003924 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003925 stack.setPictureInPictureAspectRatio(aspectRatio);
3926 stack.setPictureInPictureActions(actions);
3927 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3928 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3929 logPictureInPictureArgs(params);
3930 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 };
3932
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003933 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 // If the keyguard is showing or occluded, then try and dismiss it before
3935 // entering picture-in-picture (this will prompt the user to authenticate if the
3936 // device is currently locked).
3937 dismissKeyguard(token, new KeyguardDismissCallback() {
3938 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003939 public void onDismissSucceeded() {
3940 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 }
3942 }, null /* message */);
3943 } else {
3944 // Enter picture in picture immediately otherwise
3945 enterPipRunnable.run();
3946 }
3947 return true;
3948 }
3949 } finally {
3950 Binder.restoreCallingIdentity(origId);
3951 }
3952 }
3953
3954 @Override
3955 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3956 final long origId = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
3959 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3960 "setPictureInPictureParams", token, params);
3961
3962 // Only update the saved args from the args that are set
3963 r.pictureInPictureArgs.copyOnlySet(params);
3964 if (r.inPinnedWindowingMode()) {
3965 // If the activity is already in picture-in-picture, update the pinned stack now
3966 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3967 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003968 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003969 if (!stack.isAnimatingBoundsToFullscreen()) {
3970 stack.setPictureInPictureAspectRatio(
3971 r.pictureInPictureArgs.getAspectRatio());
3972 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3973 }
3974 }
3975 logPictureInPictureArgs(params);
3976 }
3977 } finally {
3978 Binder.restoreCallingIdentity(origId);
3979 }
3980 }
3981
3982 @Override
3983 public int getMaxNumPictureInPictureActions(IBinder token) {
3984 // Currently, this is a static constant, but later, we may change this to be dependent on
3985 // the context of the activity
3986 return 3;
3987 }
3988
3989 private void logPictureInPictureArgs(PictureInPictureParams params) {
3990 if (params.hasSetActions()) {
3991 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3992 params.getActions().size());
3993 }
3994 if (params.hasSetAspectRatio()) {
3995 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3996 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3997 MetricsLogger.action(lm);
3998 }
3999 }
4000
4001 /**
4002 * Checks the state of the system and the activity associated with the given {@param token} to
4003 * verify that picture-in-picture is supported for that activity.
4004 *
4005 * @return the activity record for the given {@param token} if all the checks pass.
4006 */
4007 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4008 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 throw new IllegalStateException(caller
4011 + ": Device doesn't support picture-in-picture mode.");
4012 }
4013
4014 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4015 if (r == null) {
4016 throw new IllegalStateException(caller
4017 + ": Can't find activity for token=" + token);
4018 }
4019
4020 if (!r.supportsPictureInPicture()) {
4021 throw new IllegalStateException(caller
4022 + ": Current activity does not support picture-in-picture.");
4023 }
4024
4025 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004026 && !mWindowManager.isValidPictureInPictureAspectRatio(
4027 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 final float minAspectRatio = mContext.getResources().getFloat(
4029 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4030 final float maxAspectRatio = mContext.getResources().getFloat(
4031 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4032 throw new IllegalArgumentException(String.format(caller
4033 + ": Aspect ratio is too extreme (must be between %f and %f).",
4034 minAspectRatio, maxAspectRatio));
4035 }
4036
4037 // Truncate the number of actions if necessary
4038 params.truncateActions(getMaxNumPictureInPictureActions(token));
4039
4040 return r;
4041 }
4042
4043 @Override
4044 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004045 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 synchronized (mGlobalLock) {
4047 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4048 if (r == null) {
4049 throw new IllegalArgumentException("Activity does not exist; token="
4050 + activityToken);
4051 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004052 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 }
4054 }
4055
4056 @Override
4057 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4058 Rect tempDockedTaskInsetBounds,
4059 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004060 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 long ident = Binder.clearCallingIdentity();
4062 try {
4063 synchronized (mGlobalLock) {
4064 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4065 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4066 PRESERVE_WINDOWS);
4067 }
4068 } finally {
4069 Binder.restoreCallingIdentity(ident);
4070 }
4071 }
4072
4073 @Override
4074 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004075 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 final long ident = Binder.clearCallingIdentity();
4077 try {
4078 synchronized (mGlobalLock) {
4079 mStackSupervisor.setSplitScreenResizing(resizing);
4080 }
4081 } finally {
4082 Binder.restoreCallingIdentity(ident);
4083 }
4084 }
4085
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004086 /**
4087 * Check that we have the features required for VR-related API calls, and throw an exception if
4088 * not.
4089 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004090 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004091 if (!mContext.getPackageManager().hasSystemFeature(
4092 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4093 throw new UnsupportedOperationException("VR mode not supported on this device!");
4094 }
4095 }
4096
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004097 @Override
4098 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004099 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100
4101 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4102
4103 ActivityRecord r;
4104 synchronized (mGlobalLock) {
4105 r = ActivityRecord.isInStackLocked(token);
4106 }
4107
4108 if (r == null) {
4109 throw new IllegalArgumentException();
4110 }
4111
4112 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004113 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 VrManagerInternal.NO_ERROR) {
4115 return err;
4116 }
4117
4118 // Clear the binder calling uid since this path may call moveToTask().
4119 final long callingId = Binder.clearCallingIdentity();
4120 try {
4121 synchronized (mGlobalLock) {
4122 r.requestedVrComponent = (enabled) ? packageName : null;
4123
4124 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004125 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004126 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 }
4128 return 0;
4129 }
4130 } finally {
4131 Binder.restoreCallingIdentity(callingId);
4132 }
4133 }
4134
4135 @Override
4136 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4137 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4138 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004139 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4141 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4142 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004143 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 || activity.voiceSession != null) {
4145 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4146 return;
4147 }
4148 if (activity.pendingVoiceInteractionStart) {
4149 Slog.w(TAG, "Pending start of voice interaction already.");
4150 return;
4151 }
4152 activity.pendingVoiceInteractionStart = true;
4153 }
4154 LocalServices.getService(VoiceInteractionManagerInternal.class)
4155 .startLocalVoiceInteraction(callingActivity, options);
4156 }
4157
4158 @Override
4159 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4160 LocalServices.getService(VoiceInteractionManagerInternal.class)
4161 .stopLocalVoiceInteraction(callingActivity);
4162 }
4163
4164 @Override
4165 public boolean supportsLocalVoiceInteraction() {
4166 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4167 .supportsLocalVoiceInteraction();
4168 }
4169
4170 /** Notifies all listeners when the pinned stack animation starts. */
4171 @Override
4172 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004173 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175
4176 /** Notifies all listeners when the pinned stack animation ends. */
4177 @Override
4178 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004179 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 }
4181
4182 @Override
4183 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004184 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 final long ident = Binder.clearCallingIdentity();
4186 try {
4187 synchronized (mGlobalLock) {
4188 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4189 }
4190 } finally {
4191 Binder.restoreCallingIdentity(ident);
4192 }
4193 }
4194
4195 @Override
4196 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004197 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198
4199 synchronized (mGlobalLock) {
4200 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004201 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 // Call might come when display is not yet added or has already been removed.
4203 if (DEBUG_CONFIGURATION) {
4204 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4205 + displayId);
4206 }
4207 return false;
4208 }
4209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004210 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004212 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 }
4214
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004215 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004216 final Message msg = PooledLambda.obtainMessage(
4217 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4218 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 }
4220
4221 final long origId = Binder.clearCallingIdentity();
4222 try {
4223 if (values != null) {
4224 Settings.System.clearConfiguration(values);
4225 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004226 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4228 return mTmpUpdateConfigurationResult.changes != 0;
4229 } finally {
4230 Binder.restoreCallingIdentity(origId);
4231 }
4232 }
4233 }
4234
4235 @Override
4236 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004237 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238
4239 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004240 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 }
4244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004245 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004246 final Message msg = PooledLambda.obtainMessage(
4247 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4248 DEFAULT_DISPLAY);
4249 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 }
4251
4252 final long origId = Binder.clearCallingIdentity();
4253 try {
4254 if (values != null) {
4255 Settings.System.clearConfiguration(values);
4256 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004257 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 UserHandle.USER_NULL, false /* deferResume */,
4259 mTmpUpdateConfigurationResult);
4260 return mTmpUpdateConfigurationResult.changes != 0;
4261 } finally {
4262 Binder.restoreCallingIdentity(origId);
4263 }
4264 }
4265 }
4266
4267 @Override
4268 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4269 CharSequence message) {
4270 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4273 }
4274 final long callingId = Binder.clearCallingIdentity();
4275 try {
4276 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004277 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004278 }
4279 } finally {
4280 Binder.restoreCallingIdentity(callingId);
4281 }
4282 }
4283
4284 @Override
4285 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004286 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 "cancelTaskWindowTransition()");
4288 final long ident = Binder.clearCallingIdentity();
4289 try {
4290 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004291 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 MATCH_TASK_IN_STACKS_ONLY);
4293 if (task == null) {
4294 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4295 return;
4296 }
4297 task.cancelWindowTransition();
4298 }
4299 } finally {
4300 Binder.restoreCallingIdentity(ident);
4301 }
4302 }
4303
4304 @Override
4305 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 final long ident = Binder.clearCallingIdentity();
4308 try {
4309 final TaskRecord task;
4310 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004311 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4313 if (task == null) {
4314 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4315 return null;
4316 }
4317 }
4318 // Don't call this while holding the lock as this operation might hit the disk.
4319 return task.getSnapshot(reducedResolution);
4320 } finally {
4321 Binder.restoreCallingIdentity(ident);
4322 }
4323 }
4324
4325 @Override
4326 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4327 synchronized (mGlobalLock) {
4328 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4329 if (r == null) {
4330 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4331 + token);
4332 return;
4333 }
4334 final long origId = Binder.clearCallingIdentity();
4335 try {
4336 r.setDisablePreviewScreenshots(disable);
4337 } finally {
4338 Binder.restoreCallingIdentity(origId);
4339 }
4340 }
4341 }
4342
4343 /** Return the user id of the last resumed activity. */
4344 @Override
4345 public @UserIdInt
4346 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4349 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004350 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004353 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 }
4355 }
4356
4357 @Override
4358 public void updateLockTaskFeatures(int userId, int flags) {
4359 final int callingUid = Binder.getCallingUid();
4360 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004361 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 "updateLockTaskFeatures()");
4363 }
4364 synchronized (mGlobalLock) {
4365 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4366 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004367 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 }
4369 }
4370
4371 @Override
4372 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4373 synchronized (mGlobalLock) {
4374 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4375 if (r == null) {
4376 return;
4377 }
4378 final long origId = Binder.clearCallingIdentity();
4379 try {
4380 r.setShowWhenLocked(showWhenLocked);
4381 } finally {
4382 Binder.restoreCallingIdentity(origId);
4383 }
4384 }
4385 }
4386
4387 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004388 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4389 synchronized (mGlobalLock) {
4390 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4391 if (r == null) {
4392 return;
4393 }
4394 final long origId = Binder.clearCallingIdentity();
4395 try {
4396 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4397 } finally {
4398 Binder.restoreCallingIdentity(origId);
4399 }
4400 }
4401 }
4402
4403 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4405 synchronized (mGlobalLock) {
4406 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4407 if (r == null) {
4408 return;
4409 }
4410 final long origId = Binder.clearCallingIdentity();
4411 try {
4412 r.setTurnScreenOn(turnScreenOn);
4413 } finally {
4414 Binder.restoreCallingIdentity(origId);
4415 }
4416 }
4417 }
4418
4419 @Override
4420 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 "registerRemoteAnimations");
4423 definition.setCallingPid(Binder.getCallingPid());
4424 synchronized (mGlobalLock) {
4425 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4426 if (r == null) {
4427 return;
4428 }
4429 final long origId = Binder.clearCallingIdentity();
4430 try {
4431 r.registerRemoteAnimations(definition);
4432 } finally {
4433 Binder.restoreCallingIdentity(origId);
4434 }
4435 }
4436 }
4437
4438 @Override
4439 public void registerRemoteAnimationForNextActivityStart(String packageName,
4440 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 "registerRemoteAnimationForNextActivityStart");
4443 adapter.setCallingPid(Binder.getCallingPid());
4444 synchronized (mGlobalLock) {
4445 final long origId = Binder.clearCallingIdentity();
4446 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004447 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 packageName, adapter);
4449 } finally {
4450 Binder.restoreCallingIdentity(origId);
4451 }
4452 }
4453 }
4454
Evan Rosky966759f2019-01-15 10:33:58 -08004455 @Override
4456 public void registerRemoteAnimationsForDisplay(int displayId,
4457 RemoteAnimationDefinition definition) {
4458 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4459 "registerRemoteAnimations");
4460 definition.setCallingPid(Binder.getCallingPid());
4461 synchronized (mGlobalLock) {
4462 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4463 if (display == null) {
4464 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4465 return;
4466 }
4467 final long origId = Binder.clearCallingIdentity();
4468 try {
4469 display.mDisplayContent.registerRemoteAnimations(definition);
4470 } finally {
4471 Binder.restoreCallingIdentity(origId);
4472 }
4473 }
4474 }
4475
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4477 @Override
4478 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4479 synchronized (mGlobalLock) {
4480 final long origId = Binder.clearCallingIdentity();
4481 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004482 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 } finally {
4484 Binder.restoreCallingIdentity(origId);
4485 }
4486 }
4487 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004488
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004489 @Override
4490 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004491 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004492 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004493 final int pid = Binder.getCallingPid();
4494 final WindowProcessController wpc = mPidMap.get(pid);
4495 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004496 }
4497 }
4498
4499 @Override
4500 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004501 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004502 != PERMISSION_GRANTED) {
4503 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4504 + Binder.getCallingPid()
4505 + ", uid=" + Binder.getCallingUid()
4506 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4507 Slog.w(TAG, msg);
4508 throw new SecurityException(msg);
4509 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004511 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004512 final int pid = Binder.getCallingPid();
4513 final WindowProcessController proc = mPidMap.get(pid);
4514 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004515 }
4516 }
4517
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004518 @Override
4519 public void stopAppSwitches() {
4520 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4521 synchronized (mGlobalLock) {
4522 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4523 mDidAppSwitch = false;
4524 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4525 }
4526 }
4527
4528 @Override
4529 public void resumeAppSwitches() {
4530 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4531 synchronized (mGlobalLock) {
4532 // Note that we don't execute any pending app switches... we will
4533 // let those wait until either the timeout, or the next start
4534 // activity request.
4535 mAppSwitchesAllowedTime = 0;
4536 }
4537 }
4538
4539 void onStartActivitySetDidAppSwitch() {
4540 if (mDidAppSwitch) {
4541 // This is the second allowed switch since we stopped switches, so now just generally
4542 // allow switches. Use case:
4543 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4544 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4545 // anyone to switch again).
4546 mAppSwitchesAllowedTime = 0;
4547 } else {
4548 mDidAppSwitch = true;
4549 }
4550 }
4551
4552 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004553 boolean shouldDisableNonVrUiLocked() {
4554 return mVrController.shouldDisableNonVrUiLocked();
4555 }
4556
Wale Ogunwale53783742018-09-16 10:21:51 -07004557 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004558 // VR apps are expected to run in a main display. If an app is turning on VR for
4559 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4560 // fullscreen stack before enabling VR Mode.
4561 // TODO: The goal of this code is to keep the VR app on the main display. When the
4562 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4563 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4564 // option would be a better choice here.
4565 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4566 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4567 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004568 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004569 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004570 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004571 }
4572 mH.post(() -> {
4573 if (!mVrController.onVrModeChanged(r)) {
4574 return;
4575 }
4576 synchronized (mGlobalLock) {
4577 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4578 mWindowManager.disableNonVrUi(disableNonVrUi);
4579 if (disableNonVrUi) {
4580 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4581 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004582 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004583 }
4584 }
4585 });
4586 }
4587
Wale Ogunwale53783742018-09-16 10:21:51 -07004588 @Override
4589 public int getPackageScreenCompatMode(String packageName) {
4590 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4591 synchronized (mGlobalLock) {
4592 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4593 }
4594 }
4595
4596 @Override
4597 public void setPackageScreenCompatMode(String packageName, int mode) {
4598 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4599 "setPackageScreenCompatMode");
4600 synchronized (mGlobalLock) {
4601 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4602 }
4603 }
4604
4605 @Override
4606 public boolean getPackageAskScreenCompat(String packageName) {
4607 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4608 synchronized (mGlobalLock) {
4609 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4610 }
4611 }
4612
4613 @Override
4614 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4615 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4616 "setPackageAskScreenCompat");
4617 synchronized (mGlobalLock) {
4618 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4619 }
4620 }
4621
Wale Ogunwale64258362018-10-16 15:13:37 -07004622 public static String relaunchReasonToString(int relaunchReason) {
4623 switch (relaunchReason) {
4624 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4625 return "window_resize";
4626 case RELAUNCH_REASON_FREE_RESIZE:
4627 return "free_resize";
4628 default:
4629 return null;
4630 }
4631 }
4632
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004633 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004634 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004635 }
4636
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004637 /** Pokes the task persister. */
4638 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4639 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4640 }
4641
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004642 boolean isKeyguardLocked() {
4643 return mKeyguardController.isKeyguardLocked();
4644 }
4645
Garfield Tan01548632018-11-27 10:15:48 -08004646 /**
4647 * Clears launch params for the given package.
4648 * @param packageNames the names of the packages of which the launch params are to be cleared
4649 */
4650 @Override
4651 public void clearLaunchParamsForPackages(List<String> packageNames) {
4652 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4653 "clearLaunchParamsForPackages");
4654 synchronized (mGlobalLock) {
4655 for (int i = 0; i < packageNames.size(); ++i) {
4656 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4657 }
4658 }
4659 }
4660
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004661 /**
4662 * Makes the display with the given id a single task instance display. I.e the display can only
4663 * contain one task.
4664 */
4665 @Override
4666 public void setDisplayToSingleTaskInstance(int displayId) {
4667 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4668 "setDisplayToSingleTaskInstance");
4669 final long origId = Binder.clearCallingIdentity();
4670 try {
4671 final ActivityDisplay display =
4672 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4673 if (display != null) {
4674 display.setDisplayToSingleTaskInstance();
4675 }
4676 } finally {
4677 Binder.restoreCallingIdentity(origId);
4678 }
4679 }
4680
Wale Ogunwale31913b52018-10-13 08:29:31 -07004681 void dumpLastANRLocked(PrintWriter pw) {
4682 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4683 if (mLastANRState == null) {
4684 pw.println(" <no ANR has occurred since boot>");
4685 } else {
4686 pw.println(mLastANRState);
4687 }
4688 }
4689
4690 void dumpLastANRTracesLocked(PrintWriter pw) {
4691 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4692
4693 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4694 if (ArrayUtils.isEmpty(files)) {
4695 pw.println(" <no ANR has occurred since boot>");
4696 return;
4697 }
4698 // Find the latest file.
4699 File latest = null;
4700 for (File f : files) {
4701 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4702 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004703 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004704 }
4705 pw.print("File: ");
4706 pw.print(latest.getName());
4707 pw.println();
4708 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4709 String line;
4710 while ((line = in.readLine()) != null) {
4711 pw.println(line);
4712 }
4713 } catch (IOException e) {
4714 pw.print("Unable to read: ");
4715 pw.print(e);
4716 pw.println();
4717 }
4718 }
4719
4720 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4721 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4722 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4723 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4724 }
4725
4726 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4727 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4728 pw.println(header);
4729
Wale Ogunwaled32da472018-11-16 07:19:28 -08004730 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004731 dumpPackage);
4732 boolean needSep = printedAnything;
4733
4734 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004735 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004736 " ResumedActivity: ");
4737 if (printed) {
4738 printedAnything = true;
4739 needSep = false;
4740 }
4741
4742 if (dumpPackage == null) {
4743 if (needSep) {
4744 pw.println();
4745 }
4746 printedAnything = true;
4747 mStackSupervisor.dump(pw, " ");
4748 }
4749
4750 if (!printedAnything) {
4751 pw.println(" (nothing)");
4752 }
4753 }
4754
4755 void dumpActivityContainersLocked(PrintWriter pw) {
4756 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004757 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004758 pw.println(" ");
4759 }
4760
4761 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4762 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4763 getActivityStartController().dump(pw, "", dumpPackage);
4764 }
4765
4766 /**
4767 * There are three things that cmd can be:
4768 * - a flattened component name that matches an existing activity
4769 * - the cmd arg isn't the flattened component name of an existing activity:
4770 * dump all activity whose component contains the cmd as a substring
4771 * - A hex number of the ActivityRecord object instance.
4772 *
4773 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4774 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4775 */
4776 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4777 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4778 ArrayList<ActivityRecord> activities;
4779
4780 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004781 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004782 dumpFocusedStackOnly);
4783 }
4784
4785 if (activities.size() <= 0) {
4786 return false;
4787 }
4788
4789 String[] newArgs = new String[args.length - opti];
4790 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4791
4792 TaskRecord lastTask = null;
4793 boolean needSep = false;
4794 for (int i = activities.size() - 1; i >= 0; i--) {
4795 ActivityRecord r = activities.get(i);
4796 if (needSep) {
4797 pw.println();
4798 }
4799 needSep = true;
4800 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004801 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004802 if (lastTask != task) {
4803 lastTask = task;
4804 pw.print("TASK "); pw.print(lastTask.affinity);
4805 pw.print(" id="); pw.print(lastTask.taskId);
4806 pw.print(" userId="); pw.println(lastTask.userId);
4807 if (dumpAll) {
4808 lastTask.dump(pw, " ");
4809 }
4810 }
4811 }
4812 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4813 }
4814 return true;
4815 }
4816
4817 /**
4818 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4819 * there is a thread associated with the activity.
4820 */
4821 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4822 final ActivityRecord r, String[] args, boolean dumpAll) {
4823 String innerPrefix = prefix + " ";
4824 synchronized (mGlobalLock) {
4825 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4826 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4827 pw.print(" pid=");
4828 if (r.hasProcess()) pw.println(r.app.getPid());
4829 else pw.println("(not running)");
4830 if (dumpAll) {
4831 r.dump(pw, innerPrefix);
4832 }
4833 }
4834 if (r.attachedToProcess()) {
4835 // flush anything that is already in the PrintWriter since the thread is going
4836 // to write to the file descriptor directly
4837 pw.flush();
4838 try {
4839 TransferPipe tp = new TransferPipe();
4840 try {
4841 r.app.getThread().dumpActivity(tp.getWriteFd(),
4842 r.appToken, innerPrefix, args);
4843 tp.go(fd);
4844 } finally {
4845 tp.kill();
4846 }
4847 } catch (IOException e) {
4848 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4849 } catch (RemoteException e) {
4850 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4851 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004852 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004853 }
4854
sanryhuang498e77e2018-12-06 14:57:01 +08004855 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4856 boolean testPssMode) {
4857 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4858 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4859 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004860 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004861 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4862 st.toString());
4863 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004864 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4865 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4866 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004867 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4868 testPssMode);
4869 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004870 }
4871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004872 int getCurrentUserId() {
4873 return mAmInternal.getCurrentUserId();
4874 }
4875
4876 private void enforceNotIsolatedCaller(String caller) {
4877 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4878 throw new SecurityException("Isolated process not allowed to call " + caller);
4879 }
4880 }
4881
Wale Ogunwalef6733932018-06-27 05:14:34 -07004882 public Configuration getConfiguration() {
4883 Configuration ci;
4884 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004885 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004886 ci.userSetLocale = false;
4887 }
4888 return ci;
4889 }
4890
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004891 /**
4892 * Current global configuration information. Contains general settings for the entire system,
4893 * also corresponds to the merged configuration of the default display.
4894 */
4895 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004896 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897 }
4898
4899 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4900 boolean initLocale) {
4901 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4902 }
4903
4904 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4905 boolean initLocale, boolean deferResume) {
4906 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4907 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4908 UserHandle.USER_NULL, deferResume);
4909 }
4910
Wale Ogunwale59507092018-10-29 09:00:30 -07004911 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004912 final long origId = Binder.clearCallingIdentity();
4913 try {
4914 synchronized (mGlobalLock) {
4915 updateConfigurationLocked(values, null, false, true, userId,
4916 false /* deferResume */);
4917 }
4918 } finally {
4919 Binder.restoreCallingIdentity(origId);
4920 }
4921 }
4922
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004923 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4924 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4925 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4926 deferResume, null /* result */);
4927 }
4928
4929 /**
4930 * Do either or both things: (1) change the current configuration, and (2)
4931 * make sure the given activity is running with the (now) current
4932 * configuration. Returns true if the activity has been left running, or
4933 * false if <var>starting</var> is being destroyed to match the new
4934 * configuration.
4935 *
4936 * @param userId is only used when persistent parameter is set to true to persist configuration
4937 * for that particular user
4938 */
4939 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4940 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4941 ActivityTaskManagerService.UpdateConfigurationResult result) {
4942 int changes = 0;
4943 boolean kept = true;
4944
4945 if (mWindowManager != null) {
4946 mWindowManager.deferSurfaceLayout();
4947 }
4948 try {
4949 if (values != null) {
4950 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4951 deferResume);
4952 }
4953
4954 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4955 } finally {
4956 if (mWindowManager != null) {
4957 mWindowManager.continueSurfaceLayout();
4958 }
4959 }
4960
4961 if (result != null) {
4962 result.changes = changes;
4963 result.activityRelaunched = !kept;
4964 }
4965 return kept;
4966 }
4967
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004968 /** Update default (global) configuration and notify listeners about changes. */
4969 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4970 boolean persistent, int userId, boolean deferResume) {
4971 mTempConfig.setTo(getGlobalConfiguration());
4972 final int changes = mTempConfig.updateFrom(values);
4973 if (changes == 0) {
4974 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4975 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4976 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4977 // (even if there are no actual changes) to unfreeze the window.
4978 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4979 return 0;
4980 }
4981
4982 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4983 "Updating global configuration to: " + values);
4984
4985 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4986 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4987 values.colorMode,
4988 values.densityDpi,
4989 values.fontScale,
4990 values.hardKeyboardHidden,
4991 values.keyboard,
4992 values.keyboardHidden,
4993 values.mcc,
4994 values.mnc,
4995 values.navigation,
4996 values.navigationHidden,
4997 values.orientation,
4998 values.screenHeightDp,
4999 values.screenLayout,
5000 values.screenWidthDp,
5001 values.smallestScreenWidthDp,
5002 values.touchscreen,
5003 values.uiMode);
5004
5005
5006 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5007 final LocaleList locales = values.getLocales();
5008 int bestLocaleIndex = 0;
5009 if (locales.size() > 1) {
5010 if (mSupportedSystemLocales == null) {
5011 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5012 }
5013 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5014 }
5015 SystemProperties.set("persist.sys.locale",
5016 locales.get(bestLocaleIndex).toLanguageTag());
5017 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005018
5019 final Message m = PooledLambda.obtainMessage(
5020 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5021 locales.get(bestLocaleIndex));
5022 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005023 }
5024
Yunfan Chen75157d72018-07-27 14:47:21 +09005025 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005026
5027 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005028 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005029
5030 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5031 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005032 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005033
5034 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005035 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005036
5037 AttributeCache ac = AttributeCache.instance();
5038 if (ac != null) {
5039 ac.updateConfiguration(mTempConfig);
5040 }
5041
5042 // Make sure all resources in our process are updated right now, so that anyone who is going
5043 // to retrieve resource values after we return will be sure to get the new ones. This is
5044 // especially important during boot, where the first config change needs to guarantee all
5045 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005046 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005047
5048 // We need another copy of global config because we're scheduling some calls instead of
5049 // running them in place. We need to be sure that object we send will be handled unchanged.
5050 final Configuration configCopy = new Configuration(mTempConfig);
5051 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005052 final Message msg = PooledLambda.obtainMessage(
5053 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5054 this, userId, configCopy);
5055 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005056 }
5057
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005058 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005059 final int pid = mPidMap.keyAt(i);
5060 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005061 if (DEBUG_CONFIGURATION) {
5062 Slog.v(TAG_CONFIGURATION, "Update process config of "
5063 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005064 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005065 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005066 }
5067
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005068 final Message msg = PooledLambda.obtainMessage(
5069 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5070 mAmInternal, changes, initLocale);
5071 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072
5073 // Override configuration of the default display duplicates global config, so we need to
5074 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005075 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076 DEFAULT_DISPLAY);
5077
5078 return changes;
5079 }
5080
5081 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5082 boolean deferResume, int displayId) {
5083 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5084 displayId, null /* result */);
5085 }
5086
5087 /**
5088 * Updates override configuration specific for the selected display. If no config is provided,
5089 * new one will be computed in WM based on current display info.
5090 */
5091 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5092 ActivityRecord starting, boolean deferResume, int displayId,
5093 ActivityTaskManagerService.UpdateConfigurationResult result) {
5094 int changes = 0;
5095 boolean kept = true;
5096
5097 if (mWindowManager != null) {
5098 mWindowManager.deferSurfaceLayout();
5099 }
5100 try {
5101 if (values != null) {
5102 if (displayId == DEFAULT_DISPLAY) {
5103 // Override configuration of the default display duplicates global config, so
5104 // we're calling global config update instead for default display. It will also
5105 // apply the correct override config.
5106 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5107 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5108 } else {
5109 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5110 }
5111 }
5112
5113 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5114 } finally {
5115 if (mWindowManager != null) {
5116 mWindowManager.continueSurfaceLayout();
5117 }
5118 }
5119
5120 if (result != null) {
5121 result.changes = changes;
5122 result.activityRelaunched = !kept;
5123 }
5124 return kept;
5125 }
5126
5127 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5128 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005129 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130 final int changes = mTempConfig.updateFrom(values);
5131 if (changes != 0) {
5132 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5133 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005134 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135
5136 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5137 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005138 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139
Wale Ogunwale5c918702018-10-18 11:06:33 -07005140 // Post message to start process to avoid possible deadlock of calling into AMS with
5141 // the ATMS lock held.
5142 final Message msg = PooledLambda.obtainMessage(
5143 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5144 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5145 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005146 }
5147 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005148 return changes;
5149 }
5150
Wale Ogunwalef6733932018-06-27 05:14:34 -07005151 private void updateEventDispatchingLocked(boolean booted) {
5152 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5153 }
5154
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005155 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5156 final ContentResolver resolver = mContext.getContentResolver();
5157 Settings.System.putConfigurationForUser(resolver, config, userId);
5158 }
5159
5160 private void sendLocaleToMountDaemonMsg(Locale l) {
5161 try {
5162 IBinder service = ServiceManager.getService("mount");
5163 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5164 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5165 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5166 } catch (RemoteException e) {
5167 Log.e(TAG, "Error storing locale for decryption UI", e);
5168 }
5169 }
5170
Alison Cichowlas3e340502018-08-07 17:15:01 -04005171 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5172 mStartActivitySources.remove(permissionToken);
5173 mExpiredStartAsCallerTokens.add(permissionToken);
5174 }
5175
5176 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5177 mExpiredStartAsCallerTokens.remove(permissionToken);
5178 }
5179
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005180 boolean isActivityStartsLoggingEnabled() {
5181 return mAmInternal.isActivityStartsLoggingEnabled();
5182 }
5183
Michal Karpinski8596ded2018-11-14 14:43:48 +00005184 boolean isBackgroundActivityStartsEnabled() {
5185 return mAmInternal.isBackgroundActivityStartsEnabled();
5186 }
5187
Wale Ogunwalef6733932018-06-27 05:14:34 -07005188 void enableScreenAfterBoot(boolean booted) {
5189 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5190 SystemClock.uptimeMillis());
5191 mWindowManager.enableScreenAfterBoot();
5192
5193 synchronized (mGlobalLock) {
5194 updateEventDispatchingLocked(booted);
5195 }
5196 }
5197
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005198 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5199 if (r == null || !r.hasProcess()) {
5200 return KEY_DISPATCHING_TIMEOUT_MS;
5201 }
5202 return getInputDispatchingTimeoutLocked(r.app);
5203 }
5204
5205 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005206 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005207 }
5208
Wale Ogunwalef6733932018-06-27 05:14:34 -07005209 /**
5210 * Decide based on the configuration whether we should show the ANR,
5211 * crash, etc dialogs. The idea is that if there is no affordance to
5212 * press the on-screen buttons, or the user experience would be more
5213 * greatly impacted than the crash itself, we shouldn't show the dialog.
5214 *
5215 * A thought: SystemUI might also want to get told about this, the Power
5216 * dialog / global actions also might want different behaviors.
5217 */
5218 private void updateShouldShowDialogsLocked(Configuration config) {
5219 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5220 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5221 && config.navigation == Configuration.NAVIGATION_NONAV);
5222 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5223 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5224 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5225 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5226 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5227 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5228 HIDE_ERROR_DIALOGS, 0) != 0;
5229 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5230 }
5231
5232 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5233 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5234 FONT_SCALE, 1.0f, userId);
5235
5236 synchronized (this) {
5237 if (getGlobalConfiguration().fontScale == scaleFactor) {
5238 return;
5239 }
5240
5241 final Configuration configuration
5242 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5243 configuration.fontScale = scaleFactor;
5244 updatePersistentConfiguration(configuration, userId);
5245 }
5246 }
5247
5248 // Actually is sleeping or shutting down or whatever else in the future
5249 // is an inactive state.
5250 boolean isSleepingOrShuttingDownLocked() {
5251 return isSleepingLocked() || mShuttingDown;
5252 }
5253
5254 boolean isSleepingLocked() {
5255 return mSleeping;
5256 }
5257
Riddle Hsu16567132018-08-16 21:37:47 +08005258 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005259 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005260 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005261 if (task.isActivityTypeStandard()) {
5262 if (mCurAppTimeTracker != r.appTimeTracker) {
5263 // We are switching app tracking. Complete the current one.
5264 if (mCurAppTimeTracker != null) {
5265 mCurAppTimeTracker.stop();
5266 mH.obtainMessage(
5267 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005268 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005269 mCurAppTimeTracker = null;
5270 }
5271 if (r.appTimeTracker != null) {
5272 mCurAppTimeTracker = r.appTimeTracker;
5273 startTimeTrackingFocusedActivityLocked();
5274 }
5275 } else {
5276 startTimeTrackingFocusedActivityLocked();
5277 }
5278 } else {
5279 r.appTimeTracker = null;
5280 }
5281 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5282 // TODO: Probably not, because we don't want to resume voice on switching
5283 // back to this activity
5284 if (task.voiceInteractor != null) {
5285 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5286 } else {
5287 finishRunningVoiceLocked();
5288
5289 if (mLastResumedActivity != null) {
5290 final IVoiceInteractionSession session;
5291
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005292 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005293 if (lastResumedActivityTask != null
5294 && lastResumedActivityTask.voiceSession != null) {
5295 session = lastResumedActivityTask.voiceSession;
5296 } else {
5297 session = mLastResumedActivity.voiceSession;
5298 }
5299
5300 if (session != null) {
5301 // We had been in a voice interaction session, but now focused has
5302 // move to something different. Just finish the session, we can't
5303 // return to it and retain the proper state and synchronization with
5304 // the voice interaction service.
5305 finishVoiceTask(session);
5306 }
5307 }
5308 }
5309
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005310 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5311 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005312 }
5313 updateResumedAppTrace(r);
5314 mLastResumedActivity = r;
5315
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005316 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005317
5318 applyUpdateLockStateLocked(r);
5319 applyUpdateVrModeLocked(r);
5320
5321 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005322 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005323 r == null ? "NULL" : r.shortComponentName,
5324 reason);
5325 }
5326
5327 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5328 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005329 final ActivityTaskManagerInternal.SleepToken token =
5330 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005331 updateSleepIfNeededLocked();
5332 return token;
5333 }
5334 }
5335
5336 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005337 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005338 final boolean wasSleeping = mSleeping;
5339 boolean updateOomAdj = false;
5340
5341 if (!shouldSleep) {
5342 // If wasSleeping is true, we need to wake up activity manager state from when
5343 // we started sleeping. In either case, we need to apply the sleep tokens, which
5344 // will wake up stacks or put them to sleep as appropriate.
5345 if (wasSleeping) {
5346 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005347 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5348 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005349 startTimeTrackingFocusedActivityLocked();
5350 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5351 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5352 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005353 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 if (wasSleeping) {
5355 updateOomAdj = true;
5356 }
5357 } else if (!mSleeping && shouldSleep) {
5358 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005359 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5360 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005361 if (mCurAppTimeTracker != null) {
5362 mCurAppTimeTracker.stop();
5363 }
5364 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5365 mStackSupervisor.goingToSleepLocked();
5366 updateResumedAppTrace(null /* resumed */);
5367 updateOomAdj = true;
5368 }
5369 if (updateOomAdj) {
5370 mH.post(mAmInternal::updateOomAdj);
5371 }
5372 }
5373
5374 void updateOomAdj() {
5375 mH.post(mAmInternal::updateOomAdj);
5376 }
5377
Wale Ogunwale53783742018-09-16 10:21:51 -07005378 void updateCpuStats() {
5379 mH.post(mAmInternal::updateCpuStats);
5380 }
5381
Hui Yu03d12402018-12-06 18:00:37 -08005382 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5383 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005384 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5385 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005386 mH.sendMessage(m);
5387 }
5388
Hui Yu03d12402018-12-06 18:00:37 -08005389 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005390 ComponentName taskRoot = null;
5391 final TaskRecord task = activity.getTaskRecord();
5392 if (task != null) {
5393 final ActivityRecord rootActivity = task.getRootActivity();
5394 if (rootActivity != null) {
5395 taskRoot = rootActivity.mActivityComponent;
5396 }
5397 }
5398
Hui Yu03d12402018-12-06 18:00:37 -08005399 final Message m = PooledLambda.obtainMessage(
5400 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005401 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005402 mH.sendMessage(m);
5403 }
5404
Wale Ogunwale53783742018-09-16 10:21:51 -07005405 void setBooting(boolean booting) {
5406 mAmInternal.setBooting(booting);
5407 }
5408
5409 boolean isBooting() {
5410 return mAmInternal.isBooting();
5411 }
5412
5413 void setBooted(boolean booted) {
5414 mAmInternal.setBooted(booted);
5415 }
5416
5417 boolean isBooted() {
5418 return mAmInternal.isBooted();
5419 }
5420
5421 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5422 mH.post(() -> {
5423 if (finishBooting) {
5424 mAmInternal.finishBooting();
5425 }
5426 if (enableScreen) {
5427 mInternal.enableScreenAfterBoot(isBooted());
5428 }
5429 });
5430 }
5431
5432 void setHeavyWeightProcess(ActivityRecord root) {
5433 mHeavyWeightProcess = root.app;
5434 final Message m = PooledLambda.obtainMessage(
5435 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005436 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005437 mH.sendMessage(m);
5438 }
5439
5440 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5441 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5442 return;
5443 }
5444
5445 mHeavyWeightProcess = null;
5446 final Message m = PooledLambda.obtainMessage(
5447 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5448 proc.mUserId);
5449 mH.sendMessage(m);
5450 }
5451
5452 private void cancelHeavyWeightProcessNotification(int userId) {
5453 final INotificationManager inm = NotificationManager.getService();
5454 if (inm == null) {
5455 return;
5456 }
5457 try {
5458 inm.cancelNotificationWithTag("android", null,
5459 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5460 } catch (RuntimeException e) {
5461 Slog.w(TAG, "Error canceling notification for service", e);
5462 } catch (RemoteException e) {
5463 }
5464
5465 }
5466
5467 private void postHeavyWeightProcessNotification(
5468 WindowProcessController proc, Intent intent, int userId) {
5469 if (proc == null) {
5470 return;
5471 }
5472
5473 final INotificationManager inm = NotificationManager.getService();
5474 if (inm == null) {
5475 return;
5476 }
5477
5478 try {
5479 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5480 String text = mContext.getString(R.string.heavy_weight_notification,
5481 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5482 Notification notification =
5483 new Notification.Builder(context,
5484 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5485 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5486 .setWhen(0)
5487 .setOngoing(true)
5488 .setTicker(text)
5489 .setColor(mContext.getColor(
5490 com.android.internal.R.color.system_notification_accent_color))
5491 .setContentTitle(text)
5492 .setContentText(
5493 mContext.getText(R.string.heavy_weight_notification_detail))
5494 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5495 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5496 new UserHandle(userId)))
5497 .build();
5498 try {
5499 inm.enqueueNotificationWithTag("android", "android", null,
5500 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5501 } catch (RuntimeException e) {
5502 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5503 } catch (RemoteException e) {
5504 }
5505 } catch (PackageManager.NameNotFoundException e) {
5506 Slog.w(TAG, "Unable to create context for heavy notification", e);
5507 }
5508
5509 }
5510
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005511 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5512 IBinder token, String resultWho, int requestCode, Intent[] intents,
5513 String[] resolvedTypes, int flags, Bundle bOptions) {
5514
5515 ActivityRecord activity = null;
5516 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5517 activity = ActivityRecord.isInStackLocked(token);
5518 if (activity == null) {
5519 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5520 return null;
5521 }
5522 if (activity.finishing) {
5523 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5524 return null;
5525 }
5526 }
5527
5528 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5529 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5530 bOptions);
5531 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5532 if (noCreate) {
5533 return rec;
5534 }
5535 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5536 if (activity.pendingResults == null) {
5537 activity.pendingResults = new HashSet<>();
5538 }
5539 activity.pendingResults.add(rec.ref);
5540 }
5541 return rec;
5542 }
5543
Andrii Kulian52d255c2018-07-13 11:32:19 -07005544 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005546 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5548 mCurAppTimeTracker.start(resumedActivity.packageName);
5549 }
5550 }
5551
5552 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5553 if (mTracedResumedActivity != null) {
5554 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5555 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5556 }
5557 if (resumed != null) {
5558 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5559 constructResumedTraceName(resumed.packageName), 0);
5560 }
5561 mTracedResumedActivity = resumed;
5562 }
5563
5564 private String constructResumedTraceName(String packageName) {
5565 return "focused app: " + packageName;
5566 }
5567
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005568 /** Applies latest configuration and/or visibility updates if needed. */
5569 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5570 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005571 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005572 // mainStack is null during startup.
5573 if (mainStack != null) {
5574 if (changes != 0 && starting == null) {
5575 // If the configuration changed, and the caller is not already
5576 // in the process of starting an activity, then find the top
5577 // activity to check if its configuration needs to change.
5578 starting = mainStack.topRunningActivityLocked();
5579 }
5580
5581 if (starting != null) {
5582 kept = starting.ensureActivityConfiguration(changes,
5583 false /* preserveWindow */);
5584 // And we need to make sure at this point that all other activities
5585 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005586 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005587 !PRESERVE_WINDOWS);
5588 }
5589 }
5590
5591 return kept;
5592 }
5593
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005594 void scheduleAppGcsLocked() {
5595 mH.post(() -> mAmInternal.scheduleAppGcs());
5596 }
5597
Wale Ogunwale53783742018-09-16 10:21:51 -07005598 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5599 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5600 }
5601
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005602 /**
5603 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5604 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5605 * on demand.
5606 */
5607 IPackageManager getPackageManager() {
5608 return AppGlobals.getPackageManager();
5609 }
5610
5611 PackageManagerInternal getPackageManagerInternalLocked() {
5612 if (mPmInternal == null) {
5613 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5614 }
5615 return mPmInternal;
5616 }
5617
Wale Ogunwale008163e2018-07-23 23:11:08 -07005618 AppWarnings getAppWarningsLocked() {
5619 return mAppWarnings;
5620 }
5621
Wale Ogunwale214f3482018-10-04 11:00:47 -07005622 Intent getHomeIntent() {
5623 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5624 intent.setComponent(mTopComponent);
5625 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5626 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5627 intent.addCategory(Intent.CATEGORY_HOME);
5628 }
5629 return intent;
5630 }
5631
Chilun2ef71f72018-11-16 17:57:15 +08005632 /**
5633 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5634 * activities.
5635 *
5636 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5637 * component defined in config_secondaryHomeComponent.
5638 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5639 */
5640 Intent getSecondaryHomeIntent(String preferredPackage) {
5641 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5642 if (preferredPackage == null) {
5643 // Using the component stored in config if no package name.
5644 final String secondaryHomeComponent = mContext.getResources().getString(
5645 com.android.internal.R.string.config_secondaryHomeComponent);
5646 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5647 } else {
5648 intent.setPackage(preferredPackage);
5649 }
5650 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5651 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5652 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5653 }
5654 return intent;
5655 }
5656
Wale Ogunwale214f3482018-10-04 11:00:47 -07005657 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5658 if (info == null) return null;
5659 ApplicationInfo newInfo = new ApplicationInfo(info);
5660 newInfo.initForUser(userId);
5661 return newInfo;
5662 }
5663
Wale Ogunwale9c103022018-10-18 07:44:54 -07005664 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005665 if (uid == SYSTEM_UID) {
5666 // The system gets to run in any process. If there are multiple processes with the same
5667 // uid, just pick the first (this should never happen).
5668 final SparseArray<WindowProcessController> procs =
5669 mProcessNames.getMap().get(processName);
5670 if (procs == null) return null;
5671 final int procCount = procs.size();
5672 for (int i = 0; i < procCount; i++) {
5673 final int procUid = procs.keyAt(i);
5674 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5675 // Don't use an app process or different user process for system component.
5676 continue;
5677 }
5678 return procs.valueAt(i);
5679 }
5680 }
5681
5682 return mProcessNames.get(processName, uid);
5683 }
5684
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005685 WindowProcessController getProcessController(IApplicationThread thread) {
5686 if (thread == null) {
5687 return null;
5688 }
5689
5690 final IBinder threadBinder = thread.asBinder();
5691 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5692 for (int i = pmap.size()-1; i >= 0; i--) {
5693 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5694 for (int j = procs.size() - 1; j >= 0; j--) {
5695 final WindowProcessController proc = procs.valueAt(j);
5696 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5697 return proc;
5698 }
5699 }
5700 }
5701
5702 return null;
5703 }
5704
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005705 WindowProcessController getProcessController(int pid, int uid) {
5706 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5707 for (int i = pmap.size()-1; i >= 0; i--) {
5708 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5709 for (int j = procs.size() - 1; j >= 0; j--) {
5710 final WindowProcessController proc = procs.valueAt(j);
5711 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5712 return proc;
5713 }
5714 }
5715 }
5716 return null;
5717 }
5718
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005719 int getUidStateLocked(int uid) {
5720 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5721 }
5722
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005723 boolean isUidForeground(int uid) {
5724 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5725 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5726 }
5727
Wale Ogunwale9de19442018-10-18 19:05:03 -07005728 /**
5729 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5730 * the whitelist
5731 */
5732 String getPendingTempWhitelistTagForUidLocked(int uid) {
5733 return mPendingTempWhitelist.get(uid);
5734 }
5735
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005736 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5737 if (true || Build.IS_USER) {
5738 return;
5739 }
5740
5741 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5742 StrictMode.allowThreadDiskWrites();
5743 try {
5744 File tracesDir = new File("/data/anr");
5745 File tracesFile = null;
5746 try {
5747 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5748
5749 StringBuilder sb = new StringBuilder();
5750 Time tobj = new Time();
5751 tobj.set(System.currentTimeMillis());
5752 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5753 sb.append(": ");
5754 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5755 sb.append(" since ");
5756 sb.append(msg);
5757 FileOutputStream fos = new FileOutputStream(tracesFile);
5758 fos.write(sb.toString().getBytes());
5759 if (app == null) {
5760 fos.write("\n*** No application process!".getBytes());
5761 }
5762 fos.close();
5763 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5764 } catch (IOException e) {
5765 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5766 return;
5767 }
5768
5769 if (app != null && app.getPid() > 0) {
5770 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5771 firstPids.add(app.getPid());
5772 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5773 }
5774
5775 File lastTracesFile = null;
5776 File curTracesFile = null;
5777 for (int i=9; i>=0; i--) {
5778 String name = String.format(Locale.US, "slow%02d.txt", i);
5779 curTracesFile = new File(tracesDir, name);
5780 if (curTracesFile.exists()) {
5781 if (lastTracesFile != null) {
5782 curTracesFile.renameTo(lastTracesFile);
5783 } else {
5784 curTracesFile.delete();
5785 }
5786 }
5787 lastTracesFile = curTracesFile;
5788 }
5789 tracesFile.renameTo(curTracesFile);
5790 } finally {
5791 StrictMode.setThreadPolicy(oldPolicy);
5792 }
5793 }
5794
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005795 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005796 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005797
5798
Wale Ogunwale98875612018-10-12 07:53:02 -07005799 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5800 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005801
Riddle Hsud93a6c42018-11-29 21:50:06 +08005802 H(Looper looper) {
5803 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005804 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005805
5806 @Override
5807 public void handleMessage(Message msg) {
5808 switch (msg.what) {
5809 case REPORT_TIME_TRACKER_MSG: {
5810 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5811 tracker.deliverResult(mContext);
5812 } break;
5813 }
5814 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005815 }
5816
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005817 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005818 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005819
5820 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005821 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005823
5824 @Override
5825 public void handleMessage(Message msg) {
5826 switch (msg.what) {
5827 case DISMISS_DIALOG_UI_MSG: {
5828 final Dialog d = (Dialog) msg.obj;
5829 d.dismiss();
5830 break;
5831 }
5832 }
5833 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005834 }
5835
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005836 final class LocalService extends ActivityTaskManagerInternal {
5837 @Override
5838 public SleepToken acquireSleepToken(String tag, int displayId) {
5839 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005840 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005841 }
5842
5843 @Override
5844 public ComponentName getHomeActivityForUser(int userId) {
5845 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005846 final ActivityRecord homeActivity =
5847 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005848 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005849 }
5850 }
5851
5852 @Override
5853 public void onLocalVoiceInteractionStarted(IBinder activity,
5854 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5855 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005856 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005857 }
5858 }
5859
5860 @Override
5861 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5862 synchronized (mGlobalLock) {
5863 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5864 reasons, timestamp);
5865 }
5866 }
5867
5868 @Override
5869 public void notifyAppTransitionFinished() {
5870 synchronized (mGlobalLock) {
5871 mStackSupervisor.notifyAppTransitionDone();
5872 }
5873 }
5874
5875 @Override
5876 public void notifyAppTransitionCancelled() {
5877 synchronized (mGlobalLock) {
5878 mStackSupervisor.notifyAppTransitionDone();
5879 }
5880 }
5881
5882 @Override
5883 public List<IBinder> getTopVisibleActivities() {
5884 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005885 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005886 }
5887 }
5888
5889 @Override
5890 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5891 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005892 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005893 }
5894 }
5895
5896 @Override
5897 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5898 Bundle bOptions) {
5899 Preconditions.checkNotNull(intents, "intents");
5900 final String[] resolvedTypes = new String[intents.length];
5901
5902 // UID of the package on user userId.
5903 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5904 // packageUid may not be initialized.
5905 int packageUid = 0;
5906 final long ident = Binder.clearCallingIdentity();
5907
5908 try {
5909 for (int i = 0; i < intents.length; i++) {
5910 resolvedTypes[i] =
5911 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5912 }
5913
5914 packageUid = AppGlobals.getPackageManager().getPackageUid(
5915 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5916 } catch (RemoteException e) {
5917 // Shouldn't happen.
5918 } finally {
5919 Binder.restoreCallingIdentity(ident);
5920 }
5921
5922 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005923 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005924 packageUid, packageName,
5925 intents, resolvedTypes, null /* resultTo */,
5926 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005927 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5928 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 }
5930 }
5931
5932 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005933 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5934 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5935 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5936 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005937 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005938 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005939 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5940 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5941 userId, validateIncomingUser, originatingPendingIntent,
5942 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005943 }
5944 }
5945
5946 @Override
5947 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5948 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5949 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5950 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005951 PendingIntentRecord originatingPendingIntent,
5952 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005953 synchronized (mGlobalLock) {
5954 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5955 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5956 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005957 validateIncomingUser, originatingPendingIntent,
5958 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005959 }
5960 }
5961
5962 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005963 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5964 Intent intent, Bundle options, int userId) {
5965 return ActivityTaskManagerService.this.startActivityAsUser(
5966 caller, callerPacakge, intent,
5967 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5968 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5969 false /*validateIncomingUser*/);
5970 }
5971
5972 @Override
lumark588a3e82018-07-20 18:53:54 +08005973 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005974 synchronized (mGlobalLock) {
5975
5976 // We might change the visibilities here, so prepare an empty app transition which
5977 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005978 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005979 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005980 if (activityDisplay == null) {
5981 return;
5982 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005983 final DisplayContent dc = activityDisplay.mDisplayContent;
5984 final boolean wasTransitionSet =
5985 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005986 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005987 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005988 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005989 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005990
5991 // If there was a transition set already we don't want to interfere with it as we
5992 // might be starting it too early.
5993 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005994 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005995 }
5996 }
5997 if (callback != null) {
5998 callback.run();
5999 }
6000 }
6001
6002 @Override
6003 public void notifyKeyguardTrustedChanged() {
6004 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006005 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006006 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006007 }
6008 }
6009 }
6010
6011 /**
6012 * Called after virtual display Id is updated by
6013 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6014 * {@param vrVr2dDisplayId}.
6015 */
6016 @Override
6017 public void setVr2dDisplayId(int vr2dDisplayId) {
6018 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6019 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006020 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006021 }
6022 }
6023
6024 @Override
6025 public void setFocusedActivity(IBinder token) {
6026 synchronized (mGlobalLock) {
6027 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6028 if (r == null) {
6029 throw new IllegalArgumentException(
6030 "setFocusedActivity: No activity record matching token=" + token);
6031 }
Louis Chang19443452018-10-09 12:10:21 +08006032 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006033 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006034 }
6035 }
6036 }
6037
6038 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006040 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006041 }
6042
6043 @Override
6044 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006045 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006046 }
6047
6048 @Override
6049 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006050 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006051 }
6052
6053 @Override
6054 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6055 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6056 }
6057
6058 @Override
6059 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006060 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006062
6063 @Override
6064 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6065 synchronized (mGlobalLock) {
6066 mActiveVoiceInteractionServiceComponent = component;
6067 }
6068 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006069
6070 @Override
6071 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6072 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6073 return;
6074 }
6075 synchronized (mGlobalLock) {
6076 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6077 if (types == null) {
6078 if (uid < 0) {
6079 return;
6080 }
6081 types = new ArrayMap<>();
6082 mAllowAppSwitchUids.put(userId, types);
6083 }
6084 if (uid < 0) {
6085 types.remove(type);
6086 } else {
6087 types.put(type, uid);
6088 }
6089 }
6090 }
6091
6092 @Override
6093 public void onUserStopped(int userId) {
6094 synchronized (mGlobalLock) {
6095 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6096 mAllowAppSwitchUids.remove(userId);
6097 }
6098 }
6099
6100 @Override
6101 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6102 synchronized (mGlobalLock) {
6103 return ActivityTaskManagerService.this.isGetTasksAllowed(
6104 caller, callingPid, callingUid);
6105 }
6106 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006107
6108 @Override
6109 public void onProcessAdded(WindowProcessController proc) {
6110 synchronized (mGlobalLock) {
6111 mProcessNames.put(proc.mName, proc.mUid, proc);
6112 }
6113 }
6114
6115 @Override
6116 public void onProcessRemoved(String name, int uid) {
6117 synchronized (mGlobalLock) {
6118 mProcessNames.remove(name, uid);
6119 }
6120 }
6121
6122 @Override
6123 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6124 synchronized (mGlobalLock) {
6125 if (proc == mHomeProcess) {
6126 mHomeProcess = null;
6127 }
6128 if (proc == mPreviousProcess) {
6129 mPreviousProcess = null;
6130 }
6131 }
6132 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006133
6134 @Override
6135 public int getTopProcessState() {
6136 synchronized (mGlobalLock) {
6137 return mTopProcessState;
6138 }
6139 }
6140
6141 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006142 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6143 synchronized (mGlobalLock) {
6144 return proc == mHeavyWeightProcess;
6145 }
6146 }
6147
6148 @Override
6149 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6150 synchronized (mGlobalLock) {
6151 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6152 }
6153 }
6154
6155 @Override
6156 public void finishHeavyWeightApp() {
6157 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006158 if (mHeavyWeightProcess != null) {
6159 mHeavyWeightProcess.finishActivities();
6160 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006161 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6162 mHeavyWeightProcess);
6163 }
6164 }
6165
6166 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006167 public boolean isSleeping() {
6168 synchronized (mGlobalLock) {
6169 return isSleepingLocked();
6170 }
6171 }
6172
6173 @Override
6174 public boolean isShuttingDown() {
6175 synchronized (mGlobalLock) {
6176 return mShuttingDown;
6177 }
6178 }
6179
6180 @Override
6181 public boolean shuttingDown(boolean booted, int timeout) {
6182 synchronized (mGlobalLock) {
6183 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006184 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006185 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006186 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006187 return mStackSupervisor.shutdownLocked(timeout);
6188 }
6189 }
6190
6191 @Override
6192 public void enableScreenAfterBoot(boolean booted) {
6193 synchronized (mGlobalLock) {
6194 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6195 SystemClock.uptimeMillis());
6196 mWindowManager.enableScreenAfterBoot();
6197 updateEventDispatchingLocked(booted);
6198 }
6199 }
6200
6201 @Override
6202 public boolean showStrictModeViolationDialog() {
6203 synchronized (mGlobalLock) {
6204 return mShowDialogs && !mSleeping && !mShuttingDown;
6205 }
6206 }
6207
6208 @Override
6209 public void showSystemReadyErrorDialogsIfNeeded() {
6210 synchronized (mGlobalLock) {
6211 try {
6212 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6213 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6214 + " data partition or your device will be unstable.");
6215 mUiHandler.post(() -> {
6216 if (mShowDialogs) {
6217 AlertDialog d = new BaseErrorDialog(mUiContext);
6218 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6219 d.setCancelable(false);
6220 d.setTitle(mUiContext.getText(R.string.android_system_label));
6221 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6222 d.setButton(DialogInterface.BUTTON_POSITIVE,
6223 mUiContext.getText(R.string.ok),
6224 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6225 d.show();
6226 }
6227 });
6228 }
6229 } catch (RemoteException e) {
6230 }
6231
6232 if (!Build.isBuildConsistent()) {
6233 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6234 mUiHandler.post(() -> {
6235 if (mShowDialogs) {
6236 AlertDialog d = new BaseErrorDialog(mUiContext);
6237 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6238 d.setCancelable(false);
6239 d.setTitle(mUiContext.getText(R.string.android_system_label));
6240 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6241 d.setButton(DialogInterface.BUTTON_POSITIVE,
6242 mUiContext.getText(R.string.ok),
6243 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6244 d.show();
6245 }
6246 });
6247 }
6248 }
6249 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006250
6251 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006252 public void onProcessMapped(int pid, WindowProcessController proc) {
6253 synchronized (mGlobalLock) {
6254 mPidMap.put(pid, proc);
6255 }
6256 }
6257
6258 @Override
6259 public void onProcessUnMapped(int pid) {
6260 synchronized (mGlobalLock) {
6261 mPidMap.remove(pid);
6262 }
6263 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006264
6265 @Override
6266 public void onPackageDataCleared(String name) {
6267 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006268 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006269 mAppWarnings.onPackageDataCleared(name);
6270 }
6271 }
6272
6273 @Override
6274 public void onPackageUninstalled(String name) {
6275 synchronized (mGlobalLock) {
6276 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006277 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006278 }
6279 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006280
6281 @Override
6282 public void onPackageAdded(String name, boolean replacing) {
6283 synchronized (mGlobalLock) {
6284 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6285 }
6286 }
6287
6288 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006289 public void onPackageReplaced(ApplicationInfo aInfo) {
6290 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006291 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006292 }
6293 }
6294
6295 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006296 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6297 synchronized (mGlobalLock) {
6298 return compatibilityInfoForPackageLocked(ai);
6299 }
6300 }
6301
Yunfan Chen75157d72018-07-27 14:47:21 +09006302 /**
6303 * Set the corresponding display information for the process global configuration. To be
6304 * called when we need to show IME on a different display.
6305 *
6306 * @param pid The process id associated with the IME window.
6307 * @param displayId The ID of the display showing the IME.
6308 */
6309 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006310 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006311 if (pid == MY_PID || pid < 0) {
6312 if (DEBUG_CONFIGURATION) {
6313 Slog.w(TAG,
6314 "Trying to update display configuration for system/invalid process.");
6315 }
6316 return;
6317 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006318 synchronized (mGlobalLock) {
6319 final ActivityDisplay activityDisplay =
6320 mRootActivityContainer.getActivityDisplay(displayId);
6321 if (activityDisplay == null) {
6322 // Call might come when display is not yet added or has been removed.
6323 if (DEBUG_CONFIGURATION) {
6324 Slog.w(TAG, "Trying to update display configuration for non-existing "
6325 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006326 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006327 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006328 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006329 final WindowProcessController process = mPidMap.get(pid);
6330 if (process == null) {
6331 if (DEBUG_CONFIGURATION) {
6332 Slog.w(TAG, "Trying to update display configuration for invalid "
6333 + "process, pid=" + pid);
6334 }
6335 return;
6336 }
6337 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6338 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006339 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006340
6341 @Override
6342 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6343 int requestCode, int resultCode, Intent data) {
6344 synchronized (mGlobalLock) {
6345 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006346 if (r != null && r.getActivityStack() != null) {
6347 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6348 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006349 }
6350 }
6351 }
6352
6353 @Override
6354 public void clearPendingResultForActivity(IBinder activityToken,
6355 WeakReference<PendingIntentRecord> pir) {
6356 synchronized (mGlobalLock) {
6357 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6358 if (r != null && r.pendingResults != null) {
6359 r.pendingResults.remove(pir);
6360 }
6361 }
6362 }
6363
6364 @Override
6365 public IIntentSender getIntentSender(int type, String packageName,
6366 int callingUid, int userId, IBinder token, String resultWho,
6367 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6368 Bundle bOptions) {
6369 synchronized (mGlobalLock) {
6370 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6371 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6372 }
6373 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006374
6375 @Override
6376 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6377 synchronized (mGlobalLock) {
6378 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6379 if (r == null) {
6380 return null;
6381 }
6382 if (r.mServiceConnectionsHolder == null) {
6383 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6384 ActivityTaskManagerService.this, r);
6385 }
6386
6387 return r.mServiceConnectionsHolder;
6388 }
6389 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006390
6391 @Override
6392 public Intent getHomeIntent() {
6393 synchronized (mGlobalLock) {
6394 return ActivityTaskManagerService.this.getHomeIntent();
6395 }
6396 }
6397
6398 @Override
6399 public boolean startHomeActivity(int userId, String reason) {
6400 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006401 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006402 }
6403 }
6404
6405 @Override
6406 public boolean startHomeOnAllDisplays(int userId, String reason) {
6407 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006408 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006409 }
6410 }
6411
6412 @Override
6413 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6414 synchronized (mGlobalLock) {
6415 if (mFactoryTest == FACTORY_TEST_OFF) {
6416 return false;
6417 }
6418 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6419 && wpc.mName.equals(mTopComponent.getPackageName())) {
6420 return true;
6421 }
6422 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6423 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6424 }
6425 }
6426
6427 @Override
6428 public void updateTopComponentForFactoryTest() {
6429 synchronized (mGlobalLock) {
6430 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6431 return;
6432 }
6433 final ResolveInfo ri = mContext.getPackageManager()
6434 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6435 final CharSequence errorMsg;
6436 if (ri != null) {
6437 final ActivityInfo ai = ri.activityInfo;
6438 final ApplicationInfo app = ai.applicationInfo;
6439 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6440 mTopAction = Intent.ACTION_FACTORY_TEST;
6441 mTopData = null;
6442 mTopComponent = new ComponentName(app.packageName, ai.name);
6443 errorMsg = null;
6444 } else {
6445 errorMsg = mContext.getResources().getText(
6446 com.android.internal.R.string.factorytest_not_system);
6447 }
6448 } else {
6449 errorMsg = mContext.getResources().getText(
6450 com.android.internal.R.string.factorytest_no_action);
6451 }
6452 if (errorMsg == null) {
6453 return;
6454 }
6455
6456 mTopAction = null;
6457 mTopData = null;
6458 mTopComponent = null;
6459 mUiHandler.post(() -> {
6460 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6461 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006462 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006463 });
6464 }
6465 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006466
6467 @Override
6468 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6469 Runnable finishInstrumentationCallback) {
6470 synchronized (mGlobalLock) {
6471 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006472 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006473
6474 wpc.clearRecentTasks();
6475 wpc.clearActivities();
6476
6477 if (wpc.isInstrumenting()) {
6478 finishInstrumentationCallback.run();
6479 }
6480
Jorim Jaggid0752812018-10-16 16:07:20 +02006481 if (!restarting && hasVisibleActivities) {
6482 mWindowManager.deferSurfaceLayout();
6483 try {
6484 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6485 // If there was nothing to resume, and we are not already restarting
6486 // this process, but there is a visible activity that is hosted by the
6487 // process...then make sure all visible activities are running, taking
6488 // care of restarting this process.
6489 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6490 !PRESERVE_WINDOWS);
6491 }
6492 } finally {
6493 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006494 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006495 }
6496 }
6497 }
6498
6499 @Override
6500 public void closeSystemDialogs(String reason) {
6501 enforceNotIsolatedCaller("closeSystemDialogs");
6502
6503 final int pid = Binder.getCallingPid();
6504 final int uid = Binder.getCallingUid();
6505 final long origId = Binder.clearCallingIdentity();
6506 try {
6507 synchronized (mGlobalLock) {
6508 // Only allow this from foreground processes, so that background
6509 // applications can't abuse it to prevent system UI from being shown.
6510 if (uid >= FIRST_APPLICATION_UID) {
6511 final WindowProcessController proc = mPidMap.get(pid);
6512 if (!proc.isPerceptible()) {
6513 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6514 + " from background process " + proc);
6515 return;
6516 }
6517 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006518 mWindowManager.closeSystemDialogs(reason);
6519
Wale Ogunwaled32da472018-11-16 07:19:28 -08006520 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006521 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006522 // Call into AM outside the synchronized block.
6523 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006524 } finally {
6525 Binder.restoreCallingIdentity(origId);
6526 }
6527 }
6528
6529 @Override
6530 public void cleanupDisabledPackageComponents(
6531 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6532 synchronized (mGlobalLock) {
6533 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006534 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006535 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006536 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006537 mStackSupervisor.scheduleIdleLocked();
6538 }
6539
6540 // Clean-up disabled tasks
6541 getRecentTasks().cleanupDisabledPackageTasksLocked(
6542 packageName, disabledClasses, userId);
6543 }
6544 }
6545
6546 @Override
6547 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6548 int userId) {
6549 synchronized (mGlobalLock) {
6550
6551 boolean didSomething =
6552 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006553 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006554 null, doit, evenPersistent, userId);
6555 return didSomething;
6556 }
6557 }
6558
6559 @Override
6560 public void resumeTopActivities(boolean scheduleIdle) {
6561 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006562 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006563 if (scheduleIdle) {
6564 mStackSupervisor.scheduleIdleLocked();
6565 }
6566 }
6567 }
6568
6569 @Override
6570 public void preBindApplication(WindowProcessController wpc) {
6571 synchronized (mGlobalLock) {
6572 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6573 }
6574 }
6575
6576 @Override
6577 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6578 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006579 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006580 }
6581 }
6582
6583 @Override
6584 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6585 try {
6586 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6587 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6588 }
6589 } catch (RemoteException ex) {
6590 throw new SecurityException("Fail to check is caller a privileged app", ex);
6591 }
6592
6593 synchronized (mGlobalLock) {
6594 final long ident = Binder.clearCallingIdentity();
6595 try {
6596 if (mAmInternal.shouldConfirmCredentials(userId)) {
6597 if (mKeyguardController.isKeyguardLocked()) {
6598 // Showing launcher to avoid user entering credential twice.
6599 startHomeActivity(currentUserId, "notifyLockedProfile");
6600 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006601 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006602 }
6603 } finally {
6604 Binder.restoreCallingIdentity(ident);
6605 }
6606 }
6607 }
6608
6609 @Override
6610 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6611 mAmInternal.enforceCallingPermission(
6612 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6613
6614 synchronized (mGlobalLock) {
6615 final long ident = Binder.clearCallingIdentity();
6616 try {
6617 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6618 FLAG_ACTIVITY_TASK_ON_HOME);
6619 ActivityOptions activityOptions = options != null
6620 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006621 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006622 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006623 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006624 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006625 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006626 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6627 UserHandle.CURRENT);
6628 } finally {
6629 Binder.restoreCallingIdentity(ident);
6630 }
6631 }
6632 }
6633
6634 @Override
6635 public void writeActivitiesToProto(ProtoOutputStream proto) {
6636 synchronized (mGlobalLock) {
6637 // The output proto of "activity --proto activities"
6638 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006639 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006640 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6641 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006642 }
6643 }
6644
6645 @Override
6646 public void saveANRState(String reason) {
6647 synchronized (mGlobalLock) {
6648 final StringWriter sw = new StringWriter();
6649 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6650 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6651 if (reason != null) {
6652 pw.println(" Reason: " + reason);
6653 }
6654 pw.println();
6655 getActivityStartController().dump(pw, " ", null);
6656 pw.println();
6657 pw.println("-------------------------------------------------------------------------------");
6658 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6659 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6660 "" /* header */);
6661 pw.println();
6662 pw.close();
6663
6664 mLastANRState = sw.toString();
6665 }
6666 }
6667
6668 @Override
6669 public void clearSavedANRState() {
6670 synchronized (mGlobalLock) {
6671 mLastANRState = null;
6672 }
6673 }
6674
6675 @Override
6676 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6677 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6678 synchronized (mGlobalLock) {
6679 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6680 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6681 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6682 dumpLastANRLocked(pw);
6683 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6684 dumpLastANRTracesLocked(pw);
6685 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6686 dumpActivityStarterLocked(pw, dumpPackage);
6687 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6688 dumpActivityContainersLocked(pw);
6689 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6690 if (getRecentTasks() != null) {
6691 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6692 }
6693 }
6694 }
6695 }
6696
6697 @Override
6698 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6699 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6700 int wakefulness) {
6701 synchronized (mGlobalLock) {
6702 if (mHomeProcess != null && (dumpPackage == null
6703 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6704 if (needSep) {
6705 pw.println();
6706 needSep = false;
6707 }
6708 pw.println(" mHomeProcess: " + mHomeProcess);
6709 }
6710 if (mPreviousProcess != null && (dumpPackage == null
6711 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6712 if (needSep) {
6713 pw.println();
6714 needSep = false;
6715 }
6716 pw.println(" mPreviousProcess: " + mPreviousProcess);
6717 }
6718 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6719 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6720 StringBuilder sb = new StringBuilder(128);
6721 sb.append(" mPreviousProcessVisibleTime: ");
6722 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6723 pw.println(sb);
6724 }
6725 if (mHeavyWeightProcess != null && (dumpPackage == null
6726 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6727 if (needSep) {
6728 pw.println();
6729 needSep = false;
6730 }
6731 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6732 }
6733 if (dumpPackage == null) {
6734 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006735 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006736 }
6737 if (dumpAll) {
6738 if (dumpPackage == null) {
6739 pw.println(" mConfigWillChange: "
6740 + getTopDisplayFocusedStack().mConfigWillChange);
6741 }
6742 if (mCompatModePackages.getPackages().size() > 0) {
6743 boolean printed = false;
6744 for (Map.Entry<String, Integer> entry
6745 : mCompatModePackages.getPackages().entrySet()) {
6746 String pkg = entry.getKey();
6747 int mode = entry.getValue();
6748 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6749 continue;
6750 }
6751 if (!printed) {
6752 pw.println(" mScreenCompatPackages:");
6753 printed = true;
6754 }
6755 pw.println(" " + pkg + ": " + mode);
6756 }
6757 }
6758 }
6759
6760 if (dumpPackage == null) {
6761 pw.println(" mWakefulness="
6762 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006763 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006764 if (mRunningVoice != null) {
6765 pw.println(" mRunningVoice=" + mRunningVoice);
6766 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6767 }
6768 pw.println(" mSleeping=" + mSleeping);
6769 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6770 pw.println(" mVrController=" + mVrController);
6771 }
6772 if (mCurAppTimeTracker != null) {
6773 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6774 }
6775 if (mAllowAppSwitchUids.size() > 0) {
6776 boolean printed = false;
6777 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6778 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6779 for (int j = 0; j < types.size(); j++) {
6780 if (dumpPackage == null ||
6781 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6782 if (needSep) {
6783 pw.println();
6784 needSep = false;
6785 }
6786 if (!printed) {
6787 pw.println(" mAllowAppSwitchUids:");
6788 printed = true;
6789 }
6790 pw.print(" User ");
6791 pw.print(mAllowAppSwitchUids.keyAt(i));
6792 pw.print(": Type ");
6793 pw.print(types.keyAt(j));
6794 pw.print(" = ");
6795 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6796 pw.println();
6797 }
6798 }
6799 }
6800 }
6801 if (dumpPackage == null) {
6802 if (mController != null) {
6803 pw.println(" mController=" + mController
6804 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6805 }
6806 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6807 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6808 }
6809
6810 return needSep;
6811 }
6812 }
6813
6814 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006815 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6816 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 synchronized (mGlobalLock) {
6818 if (dumpPackage == null) {
6819 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6820 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006821 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6822 if (mRunningVoice != null) {
6823 final long vrToken = proto.start(
6824 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6825 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6826 mRunningVoice.toString());
6827 mVoiceWakeLock.writeToProto(
6828 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6829 proto.end(vrToken);
6830 }
6831 mVrController.writeToProto(proto,
6832 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 if (mController != null) {
6834 final long token = proto.start(CONTROLLER);
6835 proto.write(CONTROLLER, mController.toString());
6836 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6837 proto.end(token);
6838 }
6839 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6840 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6841 }
6842
6843 if (mHomeProcess != null && (dumpPackage == null
6844 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006845 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
6847
6848 if (mPreviousProcess != null && (dumpPackage == null
6849 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006850 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6852 }
6853
6854 if (mHeavyWeightProcess != null && (dumpPackage == null
6855 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006856 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 }
6858
6859 for (Map.Entry<String, Integer> entry
6860 : mCompatModePackages.getPackages().entrySet()) {
6861 String pkg = entry.getKey();
6862 int mode = entry.getValue();
6863 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6864 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6865 proto.write(PACKAGE, pkg);
6866 proto.write(MODE, mode);
6867 proto.end(compatToken);
6868 }
6869 }
6870
6871 if (mCurAppTimeTracker != null) {
6872 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6873 }
6874
6875 }
6876 }
6877
6878 @Override
6879 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6880 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6881 boolean dumpFocusedStackOnly) {
6882 synchronized (mGlobalLock) {
6883 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6884 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6885 }
6886 }
6887
6888 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006889 public void dumpForOom(PrintWriter pw) {
6890 synchronized (mGlobalLock) {
6891 pw.println(" mHomeProcess: " + mHomeProcess);
6892 pw.println(" mPreviousProcess: " + mPreviousProcess);
6893 if (mHeavyWeightProcess != null) {
6894 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6895 }
6896 }
6897 }
6898
6899 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006900 public boolean canGcNow() {
6901 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006902 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 }
6904 }
6905
6906 @Override
6907 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006908 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006909 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006910 return top != null ? top.app : null;
6911 }
6912 }
6913
6914 @Override
6915 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006916 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006917 if (mRootActivityContainer != null) {
6918 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 }
6920 }
6921 }
6922
6923 @Override
6924 public void scheduleDestroyAllActivities(String reason) {
6925 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006926 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006927 }
6928 }
6929
6930 @Override
6931 public void removeUser(int userId) {
6932 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006933 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 }
6935 }
6936
6937 @Override
6938 public boolean switchUser(int userId, UserState userState) {
6939 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006940 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006941 }
6942 }
6943
6944 @Override
6945 public void onHandleAppCrash(WindowProcessController wpc) {
6946 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006947 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006948 }
6949 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006950
6951 @Override
6952 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6953 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006954 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006955 }
6956 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006957
6958 @Override
6959 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006960 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006961 mActiveUids.put(uid, procState);
6962 }
6963 }
6964
6965 @Override
6966 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006967 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006968 mActiveUids.remove(uid);
6969 }
6970 }
6971
6972 @Override
6973 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006974 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006975 mActiveUids.clear();
6976 }
6977 }
6978
6979 @Override
6980 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006981 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006982 if (mActiveUids.get(uid) != null) {
6983 mActiveUids.put(uid, procState);
6984 }
6985 }
6986 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006987
6988 @Override
6989 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006990 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006991 mPendingTempWhitelist.put(uid, tag);
6992 }
6993 }
6994
6995 @Override
6996 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006997 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006998 mPendingTempWhitelist.remove(uid);
6999 }
7000 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007001
7002 @Override
7003 public boolean handleAppCrashInActivityController(String processName, int pid,
7004 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7005 Runnable killCrashingAppCallback) {
7006 synchronized (mGlobalLock) {
7007 if (mController == null) {
7008 return false;
7009 }
7010
7011 try {
7012 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7013 stackTrace)) {
7014 killCrashingAppCallback.run();
7015 return true;
7016 }
7017 } catch (RemoteException e) {
7018 mController = null;
7019 Watchdog.getInstance().setActivityController(null);
7020 }
7021 return false;
7022 }
7023 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007024
7025 @Override
7026 public void removeRecentTasksByPackageName(String packageName, int userId) {
7027 synchronized (mGlobalLock) {
7028 mRecentTasks.removeTasksByPackageName(packageName, userId);
7029 }
7030 }
7031
7032 @Override
7033 public void cleanupRecentTasksForUser(int userId) {
7034 synchronized (mGlobalLock) {
7035 mRecentTasks.cleanupLocked(userId);
7036 }
7037 }
7038
7039 @Override
7040 public void loadRecentTasksForUser(int userId) {
7041 synchronized (mGlobalLock) {
7042 mRecentTasks.loadUserRecentsLocked(userId);
7043 }
7044 }
7045
7046 @Override
7047 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7048 synchronized (mGlobalLock) {
7049 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7050 }
7051 }
7052
7053 @Override
7054 public void flushRecentTasks() {
7055 mRecentTasks.flush();
7056 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007057
7058 @Override
7059 public WindowProcessController getHomeProcess() {
7060 synchronized (mGlobalLock) {
7061 return mHomeProcess;
7062 }
7063 }
7064
7065 @Override
7066 public WindowProcessController getPreviousProcess() {
7067 synchronized (mGlobalLock) {
7068 return mPreviousProcess;
7069 }
7070 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007071
7072 @Override
7073 public void clearLockedTasks(String reason) {
7074 synchronized (mGlobalLock) {
7075 getLockTaskController().clearLockedTasks(reason);
7076 }
7077 }
7078
7079 @Override
7080 public void updateUserConfiguration() {
7081 synchronized (mGlobalLock) {
7082 final Configuration configuration = new Configuration(getGlobalConfiguration());
7083 final int currentUserId = mAmInternal.getCurrentUserId();
7084 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7085 configuration, currentUserId, Settings.System.canWrite(mContext));
7086 updateConfigurationLocked(configuration, null /* starting */,
7087 false /* initLocale */, false /* persistent */, currentUserId,
7088 false /* deferResume */);
7089 }
7090 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007091
7092 @Override
7093 public boolean canShowErrorDialogs() {
7094 synchronized (mGlobalLock) {
7095 return mShowDialogs && !mSleeping && !mShuttingDown
7096 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7097 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7098 mAmInternal.getCurrentUserId())
7099 && !(UserManager.isDeviceInDemoMode(mContext)
7100 && mAmInternal.getCurrentUser().isDemo());
7101 }
7102 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007103
7104 @Override
7105 public void setProfileApp(String profileApp) {
7106 synchronized (mGlobalLock) {
7107 mProfileApp = profileApp;
7108 }
7109 }
7110
7111 @Override
7112 public void setProfileProc(WindowProcessController wpc) {
7113 synchronized (mGlobalLock) {
7114 mProfileProc = wpc;
7115 }
7116 }
7117
7118 @Override
7119 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7120 synchronized (mGlobalLock) {
7121 mProfilerInfo = profilerInfo;
7122 }
7123 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007124
7125 @Override
7126 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7127 synchronized (mGlobalLock) {
7128 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7129 }
7130 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007131
7132 @Override
7133 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7134 synchronized (mGlobalLock) {
7135 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7136 }
7137 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007138
7139 @Override
7140 public boolean isUidForeground(int uid) {
7141 synchronized (mGlobalLock) {
7142 return ActivityTaskManagerService.this.isUidForeground(uid);
7143 }
7144 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007145 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007146}