blob: 7aa34819692bca2481141bb87f562a2da013be0c [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)
1386 .execute();
1387 }
1388
1389 @Override
1390 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1391 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1393 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001395 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .setCallingUid(callingUid)
1397 .setCallingPackage(callingPackage)
1398 .setResolvedType(resolvedType)
1399 .setActivityOptions(bOptions)
1400 .setMayWait(userId)
1401 .execute();
1402 }
1403
1404 @Override
1405 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1406 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001407 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001408 final int callingPid = Binder.getCallingPid();
1409 final long origId = Binder.clearCallingIdentity();
1410 try {
1411 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001412 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1413 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414
1415 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1417 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1419 recentsUid, assistDataReceiver);
1420 }
1421 } finally {
1422 Binder.restoreCallingIdentity(origId);
1423 }
1424 }
1425
1426 @Override
1427 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 "startActivityFromRecents()");
1430
1431 final int callingPid = Binder.getCallingPid();
1432 final int callingUid = Binder.getCallingUid();
1433 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1434 final long origId = Binder.clearCallingIdentity();
1435 try {
1436 synchronized (mGlobalLock) {
1437 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1438 safeOptions);
1439 }
1440 } finally {
1441 Binder.restoreCallingIdentity(origId);
1442 }
1443 }
1444
1445 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001446 * Public API to check if the client is allowed to start an activity on specified display.
1447 *
1448 * If the target display is private or virtual, some restrictions will apply.
1449 *
1450 * @param displayId Target display id.
1451 * @param intent Intent used to launch the activity.
1452 * @param resolvedType The MIME type of the intent.
1453 * @param userId The id of the user for whom the call is made.
1454 * @return {@code true} if a call to start an activity on the target display should succeed and
1455 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1456 */
1457 @Override
1458 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1459 String resolvedType, int userId) {
1460 final int callingUid = Binder.getCallingUid();
1461 final int callingPid = Binder.getCallingPid();
1462 final long origId = Binder.clearCallingIdentity();
1463
1464 try {
1465 // Collect information about the target of the Intent.
1466 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1467 0 /* startFlags */, null /* profilerInfo */, userId,
1468 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1469 UserHandle.USER_NULL));
1470 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1471
1472 synchronized (mGlobalLock) {
1473 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1474 aInfo);
1475 }
1476 } finally {
1477 Binder.restoreCallingIdentity(origId);
1478 }
1479 }
1480
1481 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 * This is the internal entry point for handling Activity.finish().
1483 *
1484 * @param token The Binder token referencing the Activity we want to finish.
1485 * @param resultCode Result code, if any, from this Activity.
1486 * @param resultData Result data (Intent), if any, from this Activity.
1487 * @param finishTask Whether to finish the task associated with this Activity.
1488 *
1489 * @return Returns true if the activity successfully finished, or false if it is still running.
1490 */
1491 @Override
1492 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1493 int finishTask) {
1494 // Refuse possible leaked file descriptors
1495 if (resultData != null && resultData.hasFileDescriptors()) {
1496 throw new IllegalArgumentException("File descriptors passed in Intent");
1497 }
1498
1499 synchronized (mGlobalLock) {
1500 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1501 if (r == null) {
1502 return true;
1503 }
1504 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001505 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506 ActivityRecord rootR = tr.getRootActivity();
1507 if (rootR == null) {
1508 Slog.w(TAG, "Finishing task with all activities already finished");
1509 }
1510 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1511 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001512 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 return false;
1514 }
1515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001516 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1517 // We should consolidate.
1518 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001520 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 if (next != null) {
1522 // ask watcher if this is allowed
1523 boolean resumeOK = true;
1524 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001525 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001526 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001527 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 Watchdog.getInstance().setActivityController(null);
1529 }
1530
1531 if (!resumeOK) {
1532 Slog.i(TAG, "Not finishing activity because controller resumed");
1533 return false;
1534 }
1535 }
1536 }
1537 final long origId = Binder.clearCallingIdentity();
1538 try {
1539 boolean res;
1540 final boolean finishWithRootActivity =
1541 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1542 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1543 || (finishWithRootActivity && r == rootR)) {
1544 // If requested, remove the task that is associated to this activity only if it
1545 // was the root activity in the task. The result code and data is ignored
1546 // because we don't support returning them across task boundaries. Also, to
1547 // keep backwards compatibility we remove the task from recents when finishing
1548 // task with root activity.
1549 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1550 finishWithRootActivity, "finish-activity");
1551 if (!res) {
1552 Slog.i(TAG, "Removing task failed to finish activity");
1553 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001554 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001555 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 } else {
1557 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1558 resultData, "app-request", true);
1559 if (!res) {
1560 Slog.i(TAG, "Failed to finish by app-request");
1561 }
1562 }
1563 return res;
1564 } finally {
1565 Binder.restoreCallingIdentity(origId);
1566 }
1567 }
1568 }
1569
1570 @Override
1571 public boolean finishActivityAffinity(IBinder token) {
1572 synchronized (mGlobalLock) {
1573 final long origId = Binder.clearCallingIdentity();
1574 try {
1575 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1576 if (r == null) {
1577 return false;
1578 }
1579
1580 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1581 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001582 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001583 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 return false;
1585 }
1586 return task.getStack().finishActivityAffinityLocked(r);
1587 } finally {
1588 Binder.restoreCallingIdentity(origId);
1589 }
1590 }
1591 }
1592
1593 @Override
1594 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1595 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001596 try {
1597 WindowProcessController proc = null;
1598 synchronized (mGlobalLock) {
1599 ActivityStack stack = ActivityRecord.getStackLocked(token);
1600 if (stack == null) {
1601 return;
1602 }
1603 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1604 false /* fromTimeout */, false /* processPausingActivities */, config);
1605 if (r != null) {
1606 proc = r.app;
1607 }
1608 if (stopProfiling && proc != null) {
1609 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 }
1611 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001612 } finally {
1613 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001614 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 }
1616
1617 @Override
1618 public final void activityResumed(IBinder token) {
1619 final long origId = Binder.clearCallingIdentity();
1620 synchronized (mGlobalLock) {
1621 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001622 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 }
1624 Binder.restoreCallingIdentity(origId);
1625 }
1626
1627 @Override
1628 public final void activityPaused(IBinder token) {
1629 final long origId = Binder.clearCallingIdentity();
1630 synchronized (mGlobalLock) {
1631 ActivityStack stack = ActivityRecord.getStackLocked(token);
1632 if (stack != null) {
1633 stack.activityPausedLocked(token, false);
1634 }
1635 }
1636 Binder.restoreCallingIdentity(origId);
1637 }
1638
1639 @Override
1640 public final void activityStopped(IBinder token, Bundle icicle,
1641 PersistableBundle persistentState, CharSequence description) {
1642 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1643
1644 // Refuse possible leaked file descriptors
1645 if (icicle != null && icicle.hasFileDescriptors()) {
1646 throw new IllegalArgumentException("File descriptors passed in Bundle");
1647 }
1648
1649 final long origId = Binder.clearCallingIdentity();
1650
1651 synchronized (mGlobalLock) {
1652 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1653 if (r != null) {
1654 r.activityStoppedLocked(icicle, persistentState, description);
1655 }
1656 }
1657
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001658 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659
1660 Binder.restoreCallingIdentity(origId);
1661 }
1662
1663 @Override
1664 public final void activityDestroyed(IBinder token) {
1665 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1666 synchronized (mGlobalLock) {
1667 ActivityStack stack = ActivityRecord.getStackLocked(token);
1668 if (stack != null) {
1669 stack.activityDestroyedLocked(token, "activityDestroyed");
1670 }
1671 }
1672 }
1673
1674 @Override
1675 public final void activityRelaunched(IBinder token) {
1676 final long origId = Binder.clearCallingIdentity();
1677 synchronized (mGlobalLock) {
1678 mStackSupervisor.activityRelaunchedLocked(token);
1679 }
1680 Binder.restoreCallingIdentity(origId);
1681 }
1682
1683 public final void activitySlept(IBinder token) {
1684 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1685
1686 final long origId = Binder.clearCallingIdentity();
1687
1688 synchronized (mGlobalLock) {
1689 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1690 if (r != null) {
1691 mStackSupervisor.activitySleptLocked(r);
1692 }
1693 }
1694
1695 Binder.restoreCallingIdentity(origId);
1696 }
1697
1698 @Override
1699 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1700 synchronized (mGlobalLock) {
1701 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1702 if (r == null) {
1703 return;
1704 }
1705 final long origId = Binder.clearCallingIdentity();
1706 try {
1707 r.setRequestedOrientation(requestedOrientation);
1708 } finally {
1709 Binder.restoreCallingIdentity(origId);
1710 }
1711 }
1712 }
1713
1714 @Override
1715 public int getRequestedOrientation(IBinder token) {
1716 synchronized (mGlobalLock) {
1717 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1718 if (r == null) {
1719 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1720 }
1721 return r.getRequestedOrientation();
1722 }
1723 }
1724
1725 @Override
1726 public void setImmersive(IBinder token, boolean immersive) {
1727 synchronized (mGlobalLock) {
1728 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1729 if (r == null) {
1730 throw new IllegalArgumentException();
1731 }
1732 r.immersive = immersive;
1733
1734 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001735 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001737 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 }
1739 }
1740 }
1741
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001742 void applyUpdateLockStateLocked(ActivityRecord r) {
1743 // Modifications to the UpdateLock state are done on our handler, outside
1744 // the activity manager's locks. The new state is determined based on the
1745 // state *now* of the relevant activity record. The object is passed to
1746 // the handler solely for logging detail, not to be consulted/modified.
1747 final boolean nextState = r != null && r.immersive;
1748 mH.post(() -> {
1749 if (mUpdateLock.isHeld() != nextState) {
1750 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1751 "Applying new update lock state '" + nextState + "' for " + r);
1752 if (nextState) {
1753 mUpdateLock.acquire();
1754 } else {
1755 mUpdateLock.release();
1756 }
1757 }
1758 });
1759 }
1760
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761 @Override
1762 public boolean isImmersive(IBinder token) {
1763 synchronized (mGlobalLock) {
1764 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1765 if (r == null) {
1766 throw new IllegalArgumentException();
1767 }
1768 return r.immersive;
1769 }
1770 }
1771
1772 @Override
1773 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001774 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001776 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 return (r != null) ? r.immersive : false;
1778 }
1779 }
1780
1781 @Override
1782 public void overridePendingTransition(IBinder token, String packageName,
1783 int enterAnim, int exitAnim) {
1784 synchronized (mGlobalLock) {
1785 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1786 if (self == null) {
1787 return;
1788 }
1789
1790 final long origId = Binder.clearCallingIdentity();
1791
1792 if (self.isState(
1793 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001794 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001795 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001796 }
1797
1798 Binder.restoreCallingIdentity(origId);
1799 }
1800 }
1801
1802 @Override
1803 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001806 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 if (r == null) {
1808 return ActivityManager.COMPAT_MODE_UNKNOWN;
1809 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001810 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
1812 }
1813
1814 @Override
1815 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001818 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001820 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001821 if (r == null) {
1822 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1823 return;
1824 }
1825 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001826 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001827 }
1828 }
1829
1830 @Override
1831 public int getLaunchedFromUid(IBinder activityToken) {
1832 ActivityRecord srec;
1833 synchronized (mGlobalLock) {
1834 srec = ActivityRecord.forTokenLocked(activityToken);
1835 }
1836 if (srec == null) {
1837 return -1;
1838 }
1839 return srec.launchedFromUid;
1840 }
1841
1842 @Override
1843 public String getLaunchedFromPackage(IBinder activityToken) {
1844 ActivityRecord srec;
1845 synchronized (mGlobalLock) {
1846 srec = ActivityRecord.forTokenLocked(activityToken);
1847 }
1848 if (srec == null) {
1849 return null;
1850 }
1851 return srec.launchedFromPackage;
1852 }
1853
1854 @Override
1855 public boolean convertFromTranslucent(IBinder token) {
1856 final long origId = Binder.clearCallingIdentity();
1857 try {
1858 synchronized (mGlobalLock) {
1859 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1860 if (r == null) {
1861 return false;
1862 }
1863 final boolean translucentChanged = r.changeWindowTranslucency(true);
1864 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001865 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001867 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 return translucentChanged;
1869 }
1870 } finally {
1871 Binder.restoreCallingIdentity(origId);
1872 }
1873 }
1874
1875 @Override
1876 public boolean convertToTranslucent(IBinder token, Bundle options) {
1877 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1878 final long origId = Binder.clearCallingIdentity();
1879 try {
1880 synchronized (mGlobalLock) {
1881 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1882 if (r == null) {
1883 return false;
1884 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001885 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 int index = task.mActivities.lastIndexOf(r);
1887 if (index > 0) {
1888 ActivityRecord under = task.mActivities.get(index - 1);
1889 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1890 }
1891 final boolean translucentChanged = r.changeWindowTranslucency(false);
1892 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001893 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001895 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001896 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 return translucentChanged;
1898 }
1899 } finally {
1900 Binder.restoreCallingIdentity(origId);
1901 }
1902 }
1903
1904 @Override
1905 public void notifyActivityDrawn(IBinder token) {
1906 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1907 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001908 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001910 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 }
1912 }
1913 }
1914
1915 @Override
1916 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1917 synchronized (mGlobalLock) {
1918 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1919 if (r == null) {
1920 return;
1921 }
1922 r.reportFullyDrawnLocked(restoredFromBundle);
1923 }
1924 }
1925
1926 @Override
1927 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1928 synchronized (mGlobalLock) {
1929 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1930 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1931 return stack.mDisplayId;
1932 }
1933 return DEFAULT_DISPLAY;
1934 }
1935 }
1936
1937 @Override
1938 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 long ident = Binder.clearCallingIdentity();
1941 try {
1942 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001943 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001945 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 }
1947 return null;
1948 }
1949 } finally {
1950 Binder.restoreCallingIdentity(ident);
1951 }
1952 }
1953
1954 @Override
1955 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001956 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1958 final long callingId = Binder.clearCallingIdentity();
1959 try {
1960 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001961 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (stack == null) {
1963 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1964 return;
1965 }
1966 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001967 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001968 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001969 }
1970 }
1971 } finally {
1972 Binder.restoreCallingIdentity(callingId);
1973 }
1974 }
1975
1976 @Override
1977 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001978 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001979 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1980 final long callingId = Binder.clearCallingIdentity();
1981 try {
1982 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001983 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001984 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 if (task == null) {
1986 return;
1987 }
1988 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001989 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001990 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 }
1992 }
1993 } finally {
1994 Binder.restoreCallingIdentity(callingId);
1995 }
1996 }
1997
1998 @Override
1999 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002000 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 synchronized (mGlobalLock) {
2002 final long ident = Binder.clearCallingIdentity();
2003 try {
2004 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2005 "remove-task");
2006 } finally {
2007 Binder.restoreCallingIdentity(ident);
2008 }
2009 }
2010 }
2011
2012 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002013 public void removeAllVisibleRecentTasks() {
2014 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2015 synchronized (mGlobalLock) {
2016 final long ident = Binder.clearCallingIdentity();
2017 try {
2018 getRecentTasks().removeAllVisibleTasks();
2019 } finally {
2020 Binder.restoreCallingIdentity(ident);
2021 }
2022 }
2023 }
2024
2025 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2027 synchronized (mGlobalLock) {
2028 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2029 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002030 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 }
2032 }
2033 return false;
2034 }
2035
2036 @Override
2037 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2038 Intent resultData) {
2039
2040 synchronized (mGlobalLock) {
2041 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2042 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002043 return r.getActivityStack().navigateUpToLocked(
2044 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 }
2046 return false;
2047 }
2048 }
2049
2050 /**
2051 * Attempts to move a task backwards in z-order (the order of activities within the task is
2052 * unchanged).
2053 *
2054 * There are several possible results of this call:
2055 * - if the task is locked, then we will show the lock toast
2056 * - if there is a task behind the provided task, then that task is made visible and resumed as
2057 * this task is moved to the back
2058 * - otherwise, if there are no other tasks in the stack:
2059 * - if this task is in the pinned stack, then we remove the stack completely, which will
2060 * have the effect of moving the task to the top or bottom of the fullscreen stack
2061 * (depending on whether it is visible)
2062 * - otherwise, we simply return home and hide this task
2063 *
2064 * @param token A reference to the activity we wish to move
2065 * @param nonRoot If false then this only works if the activity is the root
2066 * of a task; if true it will work for any activity in a task.
2067 * @return Returns true if the move completed, false if not.
2068 */
2069 @Override
2070 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002071 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 synchronized (mGlobalLock) {
2073 final long origId = Binder.clearCallingIdentity();
2074 try {
2075 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002076 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 if (task != null) {
2078 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2079 }
2080 } finally {
2081 Binder.restoreCallingIdentity(origId);
2082 }
2083 }
2084 return false;
2085 }
2086
2087 @Override
2088 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002089 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 long ident = Binder.clearCallingIdentity();
2091 Rect rect = new Rect();
2092 try {
2093 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002094 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2096 if (task == null) {
2097 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2098 return rect;
2099 }
2100 if (task.getStack() != null) {
2101 // Return the bounds from window manager since it will be adjusted for various
2102 // things like the presense of a docked stack for tasks that aren't resizeable.
2103 task.getWindowContainerBounds(rect);
2104 } else {
2105 // Task isn't in window manager yet since it isn't associated with a stack.
2106 // Return the persist value from activity manager
2107 if (!task.matchParentBounds()) {
2108 rect.set(task.getBounds());
2109 } else if (task.mLastNonFullscreenBounds != null) {
2110 rect.set(task.mLastNonFullscreenBounds);
2111 }
2112 }
2113 }
2114 } finally {
2115 Binder.restoreCallingIdentity(ident);
2116 }
2117 return rect;
2118 }
2119
2120 @Override
2121 public ActivityManager.TaskDescription getTaskDescription(int id) {
2122 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002125 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2127 if (tr != null) {
2128 return tr.lastTaskDescription;
2129 }
2130 }
2131 return null;
2132 }
2133
2134 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002135 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2136 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2137 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2138 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2139 return;
2140 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002141 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002142 synchronized (mGlobalLock) {
2143 final long ident = Binder.clearCallingIdentity();
2144 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002145 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002146 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002147 if (task == null) {
2148 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2149 return;
2150 }
2151
2152 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2153 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2154
2155 if (!task.isActivityTypeStandardOrUndefined()) {
2156 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2157 + " non-standard task " + taskId + " to windowing mode="
2158 + windowingMode);
2159 }
2160
2161 final ActivityStack stack = task.getStack();
2162 if (toTop) {
2163 stack.moveToFront("setTaskWindowingMode", task);
2164 }
2165 stack.setWindowingMode(windowingMode);
2166 } finally {
2167 Binder.restoreCallingIdentity(ident);
2168 }
2169 }
2170 }
2171
2172 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002173 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002174 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 ActivityRecord r = getCallingRecordLocked(token);
2176 return r != null ? r.info.packageName : null;
2177 }
2178 }
2179
2180 @Override
2181 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002182 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002183 ActivityRecord r = getCallingRecordLocked(token);
2184 return r != null ? r.intent.getComponent() : null;
2185 }
2186 }
2187
2188 private ActivityRecord getCallingRecordLocked(IBinder token) {
2189 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2190 if (r == null) {
2191 return null;
2192 }
2193 return r.resultTo;
2194 }
2195
2196 @Override
2197 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002198 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199
2200 synchronized (mGlobalLock) {
2201 final long origId = Binder.clearCallingIdentity();
2202 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002203 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 } finally {
2205 Binder.restoreCallingIdentity(origId);
2206 }
2207 }
2208 }
2209
2210 /**
2211 * TODO: Add mController hook
2212 */
2213 @Override
2214 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002215 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002216
2217 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2218 synchronized (mGlobalLock) {
2219 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2220 false /* fromRecents */);
2221 }
2222 }
2223
2224 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2225 boolean fromRecents) {
2226
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002227 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 Binder.getCallingUid(), -1, -1, "Task to front")) {
2229 SafeActivityOptions.abort(options);
2230 return;
2231 }
2232 final long origId = Binder.clearCallingIdentity();
2233 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002234 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002235 if (task == null) {
2236 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002237 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 return;
2239 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002240 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002242 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 return;
2244 }
2245 ActivityOptions realOptions = options != null
2246 ? options.getOptions(mStackSupervisor)
2247 : null;
2248 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2249 false /* forceNonResizable */);
2250
2251 final ActivityRecord topActivity = task.getTopActivity();
2252 if (topActivity != null) {
2253
2254 // We are reshowing a task, use a starting window to hide the initial draw delay
2255 // so the transition can start earlier.
2256 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2257 true /* taskSwitch */, fromRecents);
2258 }
2259 } finally {
2260 Binder.restoreCallingIdentity(origId);
2261 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 }
2263
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002264 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2265 int callingPid, int callingUid, String name) {
2266 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2267 return true;
2268 }
2269
2270 if (getRecentTasks().isCallerRecents(sourceUid)) {
2271 return true;
2272 }
2273
2274 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2275 if (perm == PackageManager.PERMISSION_GRANTED) {
2276 return true;
2277 }
2278 if (checkAllowAppSwitchUid(sourceUid)) {
2279 return true;
2280 }
2281
2282 // If the actual IPC caller is different from the logical source, then
2283 // also see if they are allowed to control app switches.
2284 if (callingUid != -1 && callingUid != sourceUid) {
2285 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2286 if (perm == PackageManager.PERMISSION_GRANTED) {
2287 return true;
2288 }
2289 if (checkAllowAppSwitchUid(callingUid)) {
2290 return true;
2291 }
2292 }
2293
2294 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2295 return false;
2296 }
2297
2298 private boolean checkAllowAppSwitchUid(int uid) {
2299 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2300 if (types != null) {
2301 for (int i = types.size() - 1; i >= 0; i--) {
2302 if (types.valueAt(i).intValue() == uid) {
2303 return true;
2304 }
2305 }
2306 }
2307 return false;
2308 }
2309
2310 @Override
2311 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2312 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2313 "setActivityController()");
2314 synchronized (mGlobalLock) {
2315 mController = controller;
2316 mControllerIsAMonkey = imAMonkey;
2317 Watchdog.getInstance().setActivityController(controller);
2318 }
2319 }
2320
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002321 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 synchronized (mGlobalLock) {
2323 return mController != null && mControllerIsAMonkey;
2324 }
2325 }
2326
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002327 @Override
2328 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2329 synchronized (mGlobalLock) {
2330 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2331 }
2332 }
2333
2334 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2336 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2337 }
2338
2339 @Override
2340 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2341 @WindowConfiguration.ActivityType int ignoreActivityType,
2342 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2343 final int callingUid = Binder.getCallingUid();
2344 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2345
2346 synchronized (mGlobalLock) {
2347 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2348
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002349 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002350 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002351 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002352 ignoreWindowingMode, callingUid, allowed);
2353 }
2354
2355 return list;
2356 }
2357
2358 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2360 synchronized (mGlobalLock) {
2361 final long origId = Binder.clearCallingIdentity();
2362 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2363 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002364 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002365 }
2366 Binder.restoreCallingIdentity(origId);
2367 }
2368 }
2369
2370 @Override
2371 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002372 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 ActivityStack stack = ActivityRecord.getStackLocked(token);
2374 if (stack != null) {
2375 return stack.willActivityBeVisibleLocked(token);
2376 }
2377 return false;
2378 }
2379 }
2380
2381 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002382 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002383 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002384 synchronized (mGlobalLock) {
2385 final long ident = Binder.clearCallingIdentity();
2386 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002387 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002388 if (task == null) {
2389 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2390 return;
2391 }
2392
2393 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2394 + " to stackId=" + stackId + " toTop=" + toTop);
2395
Wale Ogunwaled32da472018-11-16 07:19:28 -08002396 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002397 if (stack == null) {
2398 throw new IllegalStateException(
2399 "moveTaskToStack: No stack for stackId=" + stackId);
2400 }
2401 if (!stack.isActivityTypeStandardOrUndefined()) {
2402 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2403 + taskId + " to stack " + stackId);
2404 }
2405 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002406 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002407 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2408 }
2409 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2410 "moveTaskToStack");
2411 } finally {
2412 Binder.restoreCallingIdentity(ident);
2413 }
2414 }
2415 }
2416
2417 @Override
2418 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2419 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002420 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002421
2422 final long ident = Binder.clearCallingIdentity();
2423 try {
2424 synchronized (mGlobalLock) {
2425 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002426 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002427 if (stack == null) {
2428 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2429 return;
2430 }
2431 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2432 throw new IllegalArgumentException("Stack: " + stackId
2433 + " doesn't support animated resize.");
2434 }
2435 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2436 animationDuration, false /* fromFullscreen */);
2437 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002438 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 if (stack == null) {
2440 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2441 return;
2442 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002443 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002444 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2445 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2446 }
2447 }
2448 } finally {
2449 Binder.restoreCallingIdentity(ident);
2450 }
2451 }
2452
2453 /**
2454 * Moves the specified task to the primary-split-screen stack.
2455 *
2456 * @param taskId Id of task to move.
2457 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2458 * exist already. See
2459 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2460 * and
2461 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2462 * @param toTop If the task and stack should be moved to the top.
2463 * @param animate Whether we should play an animation for the moving the task.
2464 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2465 * stack. Pass {@code null} to use default bounds.
2466 * @param showRecents If the recents activity should be shown on the other side of the task
2467 * going into split-screen mode.
2468 */
2469 @Override
2470 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2471 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002473 "setTaskWindowingModeSplitScreenPrimary()");
2474 synchronized (mGlobalLock) {
2475 final long ident = Binder.clearCallingIdentity();
2476 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002477 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002478 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002479 if (task == null) {
2480 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2481 return false;
2482 }
2483 if (DEBUG_STACK) Slog.d(TAG_STACK,
2484 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2485 + " to createMode=" + createMode + " toTop=" + toTop);
2486 if (!task.isActivityTypeStandardOrUndefined()) {
2487 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2488 + " non-standard task " + taskId + " to split-screen windowing mode");
2489 }
2490
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002491 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002492 final int windowingMode = task.getWindowingMode();
2493 final ActivityStack stack = task.getStack();
2494 if (toTop) {
2495 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2496 }
2497 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002498 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2499 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002500 return windowingMode != task.getWindowingMode();
2501 } finally {
2502 Binder.restoreCallingIdentity(ident);
2503 }
2504 }
2505 }
2506
2507 /**
2508 * Removes stacks in the input windowing modes from the system if they are of activity type
2509 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2510 */
2511 @Override
2512 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002514 "removeStacksInWindowingModes()");
2515
2516 synchronized (mGlobalLock) {
2517 final long ident = Binder.clearCallingIdentity();
2518 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002519 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002520 } finally {
2521 Binder.restoreCallingIdentity(ident);
2522 }
2523 }
2524 }
2525
2526 @Override
2527 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002528 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002529 "removeStacksWithActivityTypes()");
2530
2531 synchronized (mGlobalLock) {
2532 final long ident = Binder.clearCallingIdentity();
2533 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002534 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 } finally {
2536 Binder.restoreCallingIdentity(ident);
2537 }
2538 }
2539 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540
2541 @Override
2542 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2543 int userId) {
2544 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002545 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2546 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002547 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002548 final boolean detailed = checkGetTasksPermission(
2549 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2550 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002551 == PackageManager.PERMISSION_GRANTED;
2552
2553 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002554 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002555 callingUid);
2556 }
2557 }
2558
2559 @Override
2560 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 long ident = Binder.clearCallingIdentity();
2563 try {
2564 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002565 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002566 }
2567 } finally {
2568 Binder.restoreCallingIdentity(ident);
2569 }
2570 }
2571
2572 @Override
2573 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 long ident = Binder.clearCallingIdentity();
2576 try {
2577 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002578 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002579 }
2580 } finally {
2581 Binder.restoreCallingIdentity(ident);
2582 }
2583 }
2584
2585 @Override
2586 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002587 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002588 final long callingUid = Binder.getCallingUid();
2589 final long origId = Binder.clearCallingIdentity();
2590 try {
2591 synchronized (mGlobalLock) {
2592 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002594 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2595 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2596 }
2597 } finally {
2598 Binder.restoreCallingIdentity(origId);
2599 }
2600 }
2601
2602 @Override
2603 public void startLockTaskModeByToken(IBinder token) {
2604 synchronized (mGlobalLock) {
2605 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2606 if (r == null) {
2607 return;
2608 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002609 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002610 }
2611 }
2612
2613 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002614 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002615 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002616 // This makes inner call to look as if it was initiated by system.
2617 long ident = Binder.clearCallingIdentity();
2618 try {
2619 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002620 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002621 MATCH_TASK_IN_STACKS_ONLY);
2622 if (task == null) {
2623 return;
2624 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002625
2626 // When starting lock task mode the stack must be in front and focused
2627 task.getStack().moveToFront("startSystemLockTaskMode");
2628 startLockTaskModeLocked(task, true /* isSystemCaller */);
2629 }
2630 } finally {
2631 Binder.restoreCallingIdentity(ident);
2632 }
2633 }
2634
2635 @Override
2636 public void stopLockTaskModeByToken(IBinder token) {
2637 synchronized (mGlobalLock) {
2638 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2639 if (r == null) {
2640 return;
2641 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002642 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002643 }
2644 }
2645
2646 /**
2647 * This API should be called by SystemUI only when user perform certain action to dismiss
2648 * lock task mode. We should only dismiss pinned lock task mode in this case.
2649 */
2650 @Override
2651 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002652 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2654 }
2655
2656 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2657 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2658 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2659 return;
2660 }
2661
Wale Ogunwaled32da472018-11-16 07:19:28 -08002662 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 if (stack == null || task != stack.topTask()) {
2664 throw new IllegalArgumentException("Invalid task, not in foreground");
2665 }
2666
2667 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2668 // system or a specific app.
2669 // * System-initiated requests will only start the pinned mode (screen pinning)
2670 // * App-initiated requests
2671 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2672 // - will start the pinned mode, otherwise
2673 final int callingUid = Binder.getCallingUid();
2674 long ident = Binder.clearCallingIdentity();
2675 try {
2676 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002677 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002679 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
2684
2685 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2686 final int callingUid = Binder.getCallingUid();
2687 long ident = Binder.clearCallingIdentity();
2688 try {
2689 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002690 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002691 }
2692 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2693 // task and jumping straight into a call in the case of emergency call back.
2694 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2695 if (tm != null) {
2696 tm.showInCallScreen(false);
2697 }
2698 } finally {
2699 Binder.restoreCallingIdentity(ident);
2700 }
2701 }
2702
2703 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002704 public void updateLockTaskPackages(int userId, String[] packages) {
2705 final int callingUid = Binder.getCallingUid();
2706 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2707 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2708 "updateLockTaskPackages()");
2709 }
2710 synchronized (this) {
2711 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2712 + Arrays.toString(packages));
2713 getLockTaskController().updateLockTaskPackages(userId, packages);
2714 }
2715 }
2716
2717 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002718 public boolean isInLockTaskMode() {
2719 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2720 }
2721
2722 @Override
2723 public int getLockTaskModeState() {
2724 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002725 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002726 }
2727 }
2728
2729 @Override
2730 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2731 synchronized (mGlobalLock) {
2732 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2733 if (r != null) {
2734 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002735 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002737 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002738 }
2739 }
2740 }
2741
2742 @Override
2743 public Bundle getActivityOptions(IBinder token) {
2744 final long origId = Binder.clearCallingIdentity();
2745 try {
2746 synchronized (mGlobalLock) {
2747 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2748 if (r != null) {
2749 final ActivityOptions activityOptions = r.takeOptionsLocked();
2750 return activityOptions == null ? null : activityOptions.toBundle();
2751 }
2752 return null;
2753 }
2754 } finally {
2755 Binder.restoreCallingIdentity(origId);
2756 }
2757 }
2758
2759 @Override
2760 public List<IBinder> getAppTasks(String callingPackage) {
2761 int callingUid = Binder.getCallingUid();
2762 long ident = Binder.clearCallingIdentity();
2763 try {
2764 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002765 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 }
2767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
2770 }
2771
2772 @Override
2773 public void finishVoiceTask(IVoiceInteractionSession session) {
2774 synchronized (mGlobalLock) {
2775 final long origId = Binder.clearCallingIdentity();
2776 try {
2777 // TODO: VI Consider treating local voice interactions and voice tasks
2778 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002779 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 } finally {
2781 Binder.restoreCallingIdentity(origId);
2782 }
2783 }
2784
2785 }
2786
2787 @Override
2788 public boolean isTopOfTask(IBinder token) {
2789 synchronized (mGlobalLock) {
2790 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002791 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 }
2793 }
2794
2795 @Override
2796 public void notifyLaunchTaskBehindComplete(IBinder token) {
2797 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2798 }
2799
2800 @Override
2801 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002802 mH.post(() -> {
2803 synchronized (mGlobalLock) {
2804 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002805 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002806 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002807 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002808 } catch (RemoteException e) {
2809 }
2810 }
2811 }
2812
2813 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 }
2815
2816 /** Called from an app when assist data is ready. */
2817 @Override
2818 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2819 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002820 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 synchronized (pae) {
2822 pae.result = extras;
2823 pae.structure = structure;
2824 pae.content = content;
2825 if (referrer != null) {
2826 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2827 }
2828 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002829 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002830 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2831 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 structure.setHomeActivity(pae.isHome);
2833 }
2834 pae.haveResult = true;
2835 pae.notifyAll();
2836 if (pae.intent == null && pae.receiver == null) {
2837 // Caller is just waiting for the result.
2838 return;
2839 }
2840 }
2841 // We are now ready to launch the assist activity.
2842 IAssistDataReceiver sendReceiver = null;
2843 Bundle sendBundle = null;
2844 synchronized (mGlobalLock) {
2845 buildAssistBundleLocked(pae, extras);
2846 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002847 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 if (!exists) {
2849 // Timed out.
2850 return;
2851 }
2852
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 // Caller wants result sent back to them.
2855 sendBundle = new Bundle();
2856 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2857 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2858 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2859 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2860 }
2861 }
2862 if (sendReceiver != null) {
2863 try {
2864 sendReceiver.onHandleAssistData(sendBundle);
2865 } catch (RemoteException e) {
2866 }
2867 return;
2868 }
2869
2870 final long ident = Binder.clearCallingIdentity();
2871 try {
2872 if (TextUtils.equals(pae.intent.getAction(),
2873 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2874 pae.intent.putExtras(pae.extras);
2875 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2876 } else {
2877 pae.intent.replaceExtras(pae.extras);
2878 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2879 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2880 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002881 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882
2883 try {
2884 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2885 } catch (ActivityNotFoundException e) {
2886 Slog.w(TAG, "No activity to handle assist action.", e);
2887 }
2888 }
2889 } finally {
2890 Binder.restoreCallingIdentity(ident);
2891 }
2892 }
2893
2894 @Override
2895 public int addAppTask(IBinder activityToken, Intent intent,
2896 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2897 final int callingUid = Binder.getCallingUid();
2898 final long callingIdent = Binder.clearCallingIdentity();
2899
2900 try {
2901 synchronized (mGlobalLock) {
2902 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2903 if (r == null) {
2904 throw new IllegalArgumentException("Activity does not exist; token="
2905 + activityToken);
2906 }
2907 ComponentName comp = intent.getComponent();
2908 if (comp == null) {
2909 throw new IllegalArgumentException("Intent " + intent
2910 + " must specify explicit component");
2911 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002912 if (thumbnail.getWidth() != mThumbnailWidth
2913 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 throw new IllegalArgumentException("Bad thumbnail size: got "
2915 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002916 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 }
2918 if (intent.getSelector() != null) {
2919 intent.setSelector(null);
2920 }
2921 if (intent.getSourceBounds() != null) {
2922 intent.setSourceBounds(null);
2923 }
2924 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2925 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2926 // The caller has added this as an auto-remove task... that makes no
2927 // sense, so turn off auto-remove.
2928 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2929 }
2930 }
2931 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2932 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2933 if (ainfo.applicationInfo.uid != callingUid) {
2934 throw new SecurityException(
2935 "Can't add task for another application: target uid="
2936 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2937 }
2938
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002939 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002941 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002943 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 // The app has too many tasks already and we can't add any more
2945 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2946 return INVALID_TASK_ID;
2947 }
2948 task.lastTaskDescription.copyFrom(description);
2949
2950 // TODO: Send the thumbnail to WM to store it.
2951
2952 return task.taskId;
2953 }
2954 } finally {
2955 Binder.restoreCallingIdentity(callingIdent);
2956 }
2957 }
2958
2959 @Override
2960 public Point getAppTaskThumbnailSize() {
2961 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002962 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 }
2964 }
2965
2966 @Override
2967 public void setTaskResizeable(int taskId, int resizeableMode) {
2968 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002969 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2971 if (task == null) {
2972 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2973 return;
2974 }
2975 task.setResizeMode(resizeableMode);
2976 }
2977 }
2978
2979 @Override
2980 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002981 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 long ident = Binder.clearCallingIdentity();
2983 try {
2984 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002985 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002986 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987 if (task == null) {
2988 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2989 return;
2990 }
2991 // Place the task in the right stack if it isn't there already based on
2992 // the requested bounds.
2993 // The stack transition logic is:
2994 // - a null bounds on a freeform task moves that task to fullscreen
2995 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2996 // that task to freeform
2997 // - otherwise the task is not moved
2998 ActivityStack stack = task.getStack();
2999 if (!task.getWindowConfiguration().canResizeTask()) {
3000 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3001 }
3002 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3003 stack = stack.getDisplay().getOrCreateStack(
3004 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3005 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3006 stack = stack.getDisplay().getOrCreateStack(
3007 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3008 }
3009
3010 // Reparent the task to the right stack if necessary
3011 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3012 if (stack != task.getStack()) {
3013 // Defer resume until the task is resized below
3014 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3015 DEFER_RESUME, "resizeTask");
3016 preserveWindow = false;
3017 }
3018
3019 // After reparenting (which only resizes the task to the stack bounds), resize the
3020 // task to the actual bounds provided
3021 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3022 }
3023 } finally {
3024 Binder.restoreCallingIdentity(ident);
3025 }
3026 }
3027
3028 @Override
3029 public boolean releaseActivityInstance(IBinder token) {
3030 synchronized (mGlobalLock) {
3031 final long origId = Binder.clearCallingIdentity();
3032 try {
3033 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3034 if (r == null) {
3035 return false;
3036 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003037 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 } finally {
3039 Binder.restoreCallingIdentity(origId);
3040 }
3041 }
3042 }
3043
3044 @Override
3045 public void releaseSomeActivities(IApplicationThread appInt) {
3046 synchronized (mGlobalLock) {
3047 final long origId = Binder.clearCallingIdentity();
3048 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003049 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003050 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 } finally {
3052 Binder.restoreCallingIdentity(origId);
3053 }
3054 }
3055 }
3056
3057 @Override
3058 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003059 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003060 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 != PackageManager.PERMISSION_GRANTED) {
3062 throw new SecurityException("Requires permission "
3063 + android.Manifest.permission.DEVICE_POWER);
3064 }
3065
3066 synchronized (mGlobalLock) {
3067 long ident = Binder.clearCallingIdentity();
3068 if (mKeyguardShown != keyguardShowing) {
3069 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003070 final Message msg = PooledLambda.obtainMessage(
3071 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3072 keyguardShowing);
3073 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003074 }
3075 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003076 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003077 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078 } finally {
3079 Binder.restoreCallingIdentity(ident);
3080 }
3081 }
3082
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003083 mH.post(() -> {
3084 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3085 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3086 }
3087 });
3088 }
3089
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003090 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003091 mH.post(() -> {
3092 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3093 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3094 }
3095 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 }
3097
3098 @Override
3099 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003100 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3101 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102
3103 final File passedIconFile = new File(filePath);
3104 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3105 passedIconFile.getName());
3106 if (!legitIconFile.getPath().equals(filePath)
3107 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3108 throw new IllegalArgumentException("Bad file path: " + filePath
3109 + " passed for userId " + userId);
3110 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003111 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 }
3113
3114 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003115 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3117 final ActivityOptions activityOptions = safeOptions != null
3118 ? safeOptions.getOptions(mStackSupervisor)
3119 : null;
3120 if (activityOptions == null
3121 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3122 || activityOptions.getCustomInPlaceResId() == 0) {
3123 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3124 "with valid animation");
3125 }
lumark588a3e82018-07-20 18:53:54 +08003126 // Get top display of front most application.
3127 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3128 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003129 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3130 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3131 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003132 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003133 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003134 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 }
3136
3137 @Override
3138 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003139 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 synchronized (mGlobalLock) {
3141 final long ident = Binder.clearCallingIdentity();
3142 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003143 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 if (stack == null) {
3145 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3146 return;
3147 }
3148 if (!stack.isActivityTypeStandardOrUndefined()) {
3149 throw new IllegalArgumentException(
3150 "Removing non-standard stack is not allowed.");
3151 }
3152 mStackSupervisor.removeStack(stack);
3153 } finally {
3154 Binder.restoreCallingIdentity(ident);
3155 }
3156 }
3157 }
3158
3159 @Override
3160 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003161 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162
3163 synchronized (mGlobalLock) {
3164 final long ident = Binder.clearCallingIdentity();
3165 try {
3166 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3167 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003168 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 } finally {
3170 Binder.restoreCallingIdentity(ident);
3171 }
3172 }
3173 }
3174
3175 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 public void exitFreeformMode(IBinder token) {
3177 synchronized (mGlobalLock) {
3178 long ident = Binder.clearCallingIdentity();
3179 try {
3180 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3181 if (r == null) {
3182 throw new IllegalArgumentException(
3183 "exitFreeformMode: No activity record matching token=" + token);
3184 }
3185
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003186 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 if (stack == null || !stack.inFreeformWindowingMode()) {
3188 throw new IllegalStateException(
3189 "exitFreeformMode: You can only go fullscreen from freeform.");
3190 }
3191
3192 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3193 } finally {
3194 Binder.restoreCallingIdentity(ident);
3195 }
3196 }
3197 }
3198
3199 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3200 @Override
3201 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003202 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003204 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 }
3206
3207 /** Unregister a task stack listener so that it stops receiving callbacks. */
3208 @Override
3209 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003210 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003212 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 }
3214
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 @Override
3216 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3217 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3218 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3219 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3220 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3221 }
3222
3223 @Override
3224 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3225 IBinder activityToken, int flags) {
3226 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3227 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3228 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3229 }
3230
3231 @Override
3232 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3233 Bundle args) {
3234 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3235 true /* focused */, true /* newSessionId */, userHandle, args,
3236 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3237 }
3238
3239 @Override
3240 public Bundle getAssistContextExtras(int requestType) {
3241 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3242 null, null, true /* focused */, true /* newSessionId */,
3243 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3244 if (pae == null) {
3245 return null;
3246 }
3247 synchronized (pae) {
3248 while (!pae.haveResult) {
3249 try {
3250 pae.wait();
3251 } catch (InterruptedException e) {
3252 }
3253 }
3254 }
3255 synchronized (mGlobalLock) {
3256 buildAssistBundleLocked(pae, pae.result);
3257 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003258 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 }
3260 return pae.extras;
3261 }
3262
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003263 /**
3264 * Binder IPC calls go through the public entry point.
3265 * This can be called with or without the global lock held.
3266 */
3267 private static int checkCallingPermission(String permission) {
3268 return checkPermission(
3269 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3270 }
3271
3272 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003273 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003274 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3275 mAmInternal.enforceCallingPermission(permission, func);
3276 }
3277 }
3278
3279 @VisibleForTesting
3280 int checkGetTasksPermission(String permission, int pid, int uid) {
3281 return checkPermission(permission, pid, uid);
3282 }
3283
3284 static int checkPermission(String permission, int pid, int uid) {
3285 if (permission == null) {
3286 return PackageManager.PERMISSION_DENIED;
3287 }
3288 return checkComponentPermission(permission, pid, uid, -1, true);
3289 }
3290
Wale Ogunwale214f3482018-10-04 11:00:47 -07003291 public static int checkComponentPermission(String permission, int pid, int uid,
3292 int owningUid, boolean exported) {
3293 return ActivityManagerService.checkComponentPermission(
3294 permission, pid, uid, owningUid, exported);
3295 }
3296
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003297 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3298 if (getRecentTasks().isCallerRecents(callingUid)) {
3299 // Always allow the recents component to get tasks
3300 return true;
3301 }
3302
3303 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3304 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3305 if (!allowed) {
3306 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3307 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3308 // Temporary compatibility: some existing apps on the system image may
3309 // still be requesting the old permission and not switched to the new
3310 // one; if so, we'll still allow them full access. This means we need
3311 // to see if they are holding the old permission and are a system app.
3312 try {
3313 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3314 allowed = true;
3315 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3316 + " is using old GET_TASKS but privileged; allowing");
3317 }
3318 } catch (RemoteException e) {
3319 }
3320 }
3321 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3322 + " does not hold REAL_GET_TASKS; limiting output");
3323 }
3324 return allowed;
3325 }
3326
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3328 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3329 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3330 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 "enqueueAssistContext()");
3333
3334 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003335 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 if (activity == null) {
3337 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3338 return null;
3339 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003340 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3342 return null;
3343 }
3344 if (focused) {
3345 if (activityToken != null) {
3346 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3347 if (activity != caller) {
3348 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3349 + " is not current top " + activity);
3350 return null;
3351 }
3352 }
3353 } else {
3354 activity = ActivityRecord.forTokenLocked(activityToken);
3355 if (activity == null) {
3356 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3357 + " couldn't be found");
3358 return null;
3359 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003360 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3362 return null;
3363 }
3364 }
3365
3366 PendingAssistExtras pae;
3367 Bundle extras = new Bundle();
3368 if (args != null) {
3369 extras.putAll(args);
3370 }
3371 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003372 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373
3374 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3375 userHandle);
3376 pae.isHome = activity.isActivityTypeHome();
3377
3378 // Increment the sessionId if necessary
3379 if (newSessionId) {
3380 mViSessionId++;
3381 }
3382 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003383 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3384 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003386 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 } catch (RemoteException e) {
3388 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3389 return null;
3390 }
3391 return pae;
3392 }
3393 }
3394
3395 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3396 if (result != null) {
3397 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3398 }
3399 if (pae.hint != null) {
3400 pae.extras.putBoolean(pae.hint, true);
3401 }
3402 }
3403
3404 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3405 IAssistDataReceiver receiver;
3406 synchronized (mGlobalLock) {
3407 mPendingAssistExtras.remove(pae);
3408 receiver = pae.receiver;
3409 }
3410 if (receiver != null) {
3411 // Caller wants result sent back to them.
3412 Bundle sendBundle = new Bundle();
3413 // At least return the receiver extras
3414 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3415 try {
3416 pae.receiver.onHandleAssistData(sendBundle);
3417 } catch (RemoteException e) {
3418 }
3419 }
3420 }
3421
3422 public class PendingAssistExtras extends Binder implements Runnable {
3423 public final ActivityRecord activity;
3424 public boolean isHome;
3425 public final Bundle extras;
3426 public final Intent intent;
3427 public final String hint;
3428 public final IAssistDataReceiver receiver;
3429 public final int userHandle;
3430 public boolean haveResult = false;
3431 public Bundle result = null;
3432 public AssistStructure structure = null;
3433 public AssistContent content = null;
3434 public Bundle receiverExtras;
3435
3436 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3437 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3438 int _userHandle) {
3439 activity = _activity;
3440 extras = _extras;
3441 intent = _intent;
3442 hint = _hint;
3443 receiver = _receiver;
3444 receiverExtras = _receiverExtras;
3445 userHandle = _userHandle;
3446 }
3447
3448 @Override
3449 public void run() {
3450 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3451 synchronized (this) {
3452 haveResult = true;
3453 notifyAll();
3454 }
3455 pendingAssistExtrasTimedOut(this);
3456 }
3457 }
3458
3459 @Override
3460 public boolean isAssistDataAllowedOnCurrentActivity() {
3461 int userId;
3462 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003463 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3465 return false;
3466 }
3467
3468 final ActivityRecord activity = focusedStack.getTopActivity();
3469 if (activity == null) {
3470 return false;
3471 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003472 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 }
3474 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3475 }
3476
3477 @Override
3478 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3479 long ident = Binder.clearCallingIdentity();
3480 try {
3481 synchronized (mGlobalLock) {
3482 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003483 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 if (top != caller) {
3485 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3486 + " is not current top " + top);
3487 return false;
3488 }
3489 if (!top.nowVisible) {
3490 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3491 + " is not visible");
3492 return false;
3493 }
3494 }
3495 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3496 token);
3497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
3500 }
3501
3502 @Override
3503 public boolean isRootVoiceInteraction(IBinder token) {
3504 synchronized (mGlobalLock) {
3505 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3506 if (r == null) {
3507 return false;
3508 }
3509 return r.rootVoiceInteraction;
3510 }
3511 }
3512
Wale Ogunwalef6733932018-06-27 05:14:34 -07003513 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3514 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3515 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3516 if (activityToCallback == null) return;
3517 activityToCallback.setVoiceSessionLocked(voiceSession);
3518
3519 // Inform the activity
3520 try {
3521 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3522 voiceInteractor);
3523 long token = Binder.clearCallingIdentity();
3524 try {
3525 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3526 } finally {
3527 Binder.restoreCallingIdentity(token);
3528 }
3529 // TODO: VI Should we cache the activity so that it's easier to find later
3530 // rather than scan through all the stacks and activities?
3531 } catch (RemoteException re) {
3532 activityToCallback.clearVoiceSessionLocked();
3533 // TODO: VI Should this terminate the voice session?
3534 }
3535 }
3536
3537 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3538 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3539 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3540 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3541 boolean wasRunningVoice = mRunningVoice != null;
3542 mRunningVoice = session;
3543 if (!wasRunningVoice) {
3544 mVoiceWakeLock.acquire();
3545 updateSleepIfNeededLocked();
3546 }
3547 }
3548 }
3549
3550 void finishRunningVoiceLocked() {
3551 if (mRunningVoice != null) {
3552 mRunningVoice = null;
3553 mVoiceWakeLock.release();
3554 updateSleepIfNeededLocked();
3555 }
3556 }
3557
3558 @Override
3559 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3560 synchronized (mGlobalLock) {
3561 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3562 if (keepAwake) {
3563 mVoiceWakeLock.acquire();
3564 } else {
3565 mVoiceWakeLock.release();
3566 }
3567 }
3568 }
3569 }
3570
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 @Override
3572 public ComponentName getActivityClassForToken(IBinder token) {
3573 synchronized (mGlobalLock) {
3574 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3575 if (r == null) {
3576 return null;
3577 }
3578 return r.intent.getComponent();
3579 }
3580 }
3581
3582 @Override
3583 public String getPackageForToken(IBinder token) {
3584 synchronized (mGlobalLock) {
3585 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3586 if (r == null) {
3587 return null;
3588 }
3589 return r.packageName;
3590 }
3591 }
3592
3593 @Override
3594 public void showLockTaskEscapeMessage(IBinder token) {
3595 synchronized (mGlobalLock) {
3596 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3597 if (r == null) {
3598 return;
3599 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003600 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 }
3602 }
3603
3604 @Override
3605 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003606 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 final long token = Binder.clearCallingIdentity();
3608 try {
3609 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003610 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 }
3612 } finally {
3613 Binder.restoreCallingIdentity(token);
3614 }
3615 }
3616
3617 /**
3618 * Try to place task to provided position. The final position might be different depending on
3619 * current user and stacks state. The task will be moved to target stack if it's currently in
3620 * different stack.
3621 */
3622 @Override
3623 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003624 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 synchronized (mGlobalLock) {
3626 long ident = Binder.clearCallingIdentity();
3627 try {
3628 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3629 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003630 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003631 if (task == null) {
3632 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3633 + taskId);
3634 }
3635
Wale Ogunwaled32da472018-11-16 07:19:28 -08003636 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003637
3638 if (stack == null) {
3639 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3640 + stackId);
3641 }
3642 if (!stack.isActivityTypeStandardOrUndefined()) {
3643 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3644 + " the position of task " + taskId + " in/to non-standard stack");
3645 }
3646
3647 // TODO: Have the callers of this API call a separate reparent method if that is
3648 // what they intended to do vs. having this method also do reparenting.
3649 if (task.getStack() == stack) {
3650 // Change position in current stack.
3651 stack.positionChildAt(task, position);
3652 } else {
3653 // Reparent to new stack.
3654 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3655 !DEFER_RESUME, "positionTaskInStack");
3656 }
3657 } finally {
3658 Binder.restoreCallingIdentity(ident);
3659 }
3660 }
3661 }
3662
3663 @Override
3664 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3665 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3666 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3667 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3668 synchronized (mGlobalLock) {
3669 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3670 if (record == null) {
3671 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3672 + "found for: " + token);
3673 }
3674 record.setSizeConfigurations(horizontalSizeConfiguration,
3675 verticalSizeConfigurations, smallestSizeConfigurations);
3676 }
3677 }
3678
3679 /**
3680 * Dismisses split-screen multi-window mode.
3681 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3682 */
3683 @Override
3684 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003685 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003686 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3687 final long ident = Binder.clearCallingIdentity();
3688 try {
3689 synchronized (mGlobalLock) {
3690 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003691 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003692 if (stack == null) {
3693 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3694 return;
3695 }
3696
3697 if (toTop) {
3698 // Caller wants the current split-screen primary stack to be the top stack after
3699 // it goes fullscreen, so move it to the front.
3700 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003701 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003702 // In this case the current split-screen primary stack shouldn't be the top
3703 // stack after it goes fullscreen, but it current has focus, so we move the
3704 // focus to the top-most split-screen secondary stack next to it.
3705 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3706 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3707 if (otherStack != null) {
3708 otherStack.moveToFront("dismissSplitScreenMode_other");
3709 }
3710 }
3711
Evan Rosky10475742018-09-05 19:02:48 -07003712 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003713 }
3714 } finally {
3715 Binder.restoreCallingIdentity(ident);
3716 }
3717 }
3718
3719 /**
3720 * Dismisses Pip
3721 * @param animate True if the dismissal should be animated.
3722 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3723 * default animation duration should be used.
3724 */
3725 @Override
3726 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003727 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003728 final long ident = Binder.clearCallingIdentity();
3729 try {
3730 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003731 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003732 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003733 if (stack == null) {
3734 Slog.w(TAG, "dismissPip: pinned stack not found.");
3735 return;
3736 }
3737 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3738 throw new IllegalArgumentException("Stack: " + stack
3739 + " doesn't support animated resize.");
3740 }
3741 if (animate) {
3742 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3743 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3744 } else {
3745 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3746 }
3747 }
3748 } finally {
3749 Binder.restoreCallingIdentity(ident);
3750 }
3751 }
3752
3753 @Override
3754 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003755 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003756 synchronized (mGlobalLock) {
3757 mSuppressResizeConfigChanges = suppress;
3758 }
3759 }
3760
3761 /**
3762 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3763 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3764 * activity and clearing the task at the same time.
3765 */
3766 @Override
3767 // TODO: API should just be about changing windowing modes...
3768 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003769 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003770 "moveTasksToFullscreenStack()");
3771 synchronized (mGlobalLock) {
3772 final long origId = Binder.clearCallingIdentity();
3773 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003774 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775 if (stack != null){
3776 if (!stack.isActivityTypeStandardOrUndefined()) {
3777 throw new IllegalArgumentException(
3778 "You can't move tasks from non-standard stacks.");
3779 }
3780 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3781 }
3782 } finally {
3783 Binder.restoreCallingIdentity(origId);
3784 }
3785 }
3786 }
3787
3788 /**
3789 * Moves the top activity in the input stackId to the pinned stack.
3790 *
3791 * @param stackId Id of stack to move the top activity to pinned stack.
3792 * @param bounds Bounds to use for pinned stack.
3793 *
3794 * @return True if the top activity of the input stack was successfully moved to the pinned
3795 * stack.
3796 */
3797 @Override
3798 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003799 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003800 "moveTopActivityToPinnedStack()");
3801 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003802 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003803 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3804 + "Device doesn't support picture-in-picture mode");
3805 }
3806
3807 long ident = Binder.clearCallingIdentity();
3808 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003809 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 } finally {
3811 Binder.restoreCallingIdentity(ident);
3812 }
3813 }
3814 }
3815
3816 @Override
3817 public boolean isInMultiWindowMode(IBinder token) {
3818 final long origId = Binder.clearCallingIdentity();
3819 try {
3820 synchronized (mGlobalLock) {
3821 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3822 if (r == null) {
3823 return false;
3824 }
3825 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3826 return r.inMultiWindowMode();
3827 }
3828 } finally {
3829 Binder.restoreCallingIdentity(origId);
3830 }
3831 }
3832
3833 @Override
3834 public boolean isInPictureInPictureMode(IBinder token) {
3835 final long origId = Binder.clearCallingIdentity();
3836 try {
3837 synchronized (mGlobalLock) {
3838 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3839 }
3840 } finally {
3841 Binder.restoreCallingIdentity(origId);
3842 }
3843 }
3844
3845 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003846 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3847 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 return false;
3849 }
3850
3851 // If we are animating to fullscreen then we have already dispatched the PIP mode
3852 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003853 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3854 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 }
3856
3857 @Override
3858 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3859 final long origId = Binder.clearCallingIdentity();
3860 try {
3861 synchronized (mGlobalLock) {
3862 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3863 "enterPictureInPictureMode", token, params);
3864
3865 // If the activity is already in picture in picture mode, then just return early
3866 if (isInPictureInPictureMode(r)) {
3867 return true;
3868 }
3869
3870 // Activity supports picture-in-picture, now check that we can enter PiP at this
3871 // point, if it is
3872 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3873 false /* beforeStopping */)) {
3874 return false;
3875 }
3876
3877 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003878 synchronized (mGlobalLock) {
3879 // Only update the saved args from the args that are set
3880 r.pictureInPictureArgs.copyOnlySet(params);
3881 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3882 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3883 // Adjust the source bounds by the insets for the transition down
3884 final Rect sourceBounds = new Rect(
3885 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003886 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003887 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003888 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003889 stack.setPictureInPictureAspectRatio(aspectRatio);
3890 stack.setPictureInPictureActions(actions);
3891 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3892 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3893 logPictureInPictureArgs(params);
3894 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895 };
3896
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003897 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 // If the keyguard is showing or occluded, then try and dismiss it before
3899 // entering picture-in-picture (this will prompt the user to authenticate if the
3900 // device is currently locked).
3901 dismissKeyguard(token, new KeyguardDismissCallback() {
3902 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003903 public void onDismissSucceeded() {
3904 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003905 }
3906 }, null /* message */);
3907 } else {
3908 // Enter picture in picture immediately otherwise
3909 enterPipRunnable.run();
3910 }
3911 return true;
3912 }
3913 } finally {
3914 Binder.restoreCallingIdentity(origId);
3915 }
3916 }
3917
3918 @Override
3919 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3920 final long origId = Binder.clearCallingIdentity();
3921 try {
3922 synchronized (mGlobalLock) {
3923 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3924 "setPictureInPictureParams", token, params);
3925
3926 // Only update the saved args from the args that are set
3927 r.pictureInPictureArgs.copyOnlySet(params);
3928 if (r.inPinnedWindowingMode()) {
3929 // If the activity is already in picture-in-picture, update the pinned stack now
3930 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3931 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003932 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 if (!stack.isAnimatingBoundsToFullscreen()) {
3934 stack.setPictureInPictureAspectRatio(
3935 r.pictureInPictureArgs.getAspectRatio());
3936 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3937 }
3938 }
3939 logPictureInPictureArgs(params);
3940 }
3941 } finally {
3942 Binder.restoreCallingIdentity(origId);
3943 }
3944 }
3945
3946 @Override
3947 public int getMaxNumPictureInPictureActions(IBinder token) {
3948 // Currently, this is a static constant, but later, we may change this to be dependent on
3949 // the context of the activity
3950 return 3;
3951 }
3952
3953 private void logPictureInPictureArgs(PictureInPictureParams params) {
3954 if (params.hasSetActions()) {
3955 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3956 params.getActions().size());
3957 }
3958 if (params.hasSetAspectRatio()) {
3959 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3960 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3961 MetricsLogger.action(lm);
3962 }
3963 }
3964
3965 /**
3966 * Checks the state of the system and the activity associated with the given {@param token} to
3967 * verify that picture-in-picture is supported for that activity.
3968 *
3969 * @return the activity record for the given {@param token} if all the checks pass.
3970 */
3971 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3972 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003973 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 throw new IllegalStateException(caller
3975 + ": Device doesn't support picture-in-picture mode.");
3976 }
3977
3978 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3979 if (r == null) {
3980 throw new IllegalStateException(caller
3981 + ": Can't find activity for token=" + token);
3982 }
3983
3984 if (!r.supportsPictureInPicture()) {
3985 throw new IllegalStateException(caller
3986 + ": Current activity does not support picture-in-picture.");
3987 }
3988
3989 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003990 && !mWindowManager.isValidPictureInPictureAspectRatio(
3991 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 final float minAspectRatio = mContext.getResources().getFloat(
3993 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3994 final float maxAspectRatio = mContext.getResources().getFloat(
3995 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3996 throw new IllegalArgumentException(String.format(caller
3997 + ": Aspect ratio is too extreme (must be between %f and %f).",
3998 minAspectRatio, maxAspectRatio));
3999 }
4000
4001 // Truncate the number of actions if necessary
4002 params.truncateActions(getMaxNumPictureInPictureActions(token));
4003
4004 return r;
4005 }
4006
4007 @Override
4008 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 synchronized (mGlobalLock) {
4011 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4012 if (r == null) {
4013 throw new IllegalArgumentException("Activity does not exist; token="
4014 + activityToken);
4015 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004016 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 }
4018 }
4019
4020 @Override
4021 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4022 Rect tempDockedTaskInsetBounds,
4023 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 long ident = Binder.clearCallingIdentity();
4026 try {
4027 synchronized (mGlobalLock) {
4028 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4029 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4030 PRESERVE_WINDOWS);
4031 }
4032 } finally {
4033 Binder.restoreCallingIdentity(ident);
4034 }
4035 }
4036
4037 @Override
4038 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004039 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 final long ident = Binder.clearCallingIdentity();
4041 try {
4042 synchronized (mGlobalLock) {
4043 mStackSupervisor.setSplitScreenResizing(resizing);
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(ident);
4047 }
4048 }
4049
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 /**
4051 * Check that we have the features required for VR-related API calls, and throw an exception if
4052 * not.
4053 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004054 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004055 if (!mContext.getPackageManager().hasSystemFeature(
4056 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4057 throw new UnsupportedOperationException("VR mode not supported on this device!");
4058 }
4059 }
4060
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 @Override
4062 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004063 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064
4065 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4066
4067 ActivityRecord r;
4068 synchronized (mGlobalLock) {
4069 r = ActivityRecord.isInStackLocked(token);
4070 }
4071
4072 if (r == null) {
4073 throw new IllegalArgumentException();
4074 }
4075
4076 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004077 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 VrManagerInternal.NO_ERROR) {
4079 return err;
4080 }
4081
4082 // Clear the binder calling uid since this path may call moveToTask().
4083 final long callingId = Binder.clearCallingIdentity();
4084 try {
4085 synchronized (mGlobalLock) {
4086 r.requestedVrComponent = (enabled) ? packageName : null;
4087
4088 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004089 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004090 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 }
4092 return 0;
4093 }
4094 } finally {
4095 Binder.restoreCallingIdentity(callingId);
4096 }
4097 }
4098
4099 @Override
4100 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4101 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4102 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004103 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004104 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4105 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4106 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004107 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004108 || activity.voiceSession != null) {
4109 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4110 return;
4111 }
4112 if (activity.pendingVoiceInteractionStart) {
4113 Slog.w(TAG, "Pending start of voice interaction already.");
4114 return;
4115 }
4116 activity.pendingVoiceInteractionStart = true;
4117 }
4118 LocalServices.getService(VoiceInteractionManagerInternal.class)
4119 .startLocalVoiceInteraction(callingActivity, options);
4120 }
4121
4122 @Override
4123 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4124 LocalServices.getService(VoiceInteractionManagerInternal.class)
4125 .stopLocalVoiceInteraction(callingActivity);
4126 }
4127
4128 @Override
4129 public boolean supportsLocalVoiceInteraction() {
4130 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4131 .supportsLocalVoiceInteraction();
4132 }
4133
4134 /** Notifies all listeners when the pinned stack animation starts. */
4135 @Override
4136 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004137 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138 }
4139
4140 /** Notifies all listeners when the pinned stack animation ends. */
4141 @Override
4142 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004143 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 }
4145
4146 @Override
4147 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004148 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 final long ident = Binder.clearCallingIdentity();
4150 try {
4151 synchronized (mGlobalLock) {
4152 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4153 }
4154 } finally {
4155 Binder.restoreCallingIdentity(ident);
4156 }
4157 }
4158
4159 @Override
4160 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004161 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162
4163 synchronized (mGlobalLock) {
4164 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004165 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 // Call might come when display is not yet added or has already been removed.
4167 if (DEBUG_CONFIGURATION) {
4168 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4169 + displayId);
4170 }
4171 return false;
4172 }
4173
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004174 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004175 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004176 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 }
4178
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004179 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004180 final Message msg = PooledLambda.obtainMessage(
4181 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4182 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004183 }
4184
4185 final long origId = Binder.clearCallingIdentity();
4186 try {
4187 if (values != null) {
4188 Settings.System.clearConfiguration(values);
4189 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004190 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004191 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4192 return mTmpUpdateConfigurationResult.changes != 0;
4193 } finally {
4194 Binder.restoreCallingIdentity(origId);
4195 }
4196 }
4197 }
4198
4199 @Override
4200 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004201 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202
4203 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 }
4208
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004209 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004210 final Message msg = PooledLambda.obtainMessage(
4211 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4212 DEFAULT_DISPLAY);
4213 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004214 }
4215
4216 final long origId = Binder.clearCallingIdentity();
4217 try {
4218 if (values != null) {
4219 Settings.System.clearConfiguration(values);
4220 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004221 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 UserHandle.USER_NULL, false /* deferResume */,
4223 mTmpUpdateConfigurationResult);
4224 return mTmpUpdateConfigurationResult.changes != 0;
4225 } finally {
4226 Binder.restoreCallingIdentity(origId);
4227 }
4228 }
4229 }
4230
4231 @Override
4232 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4233 CharSequence message) {
4234 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4237 }
4238 final long callingId = Binder.clearCallingIdentity();
4239 try {
4240 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004241 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 }
4243 } finally {
4244 Binder.restoreCallingIdentity(callingId);
4245 }
4246 }
4247
4248 @Override
4249 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 "cancelTaskWindowTransition()");
4252 final long ident = Binder.clearCallingIdentity();
4253 try {
4254 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004255 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 MATCH_TASK_IN_STACKS_ONLY);
4257 if (task == null) {
4258 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4259 return;
4260 }
4261 task.cancelWindowTransition();
4262 }
4263 } finally {
4264 Binder.restoreCallingIdentity(ident);
4265 }
4266 }
4267
4268 @Override
4269 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004270 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004271 final long ident = Binder.clearCallingIdentity();
4272 try {
4273 final TaskRecord task;
4274 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004275 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4277 if (task == null) {
4278 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4279 return null;
4280 }
4281 }
4282 // Don't call this while holding the lock as this operation might hit the disk.
4283 return task.getSnapshot(reducedResolution);
4284 } finally {
4285 Binder.restoreCallingIdentity(ident);
4286 }
4287 }
4288
4289 @Override
4290 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4291 synchronized (mGlobalLock) {
4292 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4293 if (r == null) {
4294 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4295 + token);
4296 return;
4297 }
4298 final long origId = Binder.clearCallingIdentity();
4299 try {
4300 r.setDisablePreviewScreenshots(disable);
4301 } finally {
4302 Binder.restoreCallingIdentity(origId);
4303 }
4304 }
4305 }
4306
4307 /** Return the user id of the last resumed activity. */
4308 @Override
4309 public @UserIdInt
4310 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4313 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004314 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004315 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004317 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 }
4319 }
4320
4321 @Override
4322 public void updateLockTaskFeatures(int userId, int flags) {
4323 final int callingUid = Binder.getCallingUid();
4324 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004325 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004326 "updateLockTaskFeatures()");
4327 }
4328 synchronized (mGlobalLock) {
4329 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4330 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004331 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 }
4333 }
4334
4335 @Override
4336 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4337 synchronized (mGlobalLock) {
4338 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4339 if (r == null) {
4340 return;
4341 }
4342 final long origId = Binder.clearCallingIdentity();
4343 try {
4344 r.setShowWhenLocked(showWhenLocked);
4345 } finally {
4346 Binder.restoreCallingIdentity(origId);
4347 }
4348 }
4349 }
4350
4351 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004352 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4353 synchronized (mGlobalLock) {
4354 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4355 if (r == null) {
4356 return;
4357 }
4358 final long origId = Binder.clearCallingIdentity();
4359 try {
4360 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4361 } finally {
4362 Binder.restoreCallingIdentity(origId);
4363 }
4364 }
4365 }
4366
4367 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4369 synchronized (mGlobalLock) {
4370 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4371 if (r == null) {
4372 return;
4373 }
4374 final long origId = Binder.clearCallingIdentity();
4375 try {
4376 r.setTurnScreenOn(turnScreenOn);
4377 } finally {
4378 Binder.restoreCallingIdentity(origId);
4379 }
4380 }
4381 }
4382
4383 @Override
4384 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 "registerRemoteAnimations");
4387 definition.setCallingPid(Binder.getCallingPid());
4388 synchronized (mGlobalLock) {
4389 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4390 if (r == null) {
4391 return;
4392 }
4393 final long origId = Binder.clearCallingIdentity();
4394 try {
4395 r.registerRemoteAnimations(definition);
4396 } finally {
4397 Binder.restoreCallingIdentity(origId);
4398 }
4399 }
4400 }
4401
4402 @Override
4403 public void registerRemoteAnimationForNextActivityStart(String packageName,
4404 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004405 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 "registerRemoteAnimationForNextActivityStart");
4407 adapter.setCallingPid(Binder.getCallingPid());
4408 synchronized (mGlobalLock) {
4409 final long origId = Binder.clearCallingIdentity();
4410 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004411 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 packageName, adapter);
4413 } finally {
4414 Binder.restoreCallingIdentity(origId);
4415 }
4416 }
4417 }
4418
Evan Rosky966759f2019-01-15 10:33:58 -08004419 @Override
4420 public void registerRemoteAnimationsForDisplay(int displayId,
4421 RemoteAnimationDefinition definition) {
4422 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4423 "registerRemoteAnimations");
4424 definition.setCallingPid(Binder.getCallingPid());
4425 synchronized (mGlobalLock) {
4426 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4427 if (display == null) {
4428 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4429 return;
4430 }
4431 final long origId = Binder.clearCallingIdentity();
4432 try {
4433 display.mDisplayContent.registerRemoteAnimations(definition);
4434 } finally {
4435 Binder.restoreCallingIdentity(origId);
4436 }
4437 }
4438 }
4439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4441 @Override
4442 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4443 synchronized (mGlobalLock) {
4444 final long origId = Binder.clearCallingIdentity();
4445 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004446 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 } finally {
4448 Binder.restoreCallingIdentity(origId);
4449 }
4450 }
4451 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004452
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004453 @Override
4454 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004456 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004457 final int pid = Binder.getCallingPid();
4458 final WindowProcessController wpc = mPidMap.get(pid);
4459 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004460 }
4461 }
4462
4463 @Override
4464 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004466 != PERMISSION_GRANTED) {
4467 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4468 + Binder.getCallingPid()
4469 + ", uid=" + Binder.getCallingUid()
4470 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4471 Slog.w(TAG, msg);
4472 throw new SecurityException(msg);
4473 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004474 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004475 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004476 final int pid = Binder.getCallingPid();
4477 final WindowProcessController proc = mPidMap.get(pid);
4478 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004479 }
4480 }
4481
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004482 @Override
4483 public void stopAppSwitches() {
4484 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4485 synchronized (mGlobalLock) {
4486 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4487 mDidAppSwitch = false;
4488 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4489 }
4490 }
4491
4492 @Override
4493 public void resumeAppSwitches() {
4494 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4495 synchronized (mGlobalLock) {
4496 // Note that we don't execute any pending app switches... we will
4497 // let those wait until either the timeout, or the next start
4498 // activity request.
4499 mAppSwitchesAllowedTime = 0;
4500 }
4501 }
4502
4503 void onStartActivitySetDidAppSwitch() {
4504 if (mDidAppSwitch) {
4505 // This is the second allowed switch since we stopped switches, so now just generally
4506 // allow switches. Use case:
4507 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4508 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4509 // anyone to switch again).
4510 mAppSwitchesAllowedTime = 0;
4511 } else {
4512 mDidAppSwitch = true;
4513 }
4514 }
4515
4516 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004517 boolean shouldDisableNonVrUiLocked() {
4518 return mVrController.shouldDisableNonVrUiLocked();
4519 }
4520
Wale Ogunwale53783742018-09-16 10:21:51 -07004521 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004522 // VR apps are expected to run in a main display. If an app is turning on VR for
4523 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4524 // fullscreen stack before enabling VR Mode.
4525 // TODO: The goal of this code is to keep the VR app on the main display. When the
4526 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4527 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4528 // option would be a better choice here.
4529 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4530 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4531 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004532 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004533 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004534 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004535 }
4536 mH.post(() -> {
4537 if (!mVrController.onVrModeChanged(r)) {
4538 return;
4539 }
4540 synchronized (mGlobalLock) {
4541 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4542 mWindowManager.disableNonVrUi(disableNonVrUi);
4543 if (disableNonVrUi) {
4544 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4545 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004546 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004547 }
4548 }
4549 });
4550 }
4551
Wale Ogunwale53783742018-09-16 10:21:51 -07004552 @Override
4553 public int getPackageScreenCompatMode(String packageName) {
4554 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4555 synchronized (mGlobalLock) {
4556 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4557 }
4558 }
4559
4560 @Override
4561 public void setPackageScreenCompatMode(String packageName, int mode) {
4562 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4563 "setPackageScreenCompatMode");
4564 synchronized (mGlobalLock) {
4565 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4566 }
4567 }
4568
4569 @Override
4570 public boolean getPackageAskScreenCompat(String packageName) {
4571 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4572 synchronized (mGlobalLock) {
4573 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4574 }
4575 }
4576
4577 @Override
4578 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4579 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4580 "setPackageAskScreenCompat");
4581 synchronized (mGlobalLock) {
4582 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4583 }
4584 }
4585
Wale Ogunwale64258362018-10-16 15:13:37 -07004586 public static String relaunchReasonToString(int relaunchReason) {
4587 switch (relaunchReason) {
4588 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4589 return "window_resize";
4590 case RELAUNCH_REASON_FREE_RESIZE:
4591 return "free_resize";
4592 default:
4593 return null;
4594 }
4595 }
4596
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004597 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004598 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004599 }
4600
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004601 /** Pokes the task persister. */
4602 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4603 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4604 }
4605
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004606 boolean isKeyguardLocked() {
4607 return mKeyguardController.isKeyguardLocked();
4608 }
4609
Garfield Tan01548632018-11-27 10:15:48 -08004610 /**
4611 * Clears launch params for the given package.
4612 * @param packageNames the names of the packages of which the launch params are to be cleared
4613 */
4614 @Override
4615 public void clearLaunchParamsForPackages(List<String> packageNames) {
4616 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4617 "clearLaunchParamsForPackages");
4618 synchronized (mGlobalLock) {
4619 for (int i = 0; i < packageNames.size(); ++i) {
4620 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4621 }
4622 }
4623 }
4624
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004625 /**
4626 * Makes the display with the given id a single task instance display. I.e the display can only
4627 * contain one task.
4628 */
4629 @Override
4630 public void setDisplayToSingleTaskInstance(int displayId) {
4631 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4632 "setDisplayToSingleTaskInstance");
4633 final long origId = Binder.clearCallingIdentity();
4634 try {
4635 final ActivityDisplay display =
4636 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4637 if (display != null) {
4638 display.setDisplayToSingleTaskInstance();
4639 }
4640 } finally {
4641 Binder.restoreCallingIdentity(origId);
4642 }
4643 }
4644
Wale Ogunwale31913b52018-10-13 08:29:31 -07004645 void dumpLastANRLocked(PrintWriter pw) {
4646 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4647 if (mLastANRState == null) {
4648 pw.println(" <no ANR has occurred since boot>");
4649 } else {
4650 pw.println(mLastANRState);
4651 }
4652 }
4653
4654 void dumpLastANRTracesLocked(PrintWriter pw) {
4655 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4656
4657 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4658 if (ArrayUtils.isEmpty(files)) {
4659 pw.println(" <no ANR has occurred since boot>");
4660 return;
4661 }
4662 // Find the latest file.
4663 File latest = null;
4664 for (File f : files) {
4665 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4666 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004667 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004668 }
4669 pw.print("File: ");
4670 pw.print(latest.getName());
4671 pw.println();
4672 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4673 String line;
4674 while ((line = in.readLine()) != null) {
4675 pw.println(line);
4676 }
4677 } catch (IOException e) {
4678 pw.print("Unable to read: ");
4679 pw.print(e);
4680 pw.println();
4681 }
4682 }
4683
4684 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4685 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4686 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4687 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4688 }
4689
4690 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4691 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4692 pw.println(header);
4693
Wale Ogunwaled32da472018-11-16 07:19:28 -08004694 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004695 dumpPackage);
4696 boolean needSep = printedAnything;
4697
4698 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004699 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004700 " ResumedActivity: ");
4701 if (printed) {
4702 printedAnything = true;
4703 needSep = false;
4704 }
4705
4706 if (dumpPackage == null) {
4707 if (needSep) {
4708 pw.println();
4709 }
4710 printedAnything = true;
4711 mStackSupervisor.dump(pw, " ");
4712 }
4713
4714 if (!printedAnything) {
4715 pw.println(" (nothing)");
4716 }
4717 }
4718
4719 void dumpActivityContainersLocked(PrintWriter pw) {
4720 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004721 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004722 pw.println(" ");
4723 }
4724
4725 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4726 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4727 getActivityStartController().dump(pw, "", dumpPackage);
4728 }
4729
4730 /**
4731 * There are three things that cmd can be:
4732 * - a flattened component name that matches an existing activity
4733 * - the cmd arg isn't the flattened component name of an existing activity:
4734 * dump all activity whose component contains the cmd as a substring
4735 * - A hex number of the ActivityRecord object instance.
4736 *
4737 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4738 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4739 */
4740 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4741 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4742 ArrayList<ActivityRecord> activities;
4743
4744 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004745 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004746 dumpFocusedStackOnly);
4747 }
4748
4749 if (activities.size() <= 0) {
4750 return false;
4751 }
4752
4753 String[] newArgs = new String[args.length - opti];
4754 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4755
4756 TaskRecord lastTask = null;
4757 boolean needSep = false;
4758 for (int i = activities.size() - 1; i >= 0; i--) {
4759 ActivityRecord r = activities.get(i);
4760 if (needSep) {
4761 pw.println();
4762 }
4763 needSep = true;
4764 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004765 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004766 if (lastTask != task) {
4767 lastTask = task;
4768 pw.print("TASK "); pw.print(lastTask.affinity);
4769 pw.print(" id="); pw.print(lastTask.taskId);
4770 pw.print(" userId="); pw.println(lastTask.userId);
4771 if (dumpAll) {
4772 lastTask.dump(pw, " ");
4773 }
4774 }
4775 }
4776 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4777 }
4778 return true;
4779 }
4780
4781 /**
4782 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4783 * there is a thread associated with the activity.
4784 */
4785 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4786 final ActivityRecord r, String[] args, boolean dumpAll) {
4787 String innerPrefix = prefix + " ";
4788 synchronized (mGlobalLock) {
4789 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4790 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4791 pw.print(" pid=");
4792 if (r.hasProcess()) pw.println(r.app.getPid());
4793 else pw.println("(not running)");
4794 if (dumpAll) {
4795 r.dump(pw, innerPrefix);
4796 }
4797 }
4798 if (r.attachedToProcess()) {
4799 // flush anything that is already in the PrintWriter since the thread is going
4800 // to write to the file descriptor directly
4801 pw.flush();
4802 try {
4803 TransferPipe tp = new TransferPipe();
4804 try {
4805 r.app.getThread().dumpActivity(tp.getWriteFd(),
4806 r.appToken, innerPrefix, args);
4807 tp.go(fd);
4808 } finally {
4809 tp.kill();
4810 }
4811 } catch (IOException e) {
4812 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4813 } catch (RemoteException e) {
4814 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4815 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004816 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004817 }
4818
sanryhuang498e77e2018-12-06 14:57:01 +08004819 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4820 boolean testPssMode) {
4821 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4822 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4823 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004824 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004825 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4826 st.toString());
4827 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004828 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4829 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4830 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004831 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4832 testPssMode);
4833 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004834 }
4835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004836 int getCurrentUserId() {
4837 return mAmInternal.getCurrentUserId();
4838 }
4839
4840 private void enforceNotIsolatedCaller(String caller) {
4841 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4842 throw new SecurityException("Isolated process not allowed to call " + caller);
4843 }
4844 }
4845
Wale Ogunwalef6733932018-06-27 05:14:34 -07004846 public Configuration getConfiguration() {
4847 Configuration ci;
4848 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004849 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004850 ci.userSetLocale = false;
4851 }
4852 return ci;
4853 }
4854
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004855 /**
4856 * Current global configuration information. Contains general settings for the entire system,
4857 * also corresponds to the merged configuration of the default display.
4858 */
4859 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004860 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861 }
4862
4863 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4864 boolean initLocale) {
4865 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4866 }
4867
4868 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4869 boolean initLocale, boolean deferResume) {
4870 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4871 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4872 UserHandle.USER_NULL, deferResume);
4873 }
4874
Wale Ogunwale59507092018-10-29 09:00:30 -07004875 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004876 final long origId = Binder.clearCallingIdentity();
4877 try {
4878 synchronized (mGlobalLock) {
4879 updateConfigurationLocked(values, null, false, true, userId,
4880 false /* deferResume */);
4881 }
4882 } finally {
4883 Binder.restoreCallingIdentity(origId);
4884 }
4885 }
4886
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004887 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4888 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4889 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4890 deferResume, null /* result */);
4891 }
4892
4893 /**
4894 * Do either or both things: (1) change the current configuration, and (2)
4895 * make sure the given activity is running with the (now) current
4896 * configuration. Returns true if the activity has been left running, or
4897 * false if <var>starting</var> is being destroyed to match the new
4898 * configuration.
4899 *
4900 * @param userId is only used when persistent parameter is set to true to persist configuration
4901 * for that particular user
4902 */
4903 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4904 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4905 ActivityTaskManagerService.UpdateConfigurationResult result) {
4906 int changes = 0;
4907 boolean kept = true;
4908
4909 if (mWindowManager != null) {
4910 mWindowManager.deferSurfaceLayout();
4911 }
4912 try {
4913 if (values != null) {
4914 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4915 deferResume);
4916 }
4917
4918 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4919 } finally {
4920 if (mWindowManager != null) {
4921 mWindowManager.continueSurfaceLayout();
4922 }
4923 }
4924
4925 if (result != null) {
4926 result.changes = changes;
4927 result.activityRelaunched = !kept;
4928 }
4929 return kept;
4930 }
4931
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004932 /** Update default (global) configuration and notify listeners about changes. */
4933 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4934 boolean persistent, int userId, boolean deferResume) {
4935 mTempConfig.setTo(getGlobalConfiguration());
4936 final int changes = mTempConfig.updateFrom(values);
4937 if (changes == 0) {
4938 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4939 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4940 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4941 // (even if there are no actual changes) to unfreeze the window.
4942 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4943 return 0;
4944 }
4945
4946 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4947 "Updating global configuration to: " + values);
4948
4949 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4950 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4951 values.colorMode,
4952 values.densityDpi,
4953 values.fontScale,
4954 values.hardKeyboardHidden,
4955 values.keyboard,
4956 values.keyboardHidden,
4957 values.mcc,
4958 values.mnc,
4959 values.navigation,
4960 values.navigationHidden,
4961 values.orientation,
4962 values.screenHeightDp,
4963 values.screenLayout,
4964 values.screenWidthDp,
4965 values.smallestScreenWidthDp,
4966 values.touchscreen,
4967 values.uiMode);
4968
4969
4970 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4971 final LocaleList locales = values.getLocales();
4972 int bestLocaleIndex = 0;
4973 if (locales.size() > 1) {
4974 if (mSupportedSystemLocales == null) {
4975 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4976 }
4977 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4978 }
4979 SystemProperties.set("persist.sys.locale",
4980 locales.get(bestLocaleIndex).toLanguageTag());
4981 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004982
4983 final Message m = PooledLambda.obtainMessage(
4984 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4985 locales.get(bestLocaleIndex));
4986 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004987 }
4988
Yunfan Chen75157d72018-07-27 14:47:21 +09004989 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004990
4991 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004992 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004993
4994 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4995 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004996 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004997
4998 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004999 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005000
5001 AttributeCache ac = AttributeCache.instance();
5002 if (ac != null) {
5003 ac.updateConfiguration(mTempConfig);
5004 }
5005
5006 // Make sure all resources in our process are updated right now, so that anyone who is going
5007 // to retrieve resource values after we return will be sure to get the new ones. This is
5008 // especially important during boot, where the first config change needs to guarantee all
5009 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005010 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005011
5012 // We need another copy of global config because we're scheduling some calls instead of
5013 // running them in place. We need to be sure that object we send will be handled unchanged.
5014 final Configuration configCopy = new Configuration(mTempConfig);
5015 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005016 final Message msg = PooledLambda.obtainMessage(
5017 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5018 this, userId, configCopy);
5019 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005020 }
5021
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005022 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005023 final int pid = mPidMap.keyAt(i);
5024 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005025 if (DEBUG_CONFIGURATION) {
5026 Slog.v(TAG_CONFIGURATION, "Update process config of "
5027 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005028 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005029 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005030 }
5031
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005032 final Message msg = PooledLambda.obtainMessage(
5033 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5034 mAmInternal, changes, initLocale);
5035 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005036
5037 // Override configuration of the default display duplicates global config, so we need to
5038 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005039 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040 DEFAULT_DISPLAY);
5041
5042 return changes;
5043 }
5044
5045 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5046 boolean deferResume, int displayId) {
5047 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5048 displayId, null /* result */);
5049 }
5050
5051 /**
5052 * Updates override configuration specific for the selected display. If no config is provided,
5053 * new one will be computed in WM based on current display info.
5054 */
5055 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5056 ActivityRecord starting, boolean deferResume, int displayId,
5057 ActivityTaskManagerService.UpdateConfigurationResult result) {
5058 int changes = 0;
5059 boolean kept = true;
5060
5061 if (mWindowManager != null) {
5062 mWindowManager.deferSurfaceLayout();
5063 }
5064 try {
5065 if (values != null) {
5066 if (displayId == DEFAULT_DISPLAY) {
5067 // Override configuration of the default display duplicates global config, so
5068 // we're calling global config update instead for default display. It will also
5069 // apply the correct override config.
5070 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5071 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5072 } else {
5073 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5074 }
5075 }
5076
5077 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5078 } finally {
5079 if (mWindowManager != null) {
5080 mWindowManager.continueSurfaceLayout();
5081 }
5082 }
5083
5084 if (result != null) {
5085 result.changes = changes;
5086 result.activityRelaunched = !kept;
5087 }
5088 return kept;
5089 }
5090
5091 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5092 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005093 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005094 final int changes = mTempConfig.updateFrom(values);
5095 if (changes != 0) {
5096 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5097 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005098 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005099
5100 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5101 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005102 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005103
Wale Ogunwale5c918702018-10-18 11:06:33 -07005104 // Post message to start process to avoid possible deadlock of calling into AMS with
5105 // the ATMS lock held.
5106 final Message msg = PooledLambda.obtainMessage(
5107 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5108 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5109 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005110 }
5111 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005112 return changes;
5113 }
5114
Wale Ogunwalef6733932018-06-27 05:14:34 -07005115 private void updateEventDispatchingLocked(boolean booted) {
5116 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5117 }
5118
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005119 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5120 final ContentResolver resolver = mContext.getContentResolver();
5121 Settings.System.putConfigurationForUser(resolver, config, userId);
5122 }
5123
5124 private void sendLocaleToMountDaemonMsg(Locale l) {
5125 try {
5126 IBinder service = ServiceManager.getService("mount");
5127 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5128 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5129 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5130 } catch (RemoteException e) {
5131 Log.e(TAG, "Error storing locale for decryption UI", e);
5132 }
5133 }
5134
Alison Cichowlas3e340502018-08-07 17:15:01 -04005135 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5136 mStartActivitySources.remove(permissionToken);
5137 mExpiredStartAsCallerTokens.add(permissionToken);
5138 }
5139
5140 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5141 mExpiredStartAsCallerTokens.remove(permissionToken);
5142 }
5143
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005144 boolean isActivityStartsLoggingEnabled() {
5145 return mAmInternal.isActivityStartsLoggingEnabled();
5146 }
5147
Michal Karpinski8596ded2018-11-14 14:43:48 +00005148 boolean isBackgroundActivityStartsEnabled() {
5149 return mAmInternal.isBackgroundActivityStartsEnabled();
5150 }
5151
Wale Ogunwalef6733932018-06-27 05:14:34 -07005152 void enableScreenAfterBoot(boolean booted) {
5153 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5154 SystemClock.uptimeMillis());
5155 mWindowManager.enableScreenAfterBoot();
5156
5157 synchronized (mGlobalLock) {
5158 updateEventDispatchingLocked(booted);
5159 }
5160 }
5161
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005162 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5163 if (r == null || !r.hasProcess()) {
5164 return KEY_DISPATCHING_TIMEOUT_MS;
5165 }
5166 return getInputDispatchingTimeoutLocked(r.app);
5167 }
5168
5169 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005170 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005171 }
5172
Wale Ogunwalef6733932018-06-27 05:14:34 -07005173 /**
5174 * Decide based on the configuration whether we should show the ANR,
5175 * crash, etc dialogs. The idea is that if there is no affordance to
5176 * press the on-screen buttons, or the user experience would be more
5177 * greatly impacted than the crash itself, we shouldn't show the dialog.
5178 *
5179 * A thought: SystemUI might also want to get told about this, the Power
5180 * dialog / global actions also might want different behaviors.
5181 */
5182 private void updateShouldShowDialogsLocked(Configuration config) {
5183 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5184 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5185 && config.navigation == Configuration.NAVIGATION_NONAV);
5186 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5187 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5188 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5189 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5190 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5191 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5192 HIDE_ERROR_DIALOGS, 0) != 0;
5193 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5194 }
5195
5196 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5197 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5198 FONT_SCALE, 1.0f, userId);
5199
5200 synchronized (this) {
5201 if (getGlobalConfiguration().fontScale == scaleFactor) {
5202 return;
5203 }
5204
5205 final Configuration configuration
5206 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5207 configuration.fontScale = scaleFactor;
5208 updatePersistentConfiguration(configuration, userId);
5209 }
5210 }
5211
5212 // Actually is sleeping or shutting down or whatever else in the future
5213 // is an inactive state.
5214 boolean isSleepingOrShuttingDownLocked() {
5215 return isSleepingLocked() || mShuttingDown;
5216 }
5217
5218 boolean isSleepingLocked() {
5219 return mSleeping;
5220 }
5221
Riddle Hsu16567132018-08-16 21:37:47 +08005222 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005223 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005224 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005225 if (task.isActivityTypeStandard()) {
5226 if (mCurAppTimeTracker != r.appTimeTracker) {
5227 // We are switching app tracking. Complete the current one.
5228 if (mCurAppTimeTracker != null) {
5229 mCurAppTimeTracker.stop();
5230 mH.obtainMessage(
5231 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005232 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005233 mCurAppTimeTracker = null;
5234 }
5235 if (r.appTimeTracker != null) {
5236 mCurAppTimeTracker = r.appTimeTracker;
5237 startTimeTrackingFocusedActivityLocked();
5238 }
5239 } else {
5240 startTimeTrackingFocusedActivityLocked();
5241 }
5242 } else {
5243 r.appTimeTracker = null;
5244 }
5245 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5246 // TODO: Probably not, because we don't want to resume voice on switching
5247 // back to this activity
5248 if (task.voiceInteractor != null) {
5249 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5250 } else {
5251 finishRunningVoiceLocked();
5252
5253 if (mLastResumedActivity != null) {
5254 final IVoiceInteractionSession session;
5255
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005256 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 if (lastResumedActivityTask != null
5258 && lastResumedActivityTask.voiceSession != null) {
5259 session = lastResumedActivityTask.voiceSession;
5260 } else {
5261 session = mLastResumedActivity.voiceSession;
5262 }
5263
5264 if (session != null) {
5265 // We had been in a voice interaction session, but now focused has
5266 // move to something different. Just finish the session, we can't
5267 // return to it and retain the proper state and synchronization with
5268 // the voice interaction service.
5269 finishVoiceTask(session);
5270 }
5271 }
5272 }
5273
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005274 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5275 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005276 }
5277 updateResumedAppTrace(r);
5278 mLastResumedActivity = r;
5279
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005280 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005281
5282 applyUpdateLockStateLocked(r);
5283 applyUpdateVrModeLocked(r);
5284
5285 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005286 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005287 r == null ? "NULL" : r.shortComponentName,
5288 reason);
5289 }
5290
5291 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5292 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005293 final ActivityTaskManagerInternal.SleepToken token =
5294 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005295 updateSleepIfNeededLocked();
5296 return token;
5297 }
5298 }
5299
5300 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005301 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005302 final boolean wasSleeping = mSleeping;
5303 boolean updateOomAdj = false;
5304
5305 if (!shouldSleep) {
5306 // If wasSleeping is true, we need to wake up activity manager state from when
5307 // we started sleeping. In either case, we need to apply the sleep tokens, which
5308 // will wake up stacks or put them to sleep as appropriate.
5309 if (wasSleeping) {
5310 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005311 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5312 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005313 startTimeTrackingFocusedActivityLocked();
5314 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5315 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5316 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005317 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005318 if (wasSleeping) {
5319 updateOomAdj = true;
5320 }
5321 } else if (!mSleeping && shouldSleep) {
5322 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005323 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5324 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005325 if (mCurAppTimeTracker != null) {
5326 mCurAppTimeTracker.stop();
5327 }
5328 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5329 mStackSupervisor.goingToSleepLocked();
5330 updateResumedAppTrace(null /* resumed */);
5331 updateOomAdj = true;
5332 }
5333 if (updateOomAdj) {
5334 mH.post(mAmInternal::updateOomAdj);
5335 }
5336 }
5337
5338 void updateOomAdj() {
5339 mH.post(mAmInternal::updateOomAdj);
5340 }
5341
Wale Ogunwale53783742018-09-16 10:21:51 -07005342 void updateCpuStats() {
5343 mH.post(mAmInternal::updateCpuStats);
5344 }
5345
Hui Yu03d12402018-12-06 18:00:37 -08005346 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5347 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005348 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5349 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005350 mH.sendMessage(m);
5351 }
5352
Hui Yu03d12402018-12-06 18:00:37 -08005353 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005354 ComponentName taskRoot = null;
5355 final TaskRecord task = activity.getTaskRecord();
5356 if (task != null) {
5357 final ActivityRecord rootActivity = task.getRootActivity();
5358 if (rootActivity != null) {
5359 taskRoot = rootActivity.mActivityComponent;
5360 }
5361 }
5362
Hui Yu03d12402018-12-06 18:00:37 -08005363 final Message m = PooledLambda.obtainMessage(
5364 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005365 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005366 mH.sendMessage(m);
5367 }
5368
Wale Ogunwale53783742018-09-16 10:21:51 -07005369 void setBooting(boolean booting) {
5370 mAmInternal.setBooting(booting);
5371 }
5372
5373 boolean isBooting() {
5374 return mAmInternal.isBooting();
5375 }
5376
5377 void setBooted(boolean booted) {
5378 mAmInternal.setBooted(booted);
5379 }
5380
5381 boolean isBooted() {
5382 return mAmInternal.isBooted();
5383 }
5384
5385 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5386 mH.post(() -> {
5387 if (finishBooting) {
5388 mAmInternal.finishBooting();
5389 }
5390 if (enableScreen) {
5391 mInternal.enableScreenAfterBoot(isBooted());
5392 }
5393 });
5394 }
5395
5396 void setHeavyWeightProcess(ActivityRecord root) {
5397 mHeavyWeightProcess = root.app;
5398 final Message m = PooledLambda.obtainMessage(
5399 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005400 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005401 mH.sendMessage(m);
5402 }
5403
5404 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5405 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5406 return;
5407 }
5408
5409 mHeavyWeightProcess = null;
5410 final Message m = PooledLambda.obtainMessage(
5411 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5412 proc.mUserId);
5413 mH.sendMessage(m);
5414 }
5415
5416 private void cancelHeavyWeightProcessNotification(int userId) {
5417 final INotificationManager inm = NotificationManager.getService();
5418 if (inm == null) {
5419 return;
5420 }
5421 try {
5422 inm.cancelNotificationWithTag("android", null,
5423 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5424 } catch (RuntimeException e) {
5425 Slog.w(TAG, "Error canceling notification for service", e);
5426 } catch (RemoteException e) {
5427 }
5428
5429 }
5430
5431 private void postHeavyWeightProcessNotification(
5432 WindowProcessController proc, Intent intent, int userId) {
5433 if (proc == null) {
5434 return;
5435 }
5436
5437 final INotificationManager inm = NotificationManager.getService();
5438 if (inm == null) {
5439 return;
5440 }
5441
5442 try {
5443 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5444 String text = mContext.getString(R.string.heavy_weight_notification,
5445 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5446 Notification notification =
5447 new Notification.Builder(context,
5448 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5449 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5450 .setWhen(0)
5451 .setOngoing(true)
5452 .setTicker(text)
5453 .setColor(mContext.getColor(
5454 com.android.internal.R.color.system_notification_accent_color))
5455 .setContentTitle(text)
5456 .setContentText(
5457 mContext.getText(R.string.heavy_weight_notification_detail))
5458 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5459 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5460 new UserHandle(userId)))
5461 .build();
5462 try {
5463 inm.enqueueNotificationWithTag("android", "android", null,
5464 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5465 } catch (RuntimeException e) {
5466 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5467 } catch (RemoteException e) {
5468 }
5469 } catch (PackageManager.NameNotFoundException e) {
5470 Slog.w(TAG, "Unable to create context for heavy notification", e);
5471 }
5472
5473 }
5474
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005475 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5476 IBinder token, String resultWho, int requestCode, Intent[] intents,
5477 String[] resolvedTypes, int flags, Bundle bOptions) {
5478
5479 ActivityRecord activity = null;
5480 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5481 activity = ActivityRecord.isInStackLocked(token);
5482 if (activity == null) {
5483 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5484 return null;
5485 }
5486 if (activity.finishing) {
5487 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5488 return null;
5489 }
5490 }
5491
5492 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5493 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5494 bOptions);
5495 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5496 if (noCreate) {
5497 return rec;
5498 }
5499 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5500 if (activity.pendingResults == null) {
5501 activity.pendingResults = new HashSet<>();
5502 }
5503 activity.pendingResults.add(rec.ref);
5504 }
5505 return rec;
5506 }
5507
Andrii Kulian52d255c2018-07-13 11:32:19 -07005508 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005510 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5512 mCurAppTimeTracker.start(resumedActivity.packageName);
5513 }
5514 }
5515
5516 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5517 if (mTracedResumedActivity != null) {
5518 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5519 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5520 }
5521 if (resumed != null) {
5522 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5523 constructResumedTraceName(resumed.packageName), 0);
5524 }
5525 mTracedResumedActivity = resumed;
5526 }
5527
5528 private String constructResumedTraceName(String packageName) {
5529 return "focused app: " + packageName;
5530 }
5531
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005532 /** Applies latest configuration and/or visibility updates if needed. */
5533 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5534 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005535 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005536 // mainStack is null during startup.
5537 if (mainStack != null) {
5538 if (changes != 0 && starting == null) {
5539 // If the configuration changed, and the caller is not already
5540 // in the process of starting an activity, then find the top
5541 // activity to check if its configuration needs to change.
5542 starting = mainStack.topRunningActivityLocked();
5543 }
5544
5545 if (starting != null) {
5546 kept = starting.ensureActivityConfiguration(changes,
5547 false /* preserveWindow */);
5548 // And we need to make sure at this point that all other activities
5549 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005550 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005551 !PRESERVE_WINDOWS);
5552 }
5553 }
5554
5555 return kept;
5556 }
5557
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005558 void scheduleAppGcsLocked() {
5559 mH.post(() -> mAmInternal.scheduleAppGcs());
5560 }
5561
Wale Ogunwale53783742018-09-16 10:21:51 -07005562 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5563 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5564 }
5565
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005566 /**
5567 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5568 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5569 * on demand.
5570 */
5571 IPackageManager getPackageManager() {
5572 return AppGlobals.getPackageManager();
5573 }
5574
5575 PackageManagerInternal getPackageManagerInternalLocked() {
5576 if (mPmInternal == null) {
5577 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5578 }
5579 return mPmInternal;
5580 }
5581
Wale Ogunwale008163e2018-07-23 23:11:08 -07005582 AppWarnings getAppWarningsLocked() {
5583 return mAppWarnings;
5584 }
5585
Wale Ogunwale214f3482018-10-04 11:00:47 -07005586 Intent getHomeIntent() {
5587 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5588 intent.setComponent(mTopComponent);
5589 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5590 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5591 intent.addCategory(Intent.CATEGORY_HOME);
5592 }
5593 return intent;
5594 }
5595
Chilun2ef71f72018-11-16 17:57:15 +08005596 /**
5597 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5598 * activities.
5599 *
5600 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5601 * component defined in config_secondaryHomeComponent.
5602 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5603 */
5604 Intent getSecondaryHomeIntent(String preferredPackage) {
5605 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5606 if (preferredPackage == null) {
5607 // Using the component stored in config if no package name.
5608 final String secondaryHomeComponent = mContext.getResources().getString(
5609 com.android.internal.R.string.config_secondaryHomeComponent);
5610 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5611 } else {
5612 intent.setPackage(preferredPackage);
5613 }
5614 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5615 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5616 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5617 }
5618 return intent;
5619 }
5620
Wale Ogunwale214f3482018-10-04 11:00:47 -07005621 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5622 if (info == null) return null;
5623 ApplicationInfo newInfo = new ApplicationInfo(info);
5624 newInfo.initForUser(userId);
5625 return newInfo;
5626 }
5627
Wale Ogunwale9c103022018-10-18 07:44:54 -07005628 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005629 if (uid == SYSTEM_UID) {
5630 // The system gets to run in any process. If there are multiple processes with the same
5631 // uid, just pick the first (this should never happen).
5632 final SparseArray<WindowProcessController> procs =
5633 mProcessNames.getMap().get(processName);
5634 if (procs == null) return null;
5635 final int procCount = procs.size();
5636 for (int i = 0; i < procCount; i++) {
5637 final int procUid = procs.keyAt(i);
5638 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5639 // Don't use an app process or different user process for system component.
5640 continue;
5641 }
5642 return procs.valueAt(i);
5643 }
5644 }
5645
5646 return mProcessNames.get(processName, uid);
5647 }
5648
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005649 WindowProcessController getProcessController(IApplicationThread thread) {
5650 if (thread == null) {
5651 return null;
5652 }
5653
5654 final IBinder threadBinder = thread.asBinder();
5655 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5656 for (int i = pmap.size()-1; i >= 0; i--) {
5657 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5658 for (int j = procs.size() - 1; j >= 0; j--) {
5659 final WindowProcessController proc = procs.valueAt(j);
5660 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5661 return proc;
5662 }
5663 }
5664 }
5665
5666 return null;
5667 }
5668
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005669 WindowProcessController getProcessController(int pid, int uid) {
5670 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5671 for (int i = pmap.size()-1; i >= 0; i--) {
5672 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5673 for (int j = procs.size() - 1; j >= 0; j--) {
5674 final WindowProcessController proc = procs.valueAt(j);
5675 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5676 return proc;
5677 }
5678 }
5679 }
5680 return null;
5681 }
5682
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005683 int getUidStateLocked(int uid) {
5684 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5685 }
5686
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005687 boolean isUidForeground(int uid) {
5688 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5689 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5690 }
5691
Wale Ogunwale9de19442018-10-18 19:05:03 -07005692 /**
5693 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5694 * the whitelist
5695 */
5696 String getPendingTempWhitelistTagForUidLocked(int uid) {
5697 return mPendingTempWhitelist.get(uid);
5698 }
5699
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005700 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5701 if (true || Build.IS_USER) {
5702 return;
5703 }
5704
5705 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5706 StrictMode.allowThreadDiskWrites();
5707 try {
5708 File tracesDir = new File("/data/anr");
5709 File tracesFile = null;
5710 try {
5711 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5712
5713 StringBuilder sb = new StringBuilder();
5714 Time tobj = new Time();
5715 tobj.set(System.currentTimeMillis());
5716 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5717 sb.append(": ");
5718 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5719 sb.append(" since ");
5720 sb.append(msg);
5721 FileOutputStream fos = new FileOutputStream(tracesFile);
5722 fos.write(sb.toString().getBytes());
5723 if (app == null) {
5724 fos.write("\n*** No application process!".getBytes());
5725 }
5726 fos.close();
5727 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5728 } catch (IOException e) {
5729 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5730 return;
5731 }
5732
5733 if (app != null && app.getPid() > 0) {
5734 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5735 firstPids.add(app.getPid());
5736 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5737 }
5738
5739 File lastTracesFile = null;
5740 File curTracesFile = null;
5741 for (int i=9; i>=0; i--) {
5742 String name = String.format(Locale.US, "slow%02d.txt", i);
5743 curTracesFile = new File(tracesDir, name);
5744 if (curTracesFile.exists()) {
5745 if (lastTracesFile != null) {
5746 curTracesFile.renameTo(lastTracesFile);
5747 } else {
5748 curTracesFile.delete();
5749 }
5750 }
5751 lastTracesFile = curTracesFile;
5752 }
5753 tracesFile.renameTo(curTracesFile);
5754 } finally {
5755 StrictMode.setThreadPolicy(oldPolicy);
5756 }
5757 }
5758
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005759 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005760 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005761
5762
Wale Ogunwale98875612018-10-12 07:53:02 -07005763 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5764 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005765
Riddle Hsud93a6c42018-11-29 21:50:06 +08005766 H(Looper looper) {
5767 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005768 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005769
5770 @Override
5771 public void handleMessage(Message msg) {
5772 switch (msg.what) {
5773 case REPORT_TIME_TRACKER_MSG: {
5774 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5775 tracker.deliverResult(mContext);
5776 } break;
5777 }
5778 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005779 }
5780
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005781 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005782 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005783
5784 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005785 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005786 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005787
5788 @Override
5789 public void handleMessage(Message msg) {
5790 switch (msg.what) {
5791 case DISMISS_DIALOG_UI_MSG: {
5792 final Dialog d = (Dialog) msg.obj;
5793 d.dismiss();
5794 break;
5795 }
5796 }
5797 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005798 }
5799
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005800 final class LocalService extends ActivityTaskManagerInternal {
5801 @Override
5802 public SleepToken acquireSleepToken(String tag, int displayId) {
5803 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005804 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005805 }
5806
5807 @Override
5808 public ComponentName getHomeActivityForUser(int userId) {
5809 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005810 final ActivityRecord homeActivity =
5811 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005812 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005813 }
5814 }
5815
5816 @Override
5817 public void onLocalVoiceInteractionStarted(IBinder activity,
5818 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5819 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005820 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005821 }
5822 }
5823
5824 @Override
5825 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5826 synchronized (mGlobalLock) {
5827 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5828 reasons, timestamp);
5829 }
5830 }
5831
5832 @Override
5833 public void notifyAppTransitionFinished() {
5834 synchronized (mGlobalLock) {
5835 mStackSupervisor.notifyAppTransitionDone();
5836 }
5837 }
5838
5839 @Override
5840 public void notifyAppTransitionCancelled() {
5841 synchronized (mGlobalLock) {
5842 mStackSupervisor.notifyAppTransitionDone();
5843 }
5844 }
5845
5846 @Override
5847 public List<IBinder> getTopVisibleActivities() {
5848 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005849 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005850 }
5851 }
5852
5853 @Override
5854 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5855 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005856 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005857 }
5858 }
5859
5860 @Override
5861 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5862 Bundle bOptions) {
5863 Preconditions.checkNotNull(intents, "intents");
5864 final String[] resolvedTypes = new String[intents.length];
5865
5866 // UID of the package on user userId.
5867 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5868 // packageUid may not be initialized.
5869 int packageUid = 0;
5870 final long ident = Binder.clearCallingIdentity();
5871
5872 try {
5873 for (int i = 0; i < intents.length; i++) {
5874 resolvedTypes[i] =
5875 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5876 }
5877
5878 packageUid = AppGlobals.getPackageManager().getPackageUid(
5879 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5880 } catch (RemoteException e) {
5881 // Shouldn't happen.
5882 } finally {
5883 Binder.restoreCallingIdentity(ident);
5884 }
5885
5886 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005887 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005888 packageUid, packageName,
5889 intents, resolvedTypes, null /* resultTo */,
5890 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005891 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5892 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005893 }
5894 }
5895
5896 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005897 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5898 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5899 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5900 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005901 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005902 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005903 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5904 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5905 userId, validateIncomingUser, originatingPendingIntent,
5906 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005907 }
5908 }
5909
5910 @Override
5911 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5912 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5913 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5914 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005915 PendingIntentRecord originatingPendingIntent,
5916 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005917 synchronized (mGlobalLock) {
5918 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5919 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5920 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005921 validateIncomingUser, originatingPendingIntent,
5922 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005923 }
5924 }
5925
5926 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005927 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5928 Intent intent, Bundle options, int userId) {
5929 return ActivityTaskManagerService.this.startActivityAsUser(
5930 caller, callerPacakge, intent,
5931 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5932 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5933 false /*validateIncomingUser*/);
5934 }
5935
5936 @Override
lumark588a3e82018-07-20 18:53:54 +08005937 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005938 synchronized (mGlobalLock) {
5939
5940 // We might change the visibilities here, so prepare an empty app transition which
5941 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005942 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005943 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005944 if (activityDisplay == null) {
5945 return;
5946 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005947 final DisplayContent dc = activityDisplay.mDisplayContent;
5948 final boolean wasTransitionSet =
5949 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005950 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005951 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005952 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005953 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005954
5955 // If there was a transition set already we don't want to interfere with it as we
5956 // might be starting it too early.
5957 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005958 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005959 }
5960 }
5961 if (callback != null) {
5962 callback.run();
5963 }
5964 }
5965
5966 @Override
5967 public void notifyKeyguardTrustedChanged() {
5968 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005969 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005970 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005971 }
5972 }
5973 }
5974
5975 /**
5976 * Called after virtual display Id is updated by
5977 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5978 * {@param vrVr2dDisplayId}.
5979 */
5980 @Override
5981 public void setVr2dDisplayId(int vr2dDisplayId) {
5982 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5983 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005984 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005985 }
5986 }
5987
5988 @Override
5989 public void setFocusedActivity(IBinder token) {
5990 synchronized (mGlobalLock) {
5991 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5992 if (r == null) {
5993 throw new IllegalArgumentException(
5994 "setFocusedActivity: No activity record matching token=" + token);
5995 }
Louis Chang19443452018-10-09 12:10:21 +08005996 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005997 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005998 }
5999 }
6000 }
6001
6002 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006004 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006005 }
6006
6007 @Override
6008 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006009 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006010 }
6011
6012 @Override
6013 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006014 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006015 }
6016
6017 @Override
6018 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6019 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6020 }
6021
6022 @Override
6023 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006024 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006025 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006026
6027 @Override
6028 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6029 synchronized (mGlobalLock) {
6030 mActiveVoiceInteractionServiceComponent = component;
6031 }
6032 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006033
6034 @Override
6035 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6036 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6037 return;
6038 }
6039 synchronized (mGlobalLock) {
6040 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6041 if (types == null) {
6042 if (uid < 0) {
6043 return;
6044 }
6045 types = new ArrayMap<>();
6046 mAllowAppSwitchUids.put(userId, types);
6047 }
6048 if (uid < 0) {
6049 types.remove(type);
6050 } else {
6051 types.put(type, uid);
6052 }
6053 }
6054 }
6055
6056 @Override
6057 public void onUserStopped(int userId) {
6058 synchronized (mGlobalLock) {
6059 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6060 mAllowAppSwitchUids.remove(userId);
6061 }
6062 }
6063
6064 @Override
6065 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6066 synchronized (mGlobalLock) {
6067 return ActivityTaskManagerService.this.isGetTasksAllowed(
6068 caller, callingPid, callingUid);
6069 }
6070 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006071
6072 @Override
6073 public void onProcessAdded(WindowProcessController proc) {
6074 synchronized (mGlobalLock) {
6075 mProcessNames.put(proc.mName, proc.mUid, proc);
6076 }
6077 }
6078
6079 @Override
6080 public void onProcessRemoved(String name, int uid) {
6081 synchronized (mGlobalLock) {
6082 mProcessNames.remove(name, uid);
6083 }
6084 }
6085
6086 @Override
6087 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6088 synchronized (mGlobalLock) {
6089 if (proc == mHomeProcess) {
6090 mHomeProcess = null;
6091 }
6092 if (proc == mPreviousProcess) {
6093 mPreviousProcess = null;
6094 }
6095 }
6096 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006097
6098 @Override
6099 public int getTopProcessState() {
6100 synchronized (mGlobalLock) {
6101 return mTopProcessState;
6102 }
6103 }
6104
6105 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006106 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6107 synchronized (mGlobalLock) {
6108 return proc == mHeavyWeightProcess;
6109 }
6110 }
6111
6112 @Override
6113 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6114 synchronized (mGlobalLock) {
6115 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6116 }
6117 }
6118
6119 @Override
6120 public void finishHeavyWeightApp() {
6121 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006122 if (mHeavyWeightProcess != null) {
6123 mHeavyWeightProcess.finishActivities();
6124 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006125 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6126 mHeavyWeightProcess);
6127 }
6128 }
6129
6130 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006131 public boolean isSleeping() {
6132 synchronized (mGlobalLock) {
6133 return isSleepingLocked();
6134 }
6135 }
6136
6137 @Override
6138 public boolean isShuttingDown() {
6139 synchronized (mGlobalLock) {
6140 return mShuttingDown;
6141 }
6142 }
6143
6144 @Override
6145 public boolean shuttingDown(boolean booted, int timeout) {
6146 synchronized (mGlobalLock) {
6147 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006148 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006149 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006150 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006151 return mStackSupervisor.shutdownLocked(timeout);
6152 }
6153 }
6154
6155 @Override
6156 public void enableScreenAfterBoot(boolean booted) {
6157 synchronized (mGlobalLock) {
6158 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6159 SystemClock.uptimeMillis());
6160 mWindowManager.enableScreenAfterBoot();
6161 updateEventDispatchingLocked(booted);
6162 }
6163 }
6164
6165 @Override
6166 public boolean showStrictModeViolationDialog() {
6167 synchronized (mGlobalLock) {
6168 return mShowDialogs && !mSleeping && !mShuttingDown;
6169 }
6170 }
6171
6172 @Override
6173 public void showSystemReadyErrorDialogsIfNeeded() {
6174 synchronized (mGlobalLock) {
6175 try {
6176 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6177 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6178 + " data partition or your device will be unstable.");
6179 mUiHandler.post(() -> {
6180 if (mShowDialogs) {
6181 AlertDialog d = new BaseErrorDialog(mUiContext);
6182 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6183 d.setCancelable(false);
6184 d.setTitle(mUiContext.getText(R.string.android_system_label));
6185 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6186 d.setButton(DialogInterface.BUTTON_POSITIVE,
6187 mUiContext.getText(R.string.ok),
6188 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6189 d.show();
6190 }
6191 });
6192 }
6193 } catch (RemoteException e) {
6194 }
6195
6196 if (!Build.isBuildConsistent()) {
6197 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6198 mUiHandler.post(() -> {
6199 if (mShowDialogs) {
6200 AlertDialog d = new BaseErrorDialog(mUiContext);
6201 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6202 d.setCancelable(false);
6203 d.setTitle(mUiContext.getText(R.string.android_system_label));
6204 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6205 d.setButton(DialogInterface.BUTTON_POSITIVE,
6206 mUiContext.getText(R.string.ok),
6207 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6208 d.show();
6209 }
6210 });
6211 }
6212 }
6213 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006214
6215 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006216 public void onProcessMapped(int pid, WindowProcessController proc) {
6217 synchronized (mGlobalLock) {
6218 mPidMap.put(pid, proc);
6219 }
6220 }
6221
6222 @Override
6223 public void onProcessUnMapped(int pid) {
6224 synchronized (mGlobalLock) {
6225 mPidMap.remove(pid);
6226 }
6227 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006228
6229 @Override
6230 public void onPackageDataCleared(String name) {
6231 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006232 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006233 mAppWarnings.onPackageDataCleared(name);
6234 }
6235 }
6236
6237 @Override
6238 public void onPackageUninstalled(String name) {
6239 synchronized (mGlobalLock) {
6240 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006241 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006242 }
6243 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006244
6245 @Override
6246 public void onPackageAdded(String name, boolean replacing) {
6247 synchronized (mGlobalLock) {
6248 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6249 }
6250 }
6251
6252 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006253 public void onPackageReplaced(ApplicationInfo aInfo) {
6254 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006255 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006256 }
6257 }
6258
6259 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006260 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6261 synchronized (mGlobalLock) {
6262 return compatibilityInfoForPackageLocked(ai);
6263 }
6264 }
6265
Yunfan Chen75157d72018-07-27 14:47:21 +09006266 /**
6267 * Set the corresponding display information for the process global configuration. To be
6268 * called when we need to show IME on a different display.
6269 *
6270 * @param pid The process id associated with the IME window.
6271 * @param displayId The ID of the display showing the IME.
6272 */
6273 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006274 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006275 if (pid == MY_PID || pid < 0) {
6276 if (DEBUG_CONFIGURATION) {
6277 Slog.w(TAG,
6278 "Trying to update display configuration for system/invalid process.");
6279 }
6280 return;
6281 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006282 synchronized (mGlobalLock) {
6283 final ActivityDisplay activityDisplay =
6284 mRootActivityContainer.getActivityDisplay(displayId);
6285 if (activityDisplay == null) {
6286 // Call might come when display is not yet added or has been removed.
6287 if (DEBUG_CONFIGURATION) {
6288 Slog.w(TAG, "Trying to update display configuration for non-existing "
6289 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006290 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006291 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006292 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006293 final WindowProcessController process = mPidMap.get(pid);
6294 if (process == null) {
6295 if (DEBUG_CONFIGURATION) {
6296 Slog.w(TAG, "Trying to update display configuration for invalid "
6297 + "process, pid=" + pid);
6298 }
6299 return;
6300 }
6301 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6302 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006303 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006304
6305 @Override
6306 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6307 int requestCode, int resultCode, Intent data) {
6308 synchronized (mGlobalLock) {
6309 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006310 if (r != null && r.getActivityStack() != null) {
6311 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6312 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006313 }
6314 }
6315 }
6316
6317 @Override
6318 public void clearPendingResultForActivity(IBinder activityToken,
6319 WeakReference<PendingIntentRecord> pir) {
6320 synchronized (mGlobalLock) {
6321 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6322 if (r != null && r.pendingResults != null) {
6323 r.pendingResults.remove(pir);
6324 }
6325 }
6326 }
6327
6328 @Override
6329 public IIntentSender getIntentSender(int type, String packageName,
6330 int callingUid, int userId, IBinder token, String resultWho,
6331 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6332 Bundle bOptions) {
6333 synchronized (mGlobalLock) {
6334 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6335 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6336 }
6337 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006338
6339 @Override
6340 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6341 synchronized (mGlobalLock) {
6342 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6343 if (r == null) {
6344 return null;
6345 }
6346 if (r.mServiceConnectionsHolder == null) {
6347 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6348 ActivityTaskManagerService.this, r);
6349 }
6350
6351 return r.mServiceConnectionsHolder;
6352 }
6353 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006354
6355 @Override
6356 public Intent getHomeIntent() {
6357 synchronized (mGlobalLock) {
6358 return ActivityTaskManagerService.this.getHomeIntent();
6359 }
6360 }
6361
6362 @Override
6363 public boolean startHomeActivity(int userId, String reason) {
6364 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006365 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006366 }
6367 }
6368
6369 @Override
6370 public boolean startHomeOnAllDisplays(int userId, String reason) {
6371 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006372 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006373 }
6374 }
6375
6376 @Override
6377 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6378 synchronized (mGlobalLock) {
6379 if (mFactoryTest == FACTORY_TEST_OFF) {
6380 return false;
6381 }
6382 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6383 && wpc.mName.equals(mTopComponent.getPackageName())) {
6384 return true;
6385 }
6386 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6387 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6388 }
6389 }
6390
6391 @Override
6392 public void updateTopComponentForFactoryTest() {
6393 synchronized (mGlobalLock) {
6394 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6395 return;
6396 }
6397 final ResolveInfo ri = mContext.getPackageManager()
6398 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6399 final CharSequence errorMsg;
6400 if (ri != null) {
6401 final ActivityInfo ai = ri.activityInfo;
6402 final ApplicationInfo app = ai.applicationInfo;
6403 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6404 mTopAction = Intent.ACTION_FACTORY_TEST;
6405 mTopData = null;
6406 mTopComponent = new ComponentName(app.packageName, ai.name);
6407 errorMsg = null;
6408 } else {
6409 errorMsg = mContext.getResources().getText(
6410 com.android.internal.R.string.factorytest_not_system);
6411 }
6412 } else {
6413 errorMsg = mContext.getResources().getText(
6414 com.android.internal.R.string.factorytest_no_action);
6415 }
6416 if (errorMsg == null) {
6417 return;
6418 }
6419
6420 mTopAction = null;
6421 mTopData = null;
6422 mTopComponent = null;
6423 mUiHandler.post(() -> {
6424 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6425 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006426 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006427 });
6428 }
6429 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006430
6431 @Override
6432 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6433 Runnable finishInstrumentationCallback) {
6434 synchronized (mGlobalLock) {
6435 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006436 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006437
6438 wpc.clearRecentTasks();
6439 wpc.clearActivities();
6440
6441 if (wpc.isInstrumenting()) {
6442 finishInstrumentationCallback.run();
6443 }
6444
Jorim Jaggid0752812018-10-16 16:07:20 +02006445 if (!restarting && hasVisibleActivities) {
6446 mWindowManager.deferSurfaceLayout();
6447 try {
6448 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6449 // If there was nothing to resume, and we are not already restarting
6450 // this process, but there is a visible activity that is hosted by the
6451 // process...then make sure all visible activities are running, taking
6452 // care of restarting this process.
6453 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6454 !PRESERVE_WINDOWS);
6455 }
6456 } finally {
6457 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006458 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006459 }
6460 }
6461 }
6462
6463 @Override
6464 public void closeSystemDialogs(String reason) {
6465 enforceNotIsolatedCaller("closeSystemDialogs");
6466
6467 final int pid = Binder.getCallingPid();
6468 final int uid = Binder.getCallingUid();
6469 final long origId = Binder.clearCallingIdentity();
6470 try {
6471 synchronized (mGlobalLock) {
6472 // Only allow this from foreground processes, so that background
6473 // applications can't abuse it to prevent system UI from being shown.
6474 if (uid >= FIRST_APPLICATION_UID) {
6475 final WindowProcessController proc = mPidMap.get(pid);
6476 if (!proc.isPerceptible()) {
6477 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6478 + " from background process " + proc);
6479 return;
6480 }
6481 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006482 mWindowManager.closeSystemDialogs(reason);
6483
Wale Ogunwaled32da472018-11-16 07:19:28 -08006484 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006485 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006486 // Call into AM outside the synchronized block.
6487 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006488 } finally {
6489 Binder.restoreCallingIdentity(origId);
6490 }
6491 }
6492
6493 @Override
6494 public void cleanupDisabledPackageComponents(
6495 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6496 synchronized (mGlobalLock) {
6497 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006498 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006499 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006500 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006501 mStackSupervisor.scheduleIdleLocked();
6502 }
6503
6504 // Clean-up disabled tasks
6505 getRecentTasks().cleanupDisabledPackageTasksLocked(
6506 packageName, disabledClasses, userId);
6507 }
6508 }
6509
6510 @Override
6511 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6512 int userId) {
6513 synchronized (mGlobalLock) {
6514
6515 boolean didSomething =
6516 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006517 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006518 null, doit, evenPersistent, userId);
6519 return didSomething;
6520 }
6521 }
6522
6523 @Override
6524 public void resumeTopActivities(boolean scheduleIdle) {
6525 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006526 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006527 if (scheduleIdle) {
6528 mStackSupervisor.scheduleIdleLocked();
6529 }
6530 }
6531 }
6532
6533 @Override
6534 public void preBindApplication(WindowProcessController wpc) {
6535 synchronized (mGlobalLock) {
6536 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6537 }
6538 }
6539
6540 @Override
6541 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6542 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006543 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006544 }
6545 }
6546
6547 @Override
6548 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6549 try {
6550 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6551 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6552 }
6553 } catch (RemoteException ex) {
6554 throw new SecurityException("Fail to check is caller a privileged app", ex);
6555 }
6556
6557 synchronized (mGlobalLock) {
6558 final long ident = Binder.clearCallingIdentity();
6559 try {
6560 if (mAmInternal.shouldConfirmCredentials(userId)) {
6561 if (mKeyguardController.isKeyguardLocked()) {
6562 // Showing launcher to avoid user entering credential twice.
6563 startHomeActivity(currentUserId, "notifyLockedProfile");
6564 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006565 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006566 }
6567 } finally {
6568 Binder.restoreCallingIdentity(ident);
6569 }
6570 }
6571 }
6572
6573 @Override
6574 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6575 mAmInternal.enforceCallingPermission(
6576 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6577
6578 synchronized (mGlobalLock) {
6579 final long ident = Binder.clearCallingIdentity();
6580 try {
6581 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6582 FLAG_ACTIVITY_TASK_ON_HOME);
6583 ActivityOptions activityOptions = options != null
6584 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006585 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006586 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006587 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006588 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006589 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006590 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6591 UserHandle.CURRENT);
6592 } finally {
6593 Binder.restoreCallingIdentity(ident);
6594 }
6595 }
6596 }
6597
6598 @Override
6599 public void writeActivitiesToProto(ProtoOutputStream proto) {
6600 synchronized (mGlobalLock) {
6601 // The output proto of "activity --proto activities"
6602 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006603 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006604 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6605 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006606 }
6607 }
6608
6609 @Override
6610 public void saveANRState(String reason) {
6611 synchronized (mGlobalLock) {
6612 final StringWriter sw = new StringWriter();
6613 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6614 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6615 if (reason != null) {
6616 pw.println(" Reason: " + reason);
6617 }
6618 pw.println();
6619 getActivityStartController().dump(pw, " ", null);
6620 pw.println();
6621 pw.println("-------------------------------------------------------------------------------");
6622 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6623 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6624 "" /* header */);
6625 pw.println();
6626 pw.close();
6627
6628 mLastANRState = sw.toString();
6629 }
6630 }
6631
6632 @Override
6633 public void clearSavedANRState() {
6634 synchronized (mGlobalLock) {
6635 mLastANRState = null;
6636 }
6637 }
6638
6639 @Override
6640 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6641 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6642 synchronized (mGlobalLock) {
6643 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6644 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6645 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6646 dumpLastANRLocked(pw);
6647 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6648 dumpLastANRTracesLocked(pw);
6649 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6650 dumpActivityStarterLocked(pw, dumpPackage);
6651 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6652 dumpActivityContainersLocked(pw);
6653 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6654 if (getRecentTasks() != null) {
6655 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6656 }
6657 }
6658 }
6659 }
6660
6661 @Override
6662 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6663 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6664 int wakefulness) {
6665 synchronized (mGlobalLock) {
6666 if (mHomeProcess != null && (dumpPackage == null
6667 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6668 if (needSep) {
6669 pw.println();
6670 needSep = false;
6671 }
6672 pw.println(" mHomeProcess: " + mHomeProcess);
6673 }
6674 if (mPreviousProcess != null && (dumpPackage == null
6675 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6676 if (needSep) {
6677 pw.println();
6678 needSep = false;
6679 }
6680 pw.println(" mPreviousProcess: " + mPreviousProcess);
6681 }
6682 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6683 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6684 StringBuilder sb = new StringBuilder(128);
6685 sb.append(" mPreviousProcessVisibleTime: ");
6686 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6687 pw.println(sb);
6688 }
6689 if (mHeavyWeightProcess != null && (dumpPackage == null
6690 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6691 if (needSep) {
6692 pw.println();
6693 needSep = false;
6694 }
6695 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6696 }
6697 if (dumpPackage == null) {
6698 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006699 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006700 }
6701 if (dumpAll) {
6702 if (dumpPackage == null) {
6703 pw.println(" mConfigWillChange: "
6704 + getTopDisplayFocusedStack().mConfigWillChange);
6705 }
6706 if (mCompatModePackages.getPackages().size() > 0) {
6707 boolean printed = false;
6708 for (Map.Entry<String, Integer> entry
6709 : mCompatModePackages.getPackages().entrySet()) {
6710 String pkg = entry.getKey();
6711 int mode = entry.getValue();
6712 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6713 continue;
6714 }
6715 if (!printed) {
6716 pw.println(" mScreenCompatPackages:");
6717 printed = true;
6718 }
6719 pw.println(" " + pkg + ": " + mode);
6720 }
6721 }
6722 }
6723
6724 if (dumpPackage == null) {
6725 pw.println(" mWakefulness="
6726 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006727 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006728 if (mRunningVoice != null) {
6729 pw.println(" mRunningVoice=" + mRunningVoice);
6730 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6731 }
6732 pw.println(" mSleeping=" + mSleeping);
6733 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6734 pw.println(" mVrController=" + mVrController);
6735 }
6736 if (mCurAppTimeTracker != null) {
6737 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6738 }
6739 if (mAllowAppSwitchUids.size() > 0) {
6740 boolean printed = false;
6741 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6742 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6743 for (int j = 0; j < types.size(); j++) {
6744 if (dumpPackage == null ||
6745 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6746 if (needSep) {
6747 pw.println();
6748 needSep = false;
6749 }
6750 if (!printed) {
6751 pw.println(" mAllowAppSwitchUids:");
6752 printed = true;
6753 }
6754 pw.print(" User ");
6755 pw.print(mAllowAppSwitchUids.keyAt(i));
6756 pw.print(": Type ");
6757 pw.print(types.keyAt(j));
6758 pw.print(" = ");
6759 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6760 pw.println();
6761 }
6762 }
6763 }
6764 }
6765 if (dumpPackage == null) {
6766 if (mController != null) {
6767 pw.println(" mController=" + mController
6768 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6769 }
6770 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6771 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6772 }
6773
6774 return needSep;
6775 }
6776 }
6777
6778 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006779 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6780 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781 synchronized (mGlobalLock) {
6782 if (dumpPackage == null) {
6783 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6784 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006785 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6786 if (mRunningVoice != null) {
6787 final long vrToken = proto.start(
6788 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6789 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6790 mRunningVoice.toString());
6791 mVoiceWakeLock.writeToProto(
6792 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6793 proto.end(vrToken);
6794 }
6795 mVrController.writeToProto(proto,
6796 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 if (mController != null) {
6798 final long token = proto.start(CONTROLLER);
6799 proto.write(CONTROLLER, mController.toString());
6800 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6801 proto.end(token);
6802 }
6803 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6804 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6805 }
6806
6807 if (mHomeProcess != null && (dumpPackage == null
6808 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006809 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 }
6811
6812 if (mPreviousProcess != null && (dumpPackage == null
6813 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006814 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6816 }
6817
6818 if (mHeavyWeightProcess != null && (dumpPackage == null
6819 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006820 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 }
6822
6823 for (Map.Entry<String, Integer> entry
6824 : mCompatModePackages.getPackages().entrySet()) {
6825 String pkg = entry.getKey();
6826 int mode = entry.getValue();
6827 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6828 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6829 proto.write(PACKAGE, pkg);
6830 proto.write(MODE, mode);
6831 proto.end(compatToken);
6832 }
6833 }
6834
6835 if (mCurAppTimeTracker != null) {
6836 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6837 }
6838
6839 }
6840 }
6841
6842 @Override
6843 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6844 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6845 boolean dumpFocusedStackOnly) {
6846 synchronized (mGlobalLock) {
6847 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6848 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6849 }
6850 }
6851
6852 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006853 public void dumpForOom(PrintWriter pw) {
6854 synchronized (mGlobalLock) {
6855 pw.println(" mHomeProcess: " + mHomeProcess);
6856 pw.println(" mPreviousProcess: " + mPreviousProcess);
6857 if (mHeavyWeightProcess != null) {
6858 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6859 }
6860 }
6861 }
6862
6863 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 public boolean canGcNow() {
6865 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006866 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868 }
6869
6870 @Override
6871 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006872 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006873 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 return top != null ? top.app : null;
6875 }
6876 }
6877
6878 @Override
6879 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006880 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006881 if (mRootActivityContainer != null) {
6882 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006883 }
6884 }
6885 }
6886
6887 @Override
6888 public void scheduleDestroyAllActivities(String reason) {
6889 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006890 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006891 }
6892 }
6893
6894 @Override
6895 public void removeUser(int userId) {
6896 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006897 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 }
6899 }
6900
6901 @Override
6902 public boolean switchUser(int userId, UserState userState) {
6903 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006904 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 }
6906 }
6907
6908 @Override
6909 public void onHandleAppCrash(WindowProcessController wpc) {
6910 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 }
6913 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006914
6915 @Override
6916 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6917 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006918 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006919 }
6920 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006921
6922 @Override
6923 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006924 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006925 mActiveUids.put(uid, procState);
6926 }
6927 }
6928
6929 @Override
6930 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006931 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006932 mActiveUids.remove(uid);
6933 }
6934 }
6935
6936 @Override
6937 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006938 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006939 mActiveUids.clear();
6940 }
6941 }
6942
6943 @Override
6944 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006945 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006946 if (mActiveUids.get(uid) != null) {
6947 mActiveUids.put(uid, procState);
6948 }
6949 }
6950 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006951
6952 @Override
6953 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006954 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006955 mPendingTempWhitelist.put(uid, tag);
6956 }
6957 }
6958
6959 @Override
6960 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006961 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006962 mPendingTempWhitelist.remove(uid);
6963 }
6964 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006965
6966 @Override
6967 public boolean handleAppCrashInActivityController(String processName, int pid,
6968 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6969 Runnable killCrashingAppCallback) {
6970 synchronized (mGlobalLock) {
6971 if (mController == null) {
6972 return false;
6973 }
6974
6975 try {
6976 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6977 stackTrace)) {
6978 killCrashingAppCallback.run();
6979 return true;
6980 }
6981 } catch (RemoteException e) {
6982 mController = null;
6983 Watchdog.getInstance().setActivityController(null);
6984 }
6985 return false;
6986 }
6987 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006988
6989 @Override
6990 public void removeRecentTasksByPackageName(String packageName, int userId) {
6991 synchronized (mGlobalLock) {
6992 mRecentTasks.removeTasksByPackageName(packageName, userId);
6993 }
6994 }
6995
6996 @Override
6997 public void cleanupRecentTasksForUser(int userId) {
6998 synchronized (mGlobalLock) {
6999 mRecentTasks.cleanupLocked(userId);
7000 }
7001 }
7002
7003 @Override
7004 public void loadRecentTasksForUser(int userId) {
7005 synchronized (mGlobalLock) {
7006 mRecentTasks.loadUserRecentsLocked(userId);
7007 }
7008 }
7009
7010 @Override
7011 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7012 synchronized (mGlobalLock) {
7013 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7014 }
7015 }
7016
7017 @Override
7018 public void flushRecentTasks() {
7019 mRecentTasks.flush();
7020 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007021
7022 @Override
7023 public WindowProcessController getHomeProcess() {
7024 synchronized (mGlobalLock) {
7025 return mHomeProcess;
7026 }
7027 }
7028
7029 @Override
7030 public WindowProcessController getPreviousProcess() {
7031 synchronized (mGlobalLock) {
7032 return mPreviousProcess;
7033 }
7034 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007035
7036 @Override
7037 public void clearLockedTasks(String reason) {
7038 synchronized (mGlobalLock) {
7039 getLockTaskController().clearLockedTasks(reason);
7040 }
7041 }
7042
7043 @Override
7044 public void updateUserConfiguration() {
7045 synchronized (mGlobalLock) {
7046 final Configuration configuration = new Configuration(getGlobalConfiguration());
7047 final int currentUserId = mAmInternal.getCurrentUserId();
7048 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7049 configuration, currentUserId, Settings.System.canWrite(mContext));
7050 updateConfigurationLocked(configuration, null /* starting */,
7051 false /* initLocale */, false /* persistent */, currentUserId,
7052 false /* deferResume */);
7053 }
7054 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007055
7056 @Override
7057 public boolean canShowErrorDialogs() {
7058 synchronized (mGlobalLock) {
7059 return mShowDialogs && !mSleeping && !mShuttingDown
7060 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7061 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7062 mAmInternal.getCurrentUserId())
7063 && !(UserManager.isDeviceInDemoMode(mContext)
7064 && mAmInternal.getCurrentUser().isDemo());
7065 }
7066 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007067
7068 @Override
7069 public void setProfileApp(String profileApp) {
7070 synchronized (mGlobalLock) {
7071 mProfileApp = profileApp;
7072 }
7073 }
7074
7075 @Override
7076 public void setProfileProc(WindowProcessController wpc) {
7077 synchronized (mGlobalLock) {
7078 mProfileProc = wpc;
7079 }
7080 }
7081
7082 @Override
7083 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7084 synchronized (mGlobalLock) {
7085 mProfilerInfo = profilerInfo;
7086 }
7087 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007088
7089 @Override
7090 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7091 synchronized (mGlobalLock) {
7092 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7093 }
7094 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007095
7096 @Override
7097 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7098 synchronized (mGlobalLock) {
7099 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7100 }
7101 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007102
7103 @Override
7104 public boolean isUidForeground(int uid) {
7105 synchronized (mGlobalLock) {
7106 return ActivityTaskManagerService.this.isUidForeground(uid);
7107 }
7108 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007109 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007110}