blob: a8b56d3ccbed024dfd549195128df70f3abe7d7f [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100137import android.app.AppOpsManager;
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;
Mark Renouf446251d2019-04-26 10:22:41 -0400144import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.Notification;
147import android.app.NotificationManager;
148import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.PictureInPictureParams;
150import android.app.ProfilerInfo;
151import android.app.RemoteAction;
152import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700153import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.admin.DevicePolicyCache;
155import 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;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100196import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900212import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800229import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100250import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314
Wale Ogunwale98875612018-10-12 07:53:02 -0700315 /** Used to indicate that an app transition should be animated. */
316 static final boolean ANIMATE = true;
317
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700318 /** Hardware-reported OpenGLES version. */
319 final int GL_ES_VERSION;
320
Wale Ogunwale31913b52018-10-13 08:29:31 -0700321 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
322 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
323 public static final String DUMP_LASTANR_CMD = "lastanr" ;
324 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
325 public static final String DUMP_STARTER_CMD = "starter" ;
326 public static final String DUMP_CONTAINERS_CMD = "containers" ;
327 public static final String DUMP_RECENTS_CMD = "recents" ;
328 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
329
Wale Ogunwale64258362018-10-16 15:13:37 -0700330 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
331 public static final int RELAUNCH_REASON_NONE = 0;
332 /** This activity is being relaunched due to windowing mode change. */
333 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
334 /** This activity is being relaunched due to a free-resize operation. */
335 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
336
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700337 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700338
Wale Ogunwalef6733932018-06-27 05:14:34 -0700339 /**
340 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
341 * change at runtime. Use mContext for non-UI purposes.
342 */
343 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700345 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700346 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700348 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700349 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800350 @VisibleForTesting
351 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 PowerManagerInternal mPowerManagerInternal;
353 private UsageStatsManagerInternal mUsageStatsInternal;
354
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700355 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 IntentFirewall mIntentFirewall;
357
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700358 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800359 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800360 /**
361 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
362 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
363 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
364 *
365 * @see WindowManagerThreadPriorityBooster
366 */
367 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700368 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800369 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700370 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700371 private UserManagerService mUserManager;
372 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700373 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800374 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700375 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700376 /** All processes currently running that might have a window organized by name. */
377 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100378 /** All processes we currently have running mapped by pid and uid */
379 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** This is the process holding what we currently consider to be the "home" activity. */
381 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700382 /** The currently running heavy-weight process, if any. */
383 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700384 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /**
386 * This is the process holding the activity the user last visited that is in a different process
387 * from the one they are currently in.
388 */
389 WindowProcessController mPreviousProcess;
390 /** The time at which the previous process was last visible. */
391 long mPreviousProcessVisibleTime;
392
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700393 /** List of intents that were used to start the most recent tasks. */
394 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700395 /** State of external calls telling us if the device is awake or asleep. */
396 private boolean mKeyguardShown = false;
397
398 // Wrapper around VoiceInteractionServiceManager
399 private AssistUtils mAssistUtils;
400
401 // VoiceInteraction session ID that changes for each new request except when
402 // being called for multi-window assist in a single session.
403 private int mViSessionId = 1000;
404
405 // How long to wait in getAssistContextExtras for the activity and foreground services
406 // to respond with the result.
407 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
408
409 // How long top wait when going through the modern assist (which doesn't need to block
410 // on getting this result before starting to launch its UI).
411 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
412
413 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
414 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
415
Alison Cichowlas3e340502018-08-07 17:15:01 -0400416 // Permission tokens are used to temporarily granted a trusted app the ability to call
417 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
418 // showing any appropriate error messages to the user.
419 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
420 10 * MINUTE_IN_MILLIS;
421
422 // How long before the service actually expires a token. This is slightly longer than
423 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
424 // expiration exception.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
426 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
427
428 // How long the service will remember expired tokens, for the purpose of providing error
429 // messaging when a client uses an expired token.
430 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
431 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
432
Marvin Ramin830d4e32019-03-12 13:16:58 +0100433 // How long to whitelist the Services for when requested.
434 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
435
Alison Cichowlas3e340502018-08-07 17:15:01 -0400436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
462 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
507 IActivityController mController = null;
508 boolean mControllerIsAMonkey = false;
509
Wale Ogunwale214f3482018-10-04 11:00:47 -0700510 final int mFactoryTest;
511
512 /** Used to control how we initialize the service. */
513 ComponentName mTopComponent;
514 String mTopAction = Intent.ACTION_MAIN;
515 String mTopData;
516
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800517 /** Profiling app information. */
518 String mProfileApp = null;
519 WindowProcessController mProfileProc = null;
520 ProfilerInfo mProfilerInfo = null;
521
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700523 * Dump of the activity state at the time of the last ANR. Cleared after
524 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
525 */
526 String mLastANRState;
527
528 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700529 * Used to retain an update lock when the foreground activity is in
530 * immersive mode.
531 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700532 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533
534 /**
535 * Packages that are being allowed to perform unrestricted app switches. Mapping is
536 * User -> Type -> uid.
537 */
538 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
539
540 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private int mThumbnailWidth;
542 private int mThumbnailHeight;
543 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Flag that indicates if multi-window is enabled.
547 *
548 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
549 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
550 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
551 * At least one of the forms of multi-window must be enabled in order for this flag to be
552 * initialized to 'true'.
553 *
554 * @see #mSupportsSplitScreenMultiWindow
555 * @see #mSupportsFreeformWindowManagement
556 * @see #mSupportsPictureInPicture
557 * @see #mSupportsMultiDisplay
558 */
559 boolean mSupportsMultiWindow;
560 boolean mSupportsSplitScreenMultiWindow;
561 boolean mSupportsFreeformWindowManagement;
562 boolean mSupportsPictureInPicture;
563 boolean mSupportsMultiDisplay;
564 boolean mForceResizableActivities;
565
566 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
567
568 // VR Vr2d Display Id.
569 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700570
Wale Ogunwalef6733932018-06-27 05:14:34 -0700571 /**
572 * Set while we are wanting to sleep, to prevent any
573 * activities from being started/resumed.
574 *
575 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
576 *
577 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
578 * while in the sleep state until there is a pending transition out of sleep, in which case
579 * mSleeping is set to false, and remains false while awake.
580 *
581 * Whether mSleeping can quickly toggled between true/false without the device actually
582 * display changing states is undefined.
583 */
584 private boolean mSleeping = false;
585
586 /**
587 * The process state used for processes that are running the top activities.
588 * This changes between TOP and TOP_SLEEPING to following mSleeping.
589 */
590 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
591
592 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
593 // automatically. Important for devices without direct input devices.
594 private boolean mShowDialogs = true;
595
596 /** Set if we are shutting down the system, similar to sleeping. */
597 boolean mShuttingDown = false;
598
599 /**
600 * We want to hold a wake lock while running a voice interaction session, since
601 * this may happen with the screen off and we need to keep the CPU running to
602 * be able to continue to interact with the user.
603 */
604 PowerManager.WakeLock mVoiceWakeLock;
605
606 /**
607 * Set while we are running a voice interaction. This overrides sleeping while it is active.
608 */
609 IVoiceInteractionSession mRunningVoice;
610
611 /**
612 * The last resumed activity. This is identical to the current resumed activity most
613 * of the time but could be different when we're pausing one activity before we resume
614 * another activity.
615 */
616 ActivityRecord mLastResumedActivity;
617
618 /**
619 * The activity that is currently being traced as the active resumed activity.
620 *
621 * @see #updateResumedAppTrace
622 */
623 private @Nullable ActivityRecord mTracedResumedActivity;
624
625 /** If non-null, we are tracking the time the user spends in the currently focused app. */
626 AppTimeTracker mCurAppTimeTracker;
627
Wale Ogunwale008163e2018-07-23 23:11:08 -0700628 private AppWarnings mAppWarnings;
629
Wale Ogunwale53783742018-09-16 10:21:51 -0700630 /**
631 * Packages that the user has asked to have run in screen size
632 * compatibility mode instead of filling the screen.
633 */
634 CompatModePackages mCompatModePackages;
635
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 private FontScaleSettingObserver mFontScaleSettingObserver;
637
Ricky Wai96f5c352019-04-10 18:40:17 +0100638 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000639
Wale Ogunwalef6733932018-06-27 05:14:34 -0700640 private final class FontScaleSettingObserver extends ContentObserver {
641 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
642 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
643
644 public FontScaleSettingObserver() {
645 super(mH);
646 final ContentResolver resolver = mContext.getContentResolver();
647 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
648 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
649 UserHandle.USER_ALL);
650 }
651
652 @Override
653 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
654 if (mFontScaleUri.equals(uri)) {
655 updateFontScaleIfNeeded(userId);
656 } else if (mHideErrorDialogsUri.equals(uri)) {
657 synchronized (mGlobalLock) {
658 updateShouldShowDialogsLocked(getGlobalConfiguration());
659 }
660 }
661 }
662 }
663
Riddle Hsua0536432019-02-16 00:38:59 +0800664 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
665 @Target(ElementType.METHOD)
666 @Retention(RetentionPolicy.SOURCE)
667 @interface HotPath {
668 int NONE = 0;
669 int OOM_ADJUSTMENT = 1;
670 int LRU_UPDATE = 2;
671 int PROCESS_CHANGE = 3;
672 int caller() default NONE;
673 }
674
Charles Chen8d98dd22018-12-26 17:36:54 +0800675 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
676 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700677 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700678 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700679 mSystemThread = ActivityThread.currentActivityThread();
680 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700681 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800682 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700683 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 }
685
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700686 public void onSystemReady() {
687 synchronized (mGlobalLock) {
688 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
689 PackageManager.FEATURE_CANT_SAVE_STATE);
690 mAssistUtils = new AssistUtils(mContext);
691 mVrController.onSystemReady();
692 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700693 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700694 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700695 }
696
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700697 public void onInitPowerManagement() {
698 synchronized (mGlobalLock) {
699 mStackSupervisor.initPowerManagement();
700 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
701 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
702 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
703 mVoiceWakeLock.setReferenceCounted(false);
704 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700708 mFontScaleSettingObserver = new FontScaleSettingObserver();
709 }
710
Wale Ogunwale59507092018-10-29 09:00:30 -0700711 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700712 final boolean freeformWindowManagement =
713 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
714 || Settings.Global.getInt(
715 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
716
717 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
718 final boolean supportsPictureInPicture = supportsMultiWindow &&
719 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
720 final boolean supportsSplitScreenMultiWindow =
721 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
722 final boolean supportsMultiDisplay = mContext.getPackageManager()
723 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700724 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
725 final boolean forceResizable = Settings.Global.getInt(
726 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700727 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728
729 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900730 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700731
732 final Configuration configuration = new Configuration();
733 Settings.System.getConfiguration(resolver, configuration);
734 if (forceRtl) {
735 // This will take care of setting the correct layout direction flags
736 configuration.setLayoutDirection(configuration.locale);
737 }
738
739 synchronized (mGlobalLock) {
740 mForceResizableActivities = forceResizable;
741 final boolean multiWindowFormEnabled = freeformWindowManagement
742 || supportsSplitScreenMultiWindow
743 || supportsPictureInPicture
744 || supportsMultiDisplay;
745 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
746 mSupportsMultiWindow = true;
747 mSupportsFreeformWindowManagement = freeformWindowManagement;
748 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
749 mSupportsPictureInPicture = supportsPictureInPicture;
750 mSupportsMultiDisplay = supportsMultiDisplay;
751 } else {
752 mSupportsMultiWindow = false;
753 mSupportsFreeformWindowManagement = false;
754 mSupportsSplitScreenMultiWindow = false;
755 mSupportsPictureInPicture = false;
756 mSupportsMultiDisplay = false;
757 }
758 mWindowManager.setForceResizableTasks(mForceResizableActivities);
759 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700760 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
761 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700762 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763 // This happens before any activities are started, so we can change global configuration
764 // in-place.
765 updateConfigurationLocked(configuration, null, true);
766 final Configuration globalConfig = getGlobalConfiguration();
767 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
768
769 // Load resources only after the current configuration has been set.
770 final Resources res = mContext.getResources();
771 mThumbnailWidth = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_width);
773 mThumbnailHeight = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_height);
775
776 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
777 mFullscreenThumbnailScale = (float) res
778 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
779 (float) globalConfig.screenWidthDp;
780 } else {
781 mFullscreenThumbnailScale = res.getFraction(
782 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
783 }
784 }
785 }
786
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800787 public WindowManagerGlobalLock getGlobalLock() {
788 return mGlobalLock;
789 }
790
Yunfan Chen585f2932019-01-29 16:04:45 +0900791 /** For test purpose only. */
792 @VisibleForTesting
793 public ActivityTaskManagerInternal getAtmInternal() {
794 return mInternal;
795 }
796
Riddle Hsud93a6c42018-11-29 21:50:06 +0800797 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
798 Looper looper) {
799 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700800 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700801 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700802 final File systemDir = SystemServiceManager.ensureSystemDir();
803 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
804 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
807 mTempConfig.setToDefaults();
808 mTempConfig.setLocales(LocaleList.getDefault());
809 mConfigurationSeq = mTempConfig.seq = 1;
810 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800811 mRootActivityContainer = new RootActivityContainer(this);
812 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700818 mRecentTasks = createRecentTasks();
819 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mKeyguardController = mStackSupervisor.getKeyguardController();
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void onActivityManagerInternalAdded() {
825 synchronized (mGlobalLock) {
826 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
827 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
828 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700829 }
830
Yunfan Chen75157d72018-07-27 14:47:21 +0900831 int increaseConfigurationSeqLocked() {
832 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
833 return mConfigurationSeq;
834 }
835
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 protected ActivityStackSupervisor createStackSupervisor() {
837 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
838 supervisor.initialize();
839 return supervisor;
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void setWindowManager(WindowManagerService wm) {
843 synchronized (mGlobalLock) {
844 mWindowManager = wm;
845 mLockTaskController.setWindowManager(wm);
846 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800847 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700849 }
850
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
852 synchronized (mGlobalLock) {
853 mUsageStatsInternal = usageStatsManager;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 }
856
Wale Ogunwalef6733932018-06-27 05:14:34 -0700857 UserManagerService getUserManager() {
858 if (mUserManager == null) {
859 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
860 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
861 }
862 return mUserManager;
863 }
864
865 AppOpsService getAppOpsService() {
866 if (mAppOpsService == null) {
867 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
868 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
869 }
870 return mAppOpsService;
871 }
872
873 boolean hasUserRestriction(String restriction, int userId) {
874 return getUserManager().hasUserRestriction(restriction, userId);
875 }
876
Michal Karpinski15486842019-04-25 17:33:42 +0100877 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
878 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
879 callingUid, callingPackage);
880 if (mode == AppOpsManager.MODE_DEFAULT) {
881 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
882 == PERMISSION_GRANTED;
883 }
884 return mode == AppOpsManager.MODE_ALLOWED;
885 }
886
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700887 protected RecentTasks createRecentTasks() {
888 return new RecentTasks(this, mStackSupervisor);
889 }
890
891 RecentTasks getRecentTasks() {
892 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700893 }
894
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700895 ClientLifecycleManager getLifecycleManager() {
896 return mLifecycleManager;
897 }
898
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700899 ActivityStartController getActivityStartController() {
900 return mActivityStartController;
901 }
902
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700903 TaskChangeNotificationController getTaskChangeNotificationController() {
904 return mTaskChangeNotificationController;
905 }
906
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700907 LockTaskController getLockTaskController() {
908 return mLockTaskController;
909 }
910
Yunfan Chen75157d72018-07-27 14:47:21 +0900911 /**
912 * Return the global configuration used by the process corresponding to the input pid. This is
913 * usually the global configuration with some overrides specific to that process.
914 */
915 Configuration getGlobalConfigurationForCallingPid() {
916 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800917 return getGlobalConfigurationForPid(pid);
918 }
919
920 /**
921 * Return the global configuration used by the process corresponding to the given pid.
922 */
923 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900924 if (pid == MY_PID || pid < 0) {
925 return getGlobalConfiguration();
926 }
927 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100928 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 return app != null ? app.getConfiguration() : getGlobalConfiguration();
930 }
931 }
932
933 /**
934 * Return the device configuration info used by the process corresponding to the input pid.
935 * The value is consistent with the global configuration for the process.
936 */
937 @Override
938 public ConfigurationInfo getDeviceConfigurationInfo() {
939 ConfigurationInfo config = new ConfigurationInfo();
940 synchronized (mGlobalLock) {
941 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
942 config.reqTouchScreen = globalConfig.touchscreen;
943 config.reqKeyboardType = globalConfig.keyboard;
944 config.reqNavigation = globalConfig.navigation;
945 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
946 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
947 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
948 }
949 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
950 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
951 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
952 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700953 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900954 }
955 return config;
956 }
957
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700958 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700959 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 }
961
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 public static final class Lifecycle extends SystemService {
963 private final ActivityTaskManagerService mService;
964
965 public Lifecycle(Context context) {
966 super(context);
967 mService = new ActivityTaskManagerService(context);
968 }
969
970 @Override
971 public void onStart() {
972 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700973 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700974 }
975
Garfield Tan891146c2018-10-09 12:14:00 -0700976 @Override
977 public void onUnlockUser(int userId) {
978 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800979 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700980 }
981 }
982
983 @Override
984 public void onCleanupUser(int userId) {
985 synchronized (mService.getGlobalLock()) {
986 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
987 }
988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public ActivityTaskManagerService getService() {
991 return mService;
992 }
993 }
994
995 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 public final int startActivity(IApplicationThread caller, String callingPackage,
997 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
998 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
999 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1000 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1001 UserHandle.getCallingUserId());
1002 }
1003
1004 @Override
1005 public final int startActivities(IApplicationThread caller, String callingPackage,
1006 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1007 int userId) {
1008 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001009 enforceNotIsolatedCaller(reason);
1010 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001011 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001012 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1013 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1014 reason, null /* originatingPendingIntent */,
1015 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017
1018 @Override
1019 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1020 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1021 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1022 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1023 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1024 true /*validateIncomingUser*/);
1025 }
1026
1027 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1030 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001031 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001033 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1035
1036 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001037 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 .setCaller(caller)
1039 .setCallingPackage(callingPackage)
1040 .setResolvedType(resolvedType)
1041 .setResultTo(resultTo)
1042 .setResultWho(resultWho)
1043 .setRequestCode(requestCode)
1044 .setStartFlags(startFlags)
1045 .setProfilerInfo(profilerInfo)
1046 .setActivityOptions(bOptions)
1047 .setMayWait(userId)
1048 .execute();
1049
1050 }
1051
1052 @Override
1053 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1054 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001055 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1056 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 // Refuse possible leaked file descriptors
1058 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1059 throw new IllegalArgumentException("File descriptors passed in Intent");
1060 }
1061
1062 if (!(target instanceof PendingIntentRecord)) {
1063 throw new IllegalArgumentException("Bad PendingIntent object");
1064 }
1065
1066 PendingIntentRecord pir = (PendingIntentRecord)target;
1067
1068 synchronized (mGlobalLock) {
1069 // If this is coming from the currently resumed activity, it is
1070 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001071 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 if (stack.mResumedActivity != null &&
1073 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001074 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 }
1076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001077 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 }
1080
1081 @Override
1082 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1083 Bundle bOptions) {
1084 // Refuse possible leaked file descriptors
1085 if (intent != null && intent.hasFileDescriptors()) {
1086 throw new IllegalArgumentException("File descriptors passed in Intent");
1087 }
1088 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1089
1090 synchronized (mGlobalLock) {
1091 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1092 if (r == null) {
1093 SafeActivityOptions.abort(options);
1094 return false;
1095 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001096 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 // The caller is not running... d'oh!
1098 SafeActivityOptions.abort(options);
1099 return false;
1100 }
1101 intent = new Intent(intent);
1102 // The caller is not allowed to change the data.
1103 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1104 // And we are resetting to find the next component...
1105 intent.setComponent(null);
1106
1107 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1108
1109 ActivityInfo aInfo = null;
1110 try {
1111 List<ResolveInfo> resolves =
1112 AppGlobals.getPackageManager().queryIntentActivities(
1113 intent, r.resolvedType,
1114 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1115 UserHandle.getCallingUserId()).getList();
1116
1117 // Look for the original activity in the list...
1118 final int N = resolves != null ? resolves.size() : 0;
1119 for (int i=0; i<N; i++) {
1120 ResolveInfo rInfo = resolves.get(i);
1121 if (rInfo.activityInfo.packageName.equals(r.packageName)
1122 && rInfo.activityInfo.name.equals(r.info.name)) {
1123 // We found the current one... the next matching is
1124 // after it.
1125 i++;
1126 if (i<N) {
1127 aInfo = resolves.get(i).activityInfo;
1128 }
1129 if (debug) {
1130 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1131 + "/" + r.info.name);
1132 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1133 ? "null" : aInfo.packageName + "/" + aInfo.name));
1134 }
1135 break;
1136 }
1137 }
1138 } catch (RemoteException e) {
1139 }
1140
1141 if (aInfo == null) {
1142 // Nobody who is next!
1143 SafeActivityOptions.abort(options);
1144 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1145 return false;
1146 }
1147
1148 intent.setComponent(new ComponentName(
1149 aInfo.applicationInfo.packageName, aInfo.name));
1150 intent.setFlags(intent.getFlags()&~(
1151 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1152 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1153 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1154 FLAG_ACTIVITY_NEW_TASK));
1155
1156 // Okay now we need to start the new activity, replacing the currently running activity.
1157 // This is a little tricky because we want to start the new one as if the current one is
1158 // finished, but not finish the current one first so that there is no flicker.
1159 // And thus...
1160 final boolean wasFinishing = r.finishing;
1161 r.finishing = true;
1162
1163 // Propagate reply information over to the new activity.
1164 final ActivityRecord resultTo = r.resultTo;
1165 final String resultWho = r.resultWho;
1166 final int requestCode = r.requestCode;
1167 r.resultTo = null;
1168 if (resultTo != null) {
1169 resultTo.removeResultsLocked(r, resultWho, requestCode);
1170 }
1171
1172 final long origId = Binder.clearCallingIdentity();
1173 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001174 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001176 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .setResolvedType(r.resolvedType)
1178 .setActivityInfo(aInfo)
1179 .setResultTo(resultTo != null ? resultTo.appToken : null)
1180 .setResultWho(resultWho)
1181 .setRequestCode(requestCode)
1182 .setCallingPid(-1)
1183 .setCallingUid(r.launchedFromUid)
1184 .setCallingPackage(r.launchedFromPackage)
1185 .setRealCallingPid(-1)
1186 .setRealCallingUid(r.launchedFromUid)
1187 .setActivityOptions(options)
1188 .execute();
1189 Binder.restoreCallingIdentity(origId);
1190
1191 r.finishing = wasFinishing;
1192 if (res != ActivityManager.START_SUCCESS) {
1193 return false;
1194 }
1195 return true;
1196 }
1197 }
1198
1199 @Override
1200 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1201 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1202 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1203 final WaitResult res = new WaitResult();
1204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001205 enforceNotIsolatedCaller("startActivityAndWait");
1206 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1207 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001209 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .setCaller(caller)
1211 .setCallingPackage(callingPackage)
1212 .setResolvedType(resolvedType)
1213 .setResultTo(resultTo)
1214 .setResultWho(resultWho)
1215 .setRequestCode(requestCode)
1216 .setStartFlags(startFlags)
1217 .setActivityOptions(bOptions)
1218 .setMayWait(userId)
1219 .setProfilerInfo(profilerInfo)
1220 .setWaitResult(res)
1221 .execute();
1222 }
1223 return res;
1224 }
1225
1226 @Override
1227 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1228 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1229 int startFlags, Configuration config, Bundle bOptions, int userId) {
1230 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001231 enforceNotIsolatedCaller("startActivityWithConfig");
1232 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1233 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001234 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001235 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 .setCaller(caller)
1237 .setCallingPackage(callingPackage)
1238 .setResolvedType(resolvedType)
1239 .setResultTo(resultTo)
1240 .setResultWho(resultWho)
1241 .setRequestCode(requestCode)
1242 .setStartFlags(startFlags)
1243 .setGlobalConfiguration(config)
1244 .setActivityOptions(bOptions)
1245 .setMayWait(userId)
1246 .execute();
1247 }
1248 }
1249
Alison Cichowlas3e340502018-08-07 17:15:01 -04001250
1251 @Override
1252 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1253 int callingUid = Binder.getCallingUid();
1254 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1255 throw new SecurityException("Only the system process can request a permission token, "
1256 + "received request from uid: " + callingUid);
1257 }
1258 IBinder permissionToken = new Binder();
1259 synchronized (mGlobalLock) {
1260 mStartActivitySources.put(permissionToken, delegatorToken);
1261 }
1262
1263 Message expireMsg = PooledLambda.obtainMessage(
1264 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1265 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1266
1267 Message forgetMsg = PooledLambda.obtainMessage(
1268 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1269 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1270
1271 return permissionToken;
1272 }
1273
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 @Override
1275 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1276 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1278 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001280 // permission grants) as any app that may launch one of your own activities. So we only
1281 // allow this in two cases:
1282 // 1) The caller is an activity that is part of the core framework, and then only when it
1283 // is running as the system.
1284 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1285 // can only be requested by a system activity, which may then delegate this call to
1286 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 final ActivityRecord sourceRecord;
1288 final int targetUid;
1289 final String targetPackage;
1290 final boolean isResolver;
1291 synchronized (mGlobalLock) {
1292 if (resultTo == null) {
1293 throw new SecurityException("Must be called from an activity");
1294 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 final IBinder sourceToken;
1296 if (permissionToken != null) {
1297 // To even attempt to use a permissionToken, an app must also have this signature
1298 // permission.
1299 mAmInternal.enforceCallingPermission(
1300 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1301 "startActivityAsCaller");
1302 // If called with a permissionToken, we want the sourceRecord from the delegator
1303 // activity that requested this token.
1304 sourceToken = mStartActivitySources.remove(permissionToken);
1305 if (sourceToken == null) {
1306 // Invalid permissionToken, check if it recently expired.
1307 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1308 throw new SecurityException("Called with expired permission token: "
1309 + permissionToken);
1310 } else {
1311 throw new SecurityException("Called with invalid permission token: "
1312 + permissionToken);
1313 }
1314 }
1315 } else {
1316 // This method was called directly by the source.
1317 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001318 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319
Wale Ogunwaled32da472018-11-16 07:19:28 -08001320 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001321 if (sourceRecord == null) {
1322 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 }
1324 if (sourceRecord.app == null) {
1325 throw new SecurityException("Called without a process attached to activity");
1326 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327
1328 // Whether called directly or from a delegate, the source activity must be from the
1329 // android package.
1330 if (!sourceRecord.info.packageName.equals("android")) {
1331 throw new SecurityException("Must be called from an activity that is "
1332 + "declared in the android package");
1333 }
1334
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001335 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 // This is still okay, as long as this activity is running under the
1337 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001338 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 + " must be system uid or original calling uid "
1342 + sourceRecord.launchedFromUid);
1343 }
1344 }
1345 if (ignoreTargetSecurity) {
1346 if (intent.getComponent() == null) {
1347 throw new SecurityException(
1348 "Component must be specified with ignoreTargetSecurity");
1349 }
1350 if (intent.getSelector() != null) {
1351 throw new SecurityException(
1352 "Selector not allowed with ignoreTargetSecurity");
1353 }
1354 }
1355 targetUid = sourceRecord.launchedFromUid;
1356 targetPackage = sourceRecord.launchedFromPackage;
1357 isResolver = sourceRecord.isResolverOrChildActivity();
1358 }
1359
1360 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001361 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 }
1363
1364 // TODO: Switch to user app stacks here.
1365 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001366 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367 .setCallingUid(targetUid)
1368 .setCallingPackage(targetPackage)
1369 .setResolvedType(resolvedType)
1370 .setResultTo(resultTo)
1371 .setResultWho(resultWho)
1372 .setRequestCode(requestCode)
1373 .setStartFlags(startFlags)
1374 .setActivityOptions(bOptions)
1375 .setMayWait(userId)
1376 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1377 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001378 // The target may well be in the background, which would normally prevent it
1379 // from starting an activity. Here we definitely want the start to succeed.
1380 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 .execute();
1382 } catch (SecurityException e) {
1383 // XXX need to figure out how to propagate to original app.
1384 // A SecurityException here is generally actually a fault of the original
1385 // calling activity (such as a fairly granting permissions), so propagate it
1386 // back to them.
1387 /*
1388 StringBuilder msg = new StringBuilder();
1389 msg.append("While launching");
1390 msg.append(intent.toString());
1391 msg.append(": ");
1392 msg.append(e.getMessage());
1393 */
1394 throw e;
1395 }
1396 }
1397
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001398 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1399 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1400 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1401 }
1402
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 @Override
1404 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1405 Intent intent, String resolvedType, IVoiceInteractionSession session,
1406 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1407 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001408 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 if (session == null || interactor == null) {
1410 throw new NullPointerException("null session or interactor");
1411 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001412 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001414 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 .setCallingUid(callingUid)
1416 .setCallingPackage(callingPackage)
1417 .setResolvedType(resolvedType)
1418 .setVoiceSession(session)
1419 .setVoiceInteractor(interactor)
1420 .setStartFlags(startFlags)
1421 .setProfilerInfo(profilerInfo)
1422 .setActivityOptions(bOptions)
1423 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001424 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 .execute();
1426 }
1427
1428 @Override
1429 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1430 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1432 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001434 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 .setCallingUid(callingUid)
1436 .setCallingPackage(callingPackage)
1437 .setResolvedType(resolvedType)
1438 .setActivityOptions(bOptions)
1439 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001440 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 .execute();
1442 }
1443
1444 @Override
1445 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1446 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001447 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 final int callingPid = Binder.getCallingPid();
1449 final long origId = Binder.clearCallingIdentity();
1450 try {
1451 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001452 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1453 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454
1455 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001456 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1457 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1459 recentsUid, assistDataReceiver);
1460 }
1461 } finally {
1462 Binder.restoreCallingIdentity(origId);
1463 }
1464 }
1465
1466 @Override
1467 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001468 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 "startActivityFromRecents()");
1470
1471 final int callingPid = Binder.getCallingPid();
1472 final int callingUid = Binder.getCallingUid();
1473 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1474 final long origId = Binder.clearCallingIdentity();
1475 try {
1476 synchronized (mGlobalLock) {
1477 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1478 safeOptions);
1479 }
1480 } finally {
1481 Binder.restoreCallingIdentity(origId);
1482 }
1483 }
1484
1485 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001486 * Public API to check if the client is allowed to start an activity on specified display.
1487 *
1488 * If the target display is private or virtual, some restrictions will apply.
1489 *
1490 * @param displayId Target display id.
1491 * @param intent Intent used to launch the activity.
1492 * @param resolvedType The MIME type of the intent.
1493 * @param userId The id of the user for whom the call is made.
1494 * @return {@code true} if a call to start an activity on the target display should succeed and
1495 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1496 */
1497 @Override
1498 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1499 String resolvedType, int userId) {
1500 final int callingUid = Binder.getCallingUid();
1501 final int callingPid = Binder.getCallingPid();
1502 final long origId = Binder.clearCallingIdentity();
1503
1504 try {
1505 // Collect information about the target of the Intent.
1506 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1507 0 /* startFlags */, null /* profilerInfo */, userId,
1508 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1509 UserHandle.USER_NULL));
1510 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1511
1512 synchronized (mGlobalLock) {
1513 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1514 aInfo);
1515 }
1516 } finally {
1517 Binder.restoreCallingIdentity(origId);
1518 }
1519 }
1520
1521 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001522 * This is the internal entry point for handling Activity.finish().
1523 *
1524 * @param token The Binder token referencing the Activity we want to finish.
1525 * @param resultCode Result code, if any, from this Activity.
1526 * @param resultData Result data (Intent), if any, from this Activity.
1527 * @param finishTask Whether to finish the task associated with this Activity.
1528 *
1529 * @return Returns true if the activity successfully finished, or false if it is still running.
1530 */
1531 @Override
1532 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1533 int finishTask) {
1534 // Refuse possible leaked file descriptors
1535 if (resultData != null && resultData.hasFileDescriptors()) {
1536 throw new IllegalArgumentException("File descriptors passed in Intent");
1537 }
1538
1539 synchronized (mGlobalLock) {
1540 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1541 if (r == null) {
1542 return true;
1543 }
1544 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001545 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 ActivityRecord rootR = tr.getRootActivity();
1547 if (rootR == null) {
1548 Slog.w(TAG, "Finishing task with all activities already finished");
1549 }
1550 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1551 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001552 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 return false;
1554 }
1555
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001556 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1557 // We should consolidate.
1558 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001559 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001560 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 if (next != null) {
1562 // ask watcher if this is allowed
1563 boolean resumeOK = true;
1564 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001565 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001567 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 Watchdog.getInstance().setActivityController(null);
1569 }
1570
1571 if (!resumeOK) {
1572 Slog.i(TAG, "Not finishing activity because controller resumed");
1573 return false;
1574 }
1575 }
1576 }
1577 final long origId = Binder.clearCallingIdentity();
1578 try {
1579 boolean res;
1580 final boolean finishWithRootActivity =
1581 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1582 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1583 || (finishWithRootActivity && r == rootR)) {
1584 // If requested, remove the task that is associated to this activity only if it
1585 // was the root activity in the task. The result code and data is ignored
1586 // because we don't support returning them across task boundaries. Also, to
1587 // keep backwards compatibility we remove the task from recents when finishing
1588 // task with root activity.
1589 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1590 finishWithRootActivity, "finish-activity");
1591 if (!res) {
1592 Slog.i(TAG, "Removing task failed to finish activity");
1593 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001594 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001595 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 } else {
1597 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1598 resultData, "app-request", true);
1599 if (!res) {
1600 Slog.i(TAG, "Failed to finish by app-request");
1601 }
1602 }
1603 return res;
1604 } finally {
1605 Binder.restoreCallingIdentity(origId);
1606 }
1607 }
1608 }
1609
1610 @Override
1611 public boolean finishActivityAffinity(IBinder token) {
1612 synchronized (mGlobalLock) {
1613 final long origId = Binder.clearCallingIdentity();
1614 try {
1615 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1616 if (r == null) {
1617 return false;
1618 }
1619
1620 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1621 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001622 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001623 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001624 return false;
1625 }
1626 return task.getStack().finishActivityAffinityLocked(r);
1627 } finally {
1628 Binder.restoreCallingIdentity(origId);
1629 }
1630 }
1631 }
1632
1633 @Override
1634 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1635 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001636 try {
1637 WindowProcessController proc = null;
1638 synchronized (mGlobalLock) {
1639 ActivityStack stack = ActivityRecord.getStackLocked(token);
1640 if (stack == null) {
1641 return;
1642 }
1643 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1644 false /* fromTimeout */, false /* processPausingActivities */, config);
1645 if (r != null) {
1646 proc = r.app;
1647 }
1648 if (stopProfiling && proc != null) {
1649 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 }
1651 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001652 } finally {
1653 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 }
1656
1657 @Override
1658 public final void activityResumed(IBinder token) {
1659 final long origId = Binder.clearCallingIdentity();
1660 synchronized (mGlobalLock) {
1661 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001662 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 }
1664 Binder.restoreCallingIdentity(origId);
1665 }
1666
1667 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001668 public final void activityTopResumedStateLost() {
1669 final long origId = Binder.clearCallingIdentity();
1670 synchronized (mGlobalLock) {
1671 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1672 }
1673 Binder.restoreCallingIdentity(origId);
1674 }
1675
1676 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 public final void activityPaused(IBinder token) {
1678 final long origId = Binder.clearCallingIdentity();
1679 synchronized (mGlobalLock) {
1680 ActivityStack stack = ActivityRecord.getStackLocked(token);
1681 if (stack != null) {
1682 stack.activityPausedLocked(token, false);
1683 }
1684 }
1685 Binder.restoreCallingIdentity(origId);
1686 }
1687
1688 @Override
1689 public final void activityStopped(IBinder token, Bundle icicle,
1690 PersistableBundle persistentState, CharSequence description) {
1691 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1692
1693 // Refuse possible leaked file descriptors
1694 if (icicle != null && icicle.hasFileDescriptors()) {
1695 throw new IllegalArgumentException("File descriptors passed in Bundle");
1696 }
1697
1698 final long origId = Binder.clearCallingIdentity();
1699
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001700 String restartingName = null;
1701 int restartingUid = 0;
1702 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001704 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001705 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001706 if (r.attachedToProcess()
1707 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1708 // The activity was requested to restart from
1709 // {@link #restartActivityProcessIfVisible}.
1710 restartingName = r.app.mName;
1711 restartingUid = r.app.mUid;
1712 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 r.activityStoppedLocked(icicle, persistentState, description);
1714 }
1715 }
1716
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001717 if (restartingName != null) {
1718 // In order to let the foreground activity can be restarted with its saved state from
1719 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1720 // until the activity reports stopped with the state. And the activity record will be
1721 // kept because the record state is restarting, then the activity will be restarted
1722 // immediately if it is still the top one.
1723 mStackSupervisor.removeRestartTimeouts(r);
1724 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1725 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001726 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727
1728 Binder.restoreCallingIdentity(origId);
1729 }
1730
1731 @Override
1732 public final void activityDestroyed(IBinder token) {
1733 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1734 synchronized (mGlobalLock) {
1735 ActivityStack stack = ActivityRecord.getStackLocked(token);
1736 if (stack != null) {
1737 stack.activityDestroyedLocked(token, "activityDestroyed");
1738 }
1739 }
1740 }
1741
1742 @Override
1743 public final void activityRelaunched(IBinder token) {
1744 final long origId = Binder.clearCallingIdentity();
1745 synchronized (mGlobalLock) {
1746 mStackSupervisor.activityRelaunchedLocked(token);
1747 }
1748 Binder.restoreCallingIdentity(origId);
1749 }
1750
1751 public final void activitySlept(IBinder token) {
1752 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1753
1754 final long origId = Binder.clearCallingIdentity();
1755
1756 synchronized (mGlobalLock) {
1757 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1758 if (r != null) {
1759 mStackSupervisor.activitySleptLocked(r);
1760 }
1761 }
1762
1763 Binder.restoreCallingIdentity(origId);
1764 }
1765
1766 @Override
1767 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1768 synchronized (mGlobalLock) {
1769 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1770 if (r == null) {
1771 return;
1772 }
1773 final long origId = Binder.clearCallingIdentity();
1774 try {
1775 r.setRequestedOrientation(requestedOrientation);
1776 } finally {
1777 Binder.restoreCallingIdentity(origId);
1778 }
1779 }
1780 }
1781
1782 @Override
1783 public int getRequestedOrientation(IBinder token) {
1784 synchronized (mGlobalLock) {
1785 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1786 if (r == null) {
1787 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1788 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001789 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 }
1791 }
1792
1793 @Override
1794 public void setImmersive(IBinder token, boolean immersive) {
1795 synchronized (mGlobalLock) {
1796 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1797 if (r == null) {
1798 throw new IllegalArgumentException();
1799 }
1800 r.immersive = immersive;
1801
1802 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001803 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001805 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
1807 }
1808 }
1809
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001810 void applyUpdateLockStateLocked(ActivityRecord r) {
1811 // Modifications to the UpdateLock state are done on our handler, outside
1812 // the activity manager's locks. The new state is determined based on the
1813 // state *now* of the relevant activity record. The object is passed to
1814 // the handler solely for logging detail, not to be consulted/modified.
1815 final boolean nextState = r != null && r.immersive;
1816 mH.post(() -> {
1817 if (mUpdateLock.isHeld() != nextState) {
1818 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1819 "Applying new update lock state '" + nextState + "' for " + r);
1820 if (nextState) {
1821 mUpdateLock.acquire();
1822 } else {
1823 mUpdateLock.release();
1824 }
1825 }
1826 });
1827 }
1828
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001829 @Override
1830 public boolean isImmersive(IBinder token) {
1831 synchronized (mGlobalLock) {
1832 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1833 if (r == null) {
1834 throw new IllegalArgumentException();
1835 }
1836 return r.immersive;
1837 }
1838 }
1839
1840 @Override
1841 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001842 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001843 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001844 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001845 return (r != null) ? r.immersive : false;
1846 }
1847 }
1848
1849 @Override
1850 public void overridePendingTransition(IBinder token, String packageName,
1851 int enterAnim, int exitAnim) {
1852 synchronized (mGlobalLock) {
1853 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1854 if (self == null) {
1855 return;
1856 }
1857
1858 final long origId = Binder.clearCallingIdentity();
1859
1860 if (self.isState(
1861 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001862 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001863 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 }
1865
1866 Binder.restoreCallingIdentity(origId);
1867 }
1868 }
1869
1870 @Override
1871 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001872 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001873 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001874 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001875 if (r == null) {
1876 return ActivityManager.COMPAT_MODE_UNKNOWN;
1877 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001878 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 }
1880 }
1881
1882 @Override
1883 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001884 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001885 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001887 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001888 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001889 if (r == null) {
1890 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1891 return;
1892 }
1893 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001894 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 }
1896 }
1897
1898 @Override
1899 public int getLaunchedFromUid(IBinder activityToken) {
1900 ActivityRecord srec;
1901 synchronized (mGlobalLock) {
1902 srec = ActivityRecord.forTokenLocked(activityToken);
1903 }
1904 if (srec == null) {
1905 return -1;
1906 }
1907 return srec.launchedFromUid;
1908 }
1909
1910 @Override
1911 public String getLaunchedFromPackage(IBinder activityToken) {
1912 ActivityRecord srec;
1913 synchronized (mGlobalLock) {
1914 srec = ActivityRecord.forTokenLocked(activityToken);
1915 }
1916 if (srec == null) {
1917 return null;
1918 }
1919 return srec.launchedFromPackage;
1920 }
1921
1922 @Override
1923 public boolean convertFromTranslucent(IBinder token) {
1924 final long origId = Binder.clearCallingIdentity();
1925 try {
1926 synchronized (mGlobalLock) {
1927 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1928 if (r == null) {
1929 return false;
1930 }
1931 final boolean translucentChanged = r.changeWindowTranslucency(true);
1932 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001933 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001935 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 return translucentChanged;
1937 }
1938 } finally {
1939 Binder.restoreCallingIdentity(origId);
1940 }
1941 }
1942
1943 @Override
1944 public boolean convertToTranslucent(IBinder token, Bundle options) {
1945 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1946 final long origId = Binder.clearCallingIdentity();
1947 try {
1948 synchronized (mGlobalLock) {
1949 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1950 if (r == null) {
1951 return false;
1952 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001953 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 int index = task.mActivities.lastIndexOf(r);
1955 if (index > 0) {
1956 ActivityRecord under = task.mActivities.get(index - 1);
1957 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1958 }
1959 final boolean translucentChanged = r.changeWindowTranslucency(false);
1960 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001961 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001964 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 return translucentChanged;
1966 }
1967 } finally {
1968 Binder.restoreCallingIdentity(origId);
1969 }
1970 }
1971
1972 @Override
1973 public void notifyActivityDrawn(IBinder token) {
1974 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1975 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001976 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001977 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001978 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001979 }
1980 }
1981 }
1982
1983 @Override
1984 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1985 synchronized (mGlobalLock) {
1986 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1987 if (r == null) {
1988 return;
1989 }
1990 r.reportFullyDrawnLocked(restoredFromBundle);
1991 }
1992 }
1993
1994 @Override
1995 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1996 synchronized (mGlobalLock) {
1997 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1998 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1999 return stack.mDisplayId;
2000 }
2001 return DEFAULT_DISPLAY;
2002 }
2003 }
2004
2005 @Override
2006 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002007 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 long ident = Binder.clearCallingIdentity();
2009 try {
2010 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002011 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002013 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 }
2015 return null;
2016 }
2017 } finally {
2018 Binder.restoreCallingIdentity(ident);
2019 }
2020 }
2021
2022 @Override
2023 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2026 final long callingId = Binder.clearCallingIdentity();
2027 try {
2028 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002029 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 if (stack == null) {
2031 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2032 return;
2033 }
2034 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002035 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002036 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 }
2038 }
2039 } finally {
2040 Binder.restoreCallingIdentity(callingId);
2041 }
2042 }
2043
2044 @Override
2045 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002046 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2048 final long callingId = Binder.clearCallingIdentity();
2049 try {
2050 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002052 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 if (task == null) {
2054 return;
2055 }
2056 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002057 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002058 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 }
2060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(callingId);
2063 }
2064 }
2065
2066 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002067 public void restartActivityProcessIfVisible(IBinder activityToken) {
2068 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2069 final long callingId = Binder.clearCallingIdentity();
2070 try {
2071 synchronized (mGlobalLock) {
2072 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2073 if (r == null) {
2074 return;
2075 }
2076 r.restartProcessIfVisible();
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002085 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 synchronized (mGlobalLock) {
2087 final long ident = Binder.clearCallingIdentity();
2088 try {
2089 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2090 "remove-task");
2091 } finally {
2092 Binder.restoreCallingIdentity(ident);
2093 }
2094 }
2095 }
2096
2097 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002098 public void removeAllVisibleRecentTasks() {
2099 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2100 synchronized (mGlobalLock) {
2101 final long ident = Binder.clearCallingIdentity();
2102 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002103 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002104 } finally {
2105 Binder.restoreCallingIdentity(ident);
2106 }
2107 }
2108 }
2109
2110 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2112 synchronized (mGlobalLock) {
2113 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2114 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002115 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 }
2117 }
2118 return false;
2119 }
2120
2121 @Override
2122 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2123 Intent resultData) {
2124
2125 synchronized (mGlobalLock) {
2126 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2127 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002128 return r.getActivityStack().navigateUpToLocked(
2129 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 }
2131 return false;
2132 }
2133 }
2134
2135 /**
2136 * Attempts to move a task backwards in z-order (the order of activities within the task is
2137 * unchanged).
2138 *
2139 * There are several possible results of this call:
2140 * - if the task is locked, then we will show the lock toast
2141 * - if there is a task behind the provided task, then that task is made visible and resumed as
2142 * this task is moved to the back
2143 * - otherwise, if there are no other tasks in the stack:
2144 * - if this task is in the pinned stack, then we remove the stack completely, which will
2145 * have the effect of moving the task to the top or bottom of the fullscreen stack
2146 * (depending on whether it is visible)
2147 * - otherwise, we simply return home and hide this task
2148 *
2149 * @param token A reference to the activity we wish to move
2150 * @param nonRoot If false then this only works if the activity is the root
2151 * of a task; if true it will work for any activity in a task.
2152 * @return Returns true if the move completed, false if not.
2153 */
2154 @Override
2155 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002156 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157 synchronized (mGlobalLock) {
2158 final long origId = Binder.clearCallingIdentity();
2159 try {
2160 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002161 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002162 if (task != null) {
2163 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2164 }
2165 } finally {
2166 Binder.restoreCallingIdentity(origId);
2167 }
2168 }
2169 return false;
2170 }
2171
2172 @Override
2173 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002174 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 long ident = Binder.clearCallingIdentity();
2176 Rect rect = new Rect();
2177 try {
2178 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002179 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2181 if (task == null) {
2182 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2183 return rect;
2184 }
2185 if (task.getStack() != null) {
2186 // Return the bounds from window manager since it will be adjusted for various
2187 // things like the presense of a docked stack for tasks that aren't resizeable.
2188 task.getWindowContainerBounds(rect);
2189 } else {
2190 // Task isn't in window manager yet since it isn't associated with a stack.
2191 // Return the persist value from activity manager
2192 if (!task.matchParentBounds()) {
2193 rect.set(task.getBounds());
2194 } else if (task.mLastNonFullscreenBounds != null) {
2195 rect.set(task.mLastNonFullscreenBounds);
2196 }
2197 }
2198 }
2199 } finally {
2200 Binder.restoreCallingIdentity(ident);
2201 }
2202 return rect;
2203 }
2204
2205 @Override
2206 public ActivityManager.TaskDescription getTaskDescription(int id) {
2207 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002208 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002210 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2212 if (tr != null) {
2213 return tr.lastTaskDescription;
2214 }
2215 }
2216 return null;
2217 }
2218
2219 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002220 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2221 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2222 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2223 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2224 return;
2225 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002226 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002227 synchronized (mGlobalLock) {
2228 final long ident = Binder.clearCallingIdentity();
2229 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002230 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002231 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002232 if (task == null) {
2233 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2234 return;
2235 }
2236
2237 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2238 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2239
2240 if (!task.isActivityTypeStandardOrUndefined()) {
2241 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2242 + " non-standard task " + taskId + " to windowing mode="
2243 + windowingMode);
2244 }
2245
2246 final ActivityStack stack = task.getStack();
2247 if (toTop) {
2248 stack.moveToFront("setTaskWindowingMode", task);
2249 }
2250 stack.setWindowingMode(windowingMode);
2251 } finally {
2252 Binder.restoreCallingIdentity(ident);
2253 }
2254 }
2255 }
2256
2257 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002258 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002260 ActivityRecord r = getCallingRecordLocked(token);
2261 return r != null ? r.info.packageName : null;
2262 }
2263 }
2264
2265 @Override
2266 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002267 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002268 ActivityRecord r = getCallingRecordLocked(token);
2269 return r != null ? r.intent.getComponent() : null;
2270 }
2271 }
2272
2273 private ActivityRecord getCallingRecordLocked(IBinder token) {
2274 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2275 if (r == null) {
2276 return null;
2277 }
2278 return r.resultTo;
2279 }
2280
2281 @Override
2282 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002283 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002284
2285 synchronized (mGlobalLock) {
2286 final long origId = Binder.clearCallingIdentity();
2287 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002288 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 } finally {
2290 Binder.restoreCallingIdentity(origId);
2291 }
2292 }
2293 }
2294
Mark Renouf446251d2019-04-26 10:22:41 -04002295 @Override
2296 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2297 synchronized (mGlobalLock) {
2298 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2299 if (r == null) {
2300 return;
2301 }
2302 ActivityStack stack = r.getActivityStack();
2303 if (stack != null && stack.isSingleTaskInstance()) {
2304 // Single-task stacks are used for activities which are presented in floating
2305 // windows above full screen activities. Instead of directly finishing the
2306 // task, a task change listener is used to notify SystemUI so the action can be
2307 // handled specially.
2308 final TaskRecord task = r.getTaskRecord();
2309 mTaskChangeNotificationController
2310 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2311 } else {
2312 try {
2313 callback.requestFinish();
2314 } catch (RemoteException e) {
2315 Slog.e(TAG, "Failed to invoke request finish callback", e);
2316 }
2317 }
2318 }
2319 }
2320
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002321 /**
2322 * TODO: Add mController hook
2323 */
2324 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002325 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2326 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002327 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328
2329 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2330 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002331 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2332 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002333 }
2334 }
2335
Ricky Waiaca8a772019-04-04 16:01:06 +01002336 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2337 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 boolean fromRecents) {
2339
Ricky Waiaca8a772019-04-04 16:01:06 +01002340 final int callingPid = Binder.getCallingPid();
2341 final int callingUid = Binder.getCallingUid();
2342 if (!isSameApp(callingUid, callingPackage)) {
2343 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2344 + Binder.getCallingPid() + " as package " + callingPackage;
2345 Slog.w(TAG, msg);
2346 throw new SecurityException(msg);
2347 }
2348 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002349 SafeActivityOptions.abort(options);
2350 return;
2351 }
2352 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 WindowProcessController callerApp = null;
2354 if (appThread != null) {
2355 callerApp = getProcessController(appThread);
2356 }
2357 final ActivityStarter starter = getActivityStartController().obtainStarter(
2358 null /* intent */, "moveTaskToFront");
2359 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2360 -1, callerApp, null, false, null)) {
2361 boolean abort = !isBackgroundActivityStartsEnabled();
2362 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2363 if (abort) {
2364 return;
2365 }
2366 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002368 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 if (task == null) {
2370 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002371 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 return;
2373 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002374 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002376 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 return;
2378 }
2379 ActivityOptions realOptions = options != null
2380 ? options.getOptions(mStackSupervisor)
2381 : null;
2382 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2383 false /* forceNonResizable */);
2384
2385 final ActivityRecord topActivity = task.getTopActivity();
2386 if (topActivity != null) {
2387
2388 // We are reshowing a task, use a starting window to hide the initial draw delay
2389 // so the transition can start earlier.
2390 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2391 true /* taskSwitch */, fromRecents);
2392 }
2393 } finally {
2394 Binder.restoreCallingIdentity(origId);
2395 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 }
2397
Ricky Waiaca8a772019-04-04 16:01:06 +01002398 /**
2399 * Return true if callingUid is system, or packageName belongs to that callingUid.
2400 */
2401 boolean isSameApp(int callingUid, @Nullable String packageName) {
2402 try {
2403 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2404 if (packageName == null) {
2405 return false;
2406 }
2407 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2408 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2409 UserHandle.getUserId(callingUid));
2410 return UserHandle.isSameApp(callingUid, uid);
2411 }
2412 } catch (RemoteException e) {
2413 // Should not happen
2414 }
2415 return true;
2416 }
2417
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002418 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2419 int callingPid, int callingUid, String name) {
2420 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2421 return true;
2422 }
2423
2424 if (getRecentTasks().isCallerRecents(sourceUid)) {
2425 return true;
2426 }
2427
2428 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2429 if (perm == PackageManager.PERMISSION_GRANTED) {
2430 return true;
2431 }
2432 if (checkAllowAppSwitchUid(sourceUid)) {
2433 return true;
2434 }
2435
2436 // If the actual IPC caller is different from the logical source, then
2437 // also see if they are allowed to control app switches.
2438 if (callingUid != -1 && callingUid != sourceUid) {
2439 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2440 if (perm == PackageManager.PERMISSION_GRANTED) {
2441 return true;
2442 }
2443 if (checkAllowAppSwitchUid(callingUid)) {
2444 return true;
2445 }
2446 }
2447
2448 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2449 return false;
2450 }
2451
2452 private boolean checkAllowAppSwitchUid(int uid) {
2453 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2454 if (types != null) {
2455 for (int i = types.size() - 1; i >= 0; i--) {
2456 if (types.valueAt(i).intValue() == uid) {
2457 return true;
2458 }
2459 }
2460 }
2461 return false;
2462 }
2463
2464 @Override
2465 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2466 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2467 "setActivityController()");
2468 synchronized (mGlobalLock) {
2469 mController = controller;
2470 mControllerIsAMonkey = imAMonkey;
2471 Watchdog.getInstance().setActivityController(controller);
2472 }
2473 }
2474
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002475 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002476 synchronized (mGlobalLock) {
2477 return mController != null && mControllerIsAMonkey;
2478 }
2479 }
2480
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002481 @Override
2482 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2483 synchronized (mGlobalLock) {
2484 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2485 }
2486 }
2487
2488 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002489 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2490 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2491 }
2492
2493 @Override
2494 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2495 @WindowConfiguration.ActivityType int ignoreActivityType,
2496 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2497 final int callingUid = Binder.getCallingUid();
2498 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2499
2500 synchronized (mGlobalLock) {
2501 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2502
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002503 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002505 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002506 ignoreWindowingMode, callingUid, allowed);
2507 }
2508
2509 return list;
2510 }
2511
2512 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002513 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2514 synchronized (mGlobalLock) {
2515 final long origId = Binder.clearCallingIdentity();
2516 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2517 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002518 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 }
2520 Binder.restoreCallingIdentity(origId);
2521 }
2522 }
2523
2524 @Override
2525 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002526 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002527 ActivityStack stack = ActivityRecord.getStackLocked(token);
2528 if (stack != null) {
2529 return stack.willActivityBeVisibleLocked(token);
2530 }
2531 return false;
2532 }
2533 }
2534
2535 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002536 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002537 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002538 synchronized (mGlobalLock) {
2539 final long ident = Binder.clearCallingIdentity();
2540 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002541 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 if (task == null) {
2543 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2544 return;
2545 }
2546
2547 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2548 + " to stackId=" + stackId + " toTop=" + toTop);
2549
Wale Ogunwaled32da472018-11-16 07:19:28 -08002550 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 if (stack == null) {
2552 throw new IllegalStateException(
2553 "moveTaskToStack: No stack for stackId=" + stackId);
2554 }
2555 if (!stack.isActivityTypeStandardOrUndefined()) {
2556 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2557 + taskId + " to stack " + stackId);
2558 }
2559 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002560 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002561 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2562 }
2563 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2564 "moveTaskToStack");
2565 } finally {
2566 Binder.restoreCallingIdentity(ident);
2567 }
2568 }
2569 }
2570
2571 @Override
2572 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2573 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002575
2576 final long ident = Binder.clearCallingIdentity();
2577 try {
2578 synchronized (mGlobalLock) {
2579 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002580 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002581 if (stack == null) {
2582 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2583 return;
2584 }
2585 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2586 throw new IllegalArgumentException("Stack: " + stackId
2587 + " doesn't support animated resize.");
2588 }
2589 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2590 animationDuration, false /* fromFullscreen */);
2591 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002592 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002593 if (stack == null) {
2594 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2595 return;
2596 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002597 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2599 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2600 }
2601 }
2602 } finally {
2603 Binder.restoreCallingIdentity(ident);
2604 }
2605 }
2606
wilsonshih5c4cf522019-01-25 09:03:47 +08002607 @Override
2608 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2609 int animationDuration) {
2610 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2611
2612 final long ident = Binder.clearCallingIdentity();
2613 try {
2614 synchronized (mGlobalLock) {
2615 if (xOffset == 0 && yOffset == 0) {
2616 return;
2617 }
2618 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2619 if (stack == null) {
2620 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2621 return;
2622 }
2623 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2624 throw new IllegalArgumentException("Stack: " + stackId
2625 + " doesn't support animated resize.");
2626 }
2627 final Rect destBounds = new Rect();
2628 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002629 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002630 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2631 return;
2632 }
2633 destBounds.offset(xOffset, yOffset);
2634 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2635 animationDuration, false /* fromFullscreen */);
2636 }
2637 } finally {
2638 Binder.restoreCallingIdentity(ident);
2639 }
2640 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002641 /**
2642 * Moves the specified task to the primary-split-screen stack.
2643 *
2644 * @param taskId Id of task to move.
2645 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2646 * exist already. See
2647 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2648 * and
2649 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2650 * @param toTop If the task and stack should be moved to the top.
2651 * @param animate Whether we should play an animation for the moving the task.
2652 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2653 * stack. Pass {@code null} to use default bounds.
2654 * @param showRecents If the recents activity should be shown on the other side of the task
2655 * going into split-screen mode.
2656 */
2657 @Override
2658 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2659 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002660 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002661 "setTaskWindowingModeSplitScreenPrimary()");
2662 synchronized (mGlobalLock) {
2663 final long ident = Binder.clearCallingIdentity();
2664 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002665 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002666 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002667 if (task == null) {
2668 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2669 return false;
2670 }
2671 if (DEBUG_STACK) Slog.d(TAG_STACK,
2672 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2673 + " to createMode=" + createMode + " toTop=" + toTop);
2674 if (!task.isActivityTypeStandardOrUndefined()) {
2675 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2676 + " non-standard task " + taskId + " to split-screen windowing mode");
2677 }
2678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002679 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 final int windowingMode = task.getWindowingMode();
2681 final ActivityStack stack = task.getStack();
2682 if (toTop) {
2683 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2684 }
2685 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002686 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2687 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002688 return windowingMode != task.getWindowingMode();
2689 } finally {
2690 Binder.restoreCallingIdentity(ident);
2691 }
2692 }
2693 }
2694
2695 /**
2696 * Removes stacks in the input windowing modes from the system if they are of activity type
2697 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2698 */
2699 @Override
2700 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002701 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002702 "removeStacksInWindowingModes()");
2703
2704 synchronized (mGlobalLock) {
2705 final long ident = Binder.clearCallingIdentity();
2706 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002707 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002708 } finally {
2709 Binder.restoreCallingIdentity(ident);
2710 }
2711 }
2712 }
2713
2714 @Override
2715 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002716 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 "removeStacksWithActivityTypes()");
2718
2719 synchronized (mGlobalLock) {
2720 final long ident = Binder.clearCallingIdentity();
2721 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002722 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002728
2729 @Override
2730 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2731 int userId) {
2732 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2734 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002735 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002736 final boolean detailed = checkGetTasksPermission(
2737 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2738 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739 == PackageManager.PERMISSION_GRANTED;
2740
2741 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002742 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 callingUid);
2744 }
2745 }
2746
2747 @Override
2748 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 long ident = Binder.clearCallingIdentity();
2751 try {
2752 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002753 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 }
2755 } finally {
2756 Binder.restoreCallingIdentity(ident);
2757 }
2758 }
2759
2760 @Override
2761 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 long ident = Binder.clearCallingIdentity();
2764 try {
2765 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772
2773 @Override
2774 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 final long callingUid = Binder.getCallingUid();
2777 final long origId = Binder.clearCallingIdentity();
2778 try {
2779 synchronized (mGlobalLock) {
2780 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002781 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2783 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2784 }
2785 } finally {
2786 Binder.restoreCallingIdentity(origId);
2787 }
2788 }
2789
2790 @Override
2791 public void startLockTaskModeByToken(IBinder token) {
2792 synchronized (mGlobalLock) {
2793 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2794 if (r == null) {
2795 return;
2796 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002797 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 }
2799 }
2800
2801 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002802 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 // This makes inner call to look as if it was initiated by system.
2805 long ident = Binder.clearCallingIdentity();
2806 try {
2807 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002808 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002809 MATCH_TASK_IN_STACKS_ONLY);
2810 if (task == null) {
2811 return;
2812 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813
2814 // When starting lock task mode the stack must be in front and focused
2815 task.getStack().moveToFront("startSystemLockTaskMode");
2816 startLockTaskModeLocked(task, true /* isSystemCaller */);
2817 }
2818 } finally {
2819 Binder.restoreCallingIdentity(ident);
2820 }
2821 }
2822
2823 @Override
2824 public void stopLockTaskModeByToken(IBinder token) {
2825 synchronized (mGlobalLock) {
2826 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2827 if (r == null) {
2828 return;
2829 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002830 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002831 }
2832 }
2833
2834 /**
2835 * This API should be called by SystemUI only when user perform certain action to dismiss
2836 * lock task mode. We should only dismiss pinned lock task mode in this case.
2837 */
2838 @Override
2839 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002840 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2842 }
2843
2844 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2845 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2846 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2847 return;
2848 }
2849
Wale Ogunwaled32da472018-11-16 07:19:28 -08002850 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002851 if (stack == null || task != stack.topTask()) {
2852 throw new IllegalArgumentException("Invalid task, not in foreground");
2853 }
2854
2855 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2856 // system or a specific app.
2857 // * System-initiated requests will only start the pinned mode (screen pinning)
2858 // * App-initiated requests
2859 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2860 // - will start the pinned mode, otherwise
2861 final int callingUid = Binder.getCallingUid();
2862 long ident = Binder.clearCallingIdentity();
2863 try {
2864 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002865 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002867 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2874 final int callingUid = Binder.getCallingUid();
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002878 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 }
2880 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2881 // task and jumping straight into a call in the case of emergency call back.
2882 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2883 if (tm != null) {
2884 tm.showInCallScreen(false);
2885 }
2886 } finally {
2887 Binder.restoreCallingIdentity(ident);
2888 }
2889 }
2890
2891 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002892 public void updateLockTaskPackages(int userId, String[] packages) {
2893 final int callingUid = Binder.getCallingUid();
2894 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2895 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2896 "updateLockTaskPackages()");
2897 }
2898 synchronized (this) {
2899 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2900 + Arrays.toString(packages));
2901 getLockTaskController().updateLockTaskPackages(userId, packages);
2902 }
2903 }
2904
2905 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 public boolean isInLockTaskMode() {
2907 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2908 }
2909
2910 @Override
2911 public int getLockTaskModeState() {
2912 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002913 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 }
2915 }
2916
2917 @Override
2918 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2919 synchronized (mGlobalLock) {
2920 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2921 if (r != null) {
2922 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002923 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002925 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 }
2927 }
2928 }
2929
2930 @Override
2931 public Bundle getActivityOptions(IBinder token) {
2932 final long origId = Binder.clearCallingIdentity();
2933 try {
2934 synchronized (mGlobalLock) {
2935 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2936 if (r != null) {
2937 final ActivityOptions activityOptions = r.takeOptionsLocked();
2938 return activityOptions == null ? null : activityOptions.toBundle();
2939 }
2940 return null;
2941 }
2942 } finally {
2943 Binder.restoreCallingIdentity(origId);
2944 }
2945 }
2946
2947 @Override
2948 public List<IBinder> getAppTasks(String callingPackage) {
2949 int callingUid = Binder.getCallingUid();
2950 long ident = Binder.clearCallingIdentity();
2951 try {
2952 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002953 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 }
2955 } finally {
2956 Binder.restoreCallingIdentity(ident);
2957 }
2958 }
2959
2960 @Override
2961 public void finishVoiceTask(IVoiceInteractionSession session) {
2962 synchronized (mGlobalLock) {
2963 final long origId = Binder.clearCallingIdentity();
2964 try {
2965 // TODO: VI Consider treating local voice interactions and voice tasks
2966 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002967 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 } finally {
2969 Binder.restoreCallingIdentity(origId);
2970 }
2971 }
2972
2973 }
2974
2975 @Override
2976 public boolean isTopOfTask(IBinder token) {
2977 synchronized (mGlobalLock) {
2978 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002979 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 }
2981 }
2982
2983 @Override
2984 public void notifyLaunchTaskBehindComplete(IBinder token) {
2985 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2986 }
2987
2988 @Override
2989 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002990 mH.post(() -> {
2991 synchronized (mGlobalLock) {
2992 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002993 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002994 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002995 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002996 } catch (RemoteException e) {
2997 }
2998 }
2999 }
3000
3001 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003002 }
3003
3004 /** Called from an app when assist data is ready. */
3005 @Override
3006 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3007 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003008 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 synchronized (pae) {
3010 pae.result = extras;
3011 pae.structure = structure;
3012 pae.content = content;
3013 if (referrer != null) {
3014 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3015 }
3016 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003017 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003018 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3019 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 structure.setHomeActivity(pae.isHome);
3021 }
3022 pae.haveResult = true;
3023 pae.notifyAll();
3024 if (pae.intent == null && pae.receiver == null) {
3025 // Caller is just waiting for the result.
3026 return;
3027 }
3028 }
3029 // We are now ready to launch the assist activity.
3030 IAssistDataReceiver sendReceiver = null;
3031 Bundle sendBundle = null;
3032 synchronized (mGlobalLock) {
3033 buildAssistBundleLocked(pae, extras);
3034 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003035 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 if (!exists) {
3037 // Timed out.
3038 return;
3039 }
3040
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003041 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 // Caller wants result sent back to them.
3043 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003044 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3045 pae.activity.getTaskRecord().taskId);
3046 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3047 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3049 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3050 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3051 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3052 }
3053 }
3054 if (sendReceiver != null) {
3055 try {
3056 sendReceiver.onHandleAssistData(sendBundle);
3057 } catch (RemoteException e) {
3058 }
3059 return;
3060 }
3061
3062 final long ident = Binder.clearCallingIdentity();
3063 try {
3064 if (TextUtils.equals(pae.intent.getAction(),
3065 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3066 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003067
3068 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 } else {
3070 pae.intent.replaceExtras(pae.extras);
3071 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3072 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3073 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003074 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075
3076 try {
3077 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3078 } catch (ActivityNotFoundException e) {
3079 Slog.w(TAG, "No activity to handle assist action.", e);
3080 }
3081 }
3082 } finally {
3083 Binder.restoreCallingIdentity(ident);
3084 }
3085 }
3086
Marvin Ramin830d4e32019-03-12 13:16:58 +01003087 /**
3088 * Workaround for historical API which starts the Assist service with a non-foreground
3089 * {@code startService()} call.
3090 */
3091 private void startVoiceInteractionServiceAsUser(
3092 Intent intent, int userHandle, String reason) {
3093 // Resolve the intent to find out which package we need to whitelist.
3094 ResolveInfo resolveInfo =
3095 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3096 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3097 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3098 return;
3099 }
3100 intent.setPackage(resolveInfo.serviceInfo.packageName);
3101
3102 // Whitelist background services temporarily.
3103 LocalServices.getService(DeviceIdleController.LocalService.class)
3104 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3105 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3106
3107 // Finally, try to start the service.
3108 try {
3109 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3110 } catch (RuntimeException e) {
3111 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3112 }
3113 }
3114
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 @Override
3116 public int addAppTask(IBinder activityToken, Intent intent,
3117 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3118 final int callingUid = Binder.getCallingUid();
3119 final long callingIdent = Binder.clearCallingIdentity();
3120
3121 try {
3122 synchronized (mGlobalLock) {
3123 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3124 if (r == null) {
3125 throw new IllegalArgumentException("Activity does not exist; token="
3126 + activityToken);
3127 }
3128 ComponentName comp = intent.getComponent();
3129 if (comp == null) {
3130 throw new IllegalArgumentException("Intent " + intent
3131 + " must specify explicit component");
3132 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003133 if (thumbnail.getWidth() != mThumbnailWidth
3134 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 throw new IllegalArgumentException("Bad thumbnail size: got "
3136 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003137 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 }
3139 if (intent.getSelector() != null) {
3140 intent.setSelector(null);
3141 }
3142 if (intent.getSourceBounds() != null) {
3143 intent.setSourceBounds(null);
3144 }
3145 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3146 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3147 // The caller has added this as an auto-remove task... that makes no
3148 // sense, so turn off auto-remove.
3149 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3150 }
3151 }
3152 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3153 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3154 if (ainfo.applicationInfo.uid != callingUid) {
3155 throw new SecurityException(
3156 "Can't add task for another application: target uid="
3157 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3158 }
3159
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003160 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003162 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003164 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 // The app has too many tasks already and we can't add any more
3166 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3167 return INVALID_TASK_ID;
3168 }
3169 task.lastTaskDescription.copyFrom(description);
3170
3171 // TODO: Send the thumbnail to WM to store it.
3172
3173 return task.taskId;
3174 }
3175 } finally {
3176 Binder.restoreCallingIdentity(callingIdent);
3177 }
3178 }
3179
3180 @Override
3181 public Point getAppTaskThumbnailSize() {
3182 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003183 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 }
3185 }
3186
3187 @Override
3188 public void setTaskResizeable(int taskId, int resizeableMode) {
3189 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003190 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3192 if (task == null) {
3193 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3194 return;
3195 }
3196 task.setResizeMode(resizeableMode);
3197 }
3198 }
3199
3200 @Override
3201 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003202 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 long ident = Binder.clearCallingIdentity();
3204 try {
3205 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003206 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003207 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 if (task == null) {
3209 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3210 return;
3211 }
3212 // Place the task in the right stack if it isn't there already based on
3213 // the requested bounds.
3214 // The stack transition logic is:
3215 // - a null bounds on a freeform task moves that task to fullscreen
3216 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3217 // that task to freeform
3218 // - otherwise the task is not moved
3219 ActivityStack stack = task.getStack();
3220 if (!task.getWindowConfiguration().canResizeTask()) {
3221 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3222 }
3223 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3224 stack = stack.getDisplay().getOrCreateStack(
3225 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3226 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3227 stack = stack.getDisplay().getOrCreateStack(
3228 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3229 }
3230
3231 // Reparent the task to the right stack if necessary
3232 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3233 if (stack != task.getStack()) {
3234 // Defer resume until the task is resized below
3235 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3236 DEFER_RESUME, "resizeTask");
3237 preserveWindow = false;
3238 }
3239
3240 // After reparenting (which only resizes the task to the stack bounds), resize the
3241 // task to the actual bounds provided
3242 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3243 }
3244 } finally {
3245 Binder.restoreCallingIdentity(ident);
3246 }
3247 }
3248
3249 @Override
3250 public boolean releaseActivityInstance(IBinder token) {
3251 synchronized (mGlobalLock) {
3252 final long origId = Binder.clearCallingIdentity();
3253 try {
3254 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3255 if (r == null) {
3256 return false;
3257 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003258 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 } finally {
3260 Binder.restoreCallingIdentity(origId);
3261 }
3262 }
3263 }
3264
3265 @Override
3266 public void releaseSomeActivities(IApplicationThread appInt) {
3267 synchronized (mGlobalLock) {
3268 final long origId = Binder.clearCallingIdentity();
3269 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003270 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003271 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 } finally {
3273 Binder.restoreCallingIdentity(origId);
3274 }
3275 }
3276 }
3277
3278 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003279 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 != PackageManager.PERMISSION_GRANTED) {
3282 throw new SecurityException("Requires permission "
3283 + android.Manifest.permission.DEVICE_POWER);
3284 }
3285
3286 synchronized (mGlobalLock) {
3287 long ident = Binder.clearCallingIdentity();
3288 if (mKeyguardShown != keyguardShowing) {
3289 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003290 final Message msg = PooledLambda.obtainMessage(
3291 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3292 keyguardShowing);
3293 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003294 }
3295 try {
wilsonshih177261f2019-02-22 12:02:18 +08003296 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 } finally {
3298 Binder.restoreCallingIdentity(ident);
3299 }
3300 }
3301
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003302 mH.post(() -> {
3303 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3304 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3305 }
3306 });
3307 }
3308
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003309 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003310 mH.post(() -> {
3311 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3312 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3313 }
3314 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 }
3316
3317 @Override
3318 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003319 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3320 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321
3322 final File passedIconFile = new File(filePath);
3323 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3324 passedIconFile.getName());
3325 if (!legitIconFile.getPath().equals(filePath)
3326 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3327 throw new IllegalArgumentException("Bad file path: " + filePath
3328 + " passed for userId " + userId);
3329 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003330 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 }
3332
3333 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003334 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3336 final ActivityOptions activityOptions = safeOptions != null
3337 ? safeOptions.getOptions(mStackSupervisor)
3338 : null;
3339 if (activityOptions == null
3340 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3341 || activityOptions.getCustomInPlaceResId() == 0) {
3342 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3343 "with valid animation");
3344 }
lumark588a3e82018-07-20 18:53:54 +08003345 // Get top display of front most application.
3346 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3347 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003348 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3349 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3350 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003351 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003352 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003353 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 }
3355
3356 @Override
3357 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003358 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 synchronized (mGlobalLock) {
3360 final long ident = Binder.clearCallingIdentity();
3361 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003362 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363 if (stack == null) {
3364 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3365 return;
3366 }
3367 if (!stack.isActivityTypeStandardOrUndefined()) {
3368 throw new IllegalArgumentException(
3369 "Removing non-standard stack is not allowed.");
3370 }
3371 mStackSupervisor.removeStack(stack);
3372 } finally {
3373 Binder.restoreCallingIdentity(ident);
3374 }
3375 }
3376 }
3377
3378 @Override
3379 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003380 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381
3382 synchronized (mGlobalLock) {
3383 final long ident = Binder.clearCallingIdentity();
3384 try {
3385 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3386 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003387 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 } finally {
3389 Binder.restoreCallingIdentity(ident);
3390 }
3391 }
3392 }
3393
3394 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003395 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 synchronized (mGlobalLock) {
3397 long ident = Binder.clearCallingIdentity();
3398 try {
3399 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3400 if (r == null) {
3401 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003402 "toggleFreeformWindowingMode: No activity record matching token="
3403 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 }
3405
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003406 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003407 if (stack == null) {
3408 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3409 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 }
3411
Yunfan Chend967af82019-01-17 18:30:18 +09003412 if (!stack.inFreeformWindowingMode()
3413 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3414 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3415 + "toggle between fullscreen and freeform.");
3416 }
3417
3418 if (stack.inFreeformWindowingMode()) {
3419 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003420 } else if (stack.getParent().inFreeformWindowingMode()) {
3421 // If the window is on a freeform display, set it to undefined. It will be
3422 // resolved to freeform and it can adjust windowing mode when the display mode
3423 // changes in runtime.
3424 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003425 } else {
3426 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3427 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 } finally {
3429 Binder.restoreCallingIdentity(ident);
3430 }
3431 }
3432 }
3433
3434 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3435 @Override
3436 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003439 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 }
3441
3442 /** Unregister a task stack listener so that it stops receiving callbacks. */
3443 @Override
3444 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003445 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003447 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003448 }
3449
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 @Override
3451 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3452 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3453 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3454 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3455 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3456 }
3457
3458 @Override
3459 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3460 IBinder activityToken, int flags) {
3461 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3462 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3463 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3464 }
3465
3466 @Override
3467 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3468 Bundle args) {
3469 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3470 true /* focused */, true /* newSessionId */, userHandle, args,
3471 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3472 }
3473
3474 @Override
3475 public Bundle getAssistContextExtras(int requestType) {
3476 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3477 null, null, true /* focused */, true /* newSessionId */,
3478 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3479 if (pae == null) {
3480 return null;
3481 }
3482 synchronized (pae) {
3483 while (!pae.haveResult) {
3484 try {
3485 pae.wait();
3486 } catch (InterruptedException e) {
3487 }
3488 }
3489 }
3490 synchronized (mGlobalLock) {
3491 buildAssistBundleLocked(pae, pae.result);
3492 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003493 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003494 }
3495 return pae.extras;
3496 }
3497
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003498 /**
3499 * Binder IPC calls go through the public entry point.
3500 * This can be called with or without the global lock held.
3501 */
3502 private static int checkCallingPermission(String permission) {
3503 return checkPermission(
3504 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3505 }
3506
3507 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003508 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003509 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3510 mAmInternal.enforceCallingPermission(permission, func);
3511 }
3512 }
3513
3514 @VisibleForTesting
3515 int checkGetTasksPermission(String permission, int pid, int uid) {
3516 return checkPermission(permission, pid, uid);
3517 }
3518
3519 static int checkPermission(String permission, int pid, int uid) {
3520 if (permission == null) {
3521 return PackageManager.PERMISSION_DENIED;
3522 }
3523 return checkComponentPermission(permission, pid, uid, -1, true);
3524 }
3525
Wale Ogunwale214f3482018-10-04 11:00:47 -07003526 public static int checkComponentPermission(String permission, int pid, int uid,
3527 int owningUid, boolean exported) {
3528 return ActivityManagerService.checkComponentPermission(
3529 permission, pid, uid, owningUid, exported);
3530 }
3531
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003532 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3533 if (getRecentTasks().isCallerRecents(callingUid)) {
3534 // Always allow the recents component to get tasks
3535 return true;
3536 }
3537
3538 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3539 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3540 if (!allowed) {
3541 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3542 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3543 // Temporary compatibility: some existing apps on the system image may
3544 // still be requesting the old permission and not switched to the new
3545 // one; if so, we'll still allow them full access. This means we need
3546 // to see if they are holding the old permission and are a system app.
3547 try {
3548 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3549 allowed = true;
3550 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3551 + " is using old GET_TASKS but privileged; allowing");
3552 }
3553 } catch (RemoteException e) {
3554 }
3555 }
3556 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3557 + " does not hold REAL_GET_TASKS; limiting output");
3558 }
3559 return allowed;
3560 }
3561
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3563 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3564 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3565 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003566 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003567 "enqueueAssistContext()");
3568
3569 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003570 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 if (activity == null) {
3572 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3573 return null;
3574 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003575 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003576 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3577 return null;
3578 }
3579 if (focused) {
3580 if (activityToken != null) {
3581 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3582 if (activity != caller) {
3583 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3584 + " is not current top " + activity);
3585 return null;
3586 }
3587 }
3588 } else {
3589 activity = ActivityRecord.forTokenLocked(activityToken);
3590 if (activity == null) {
3591 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3592 + " couldn't be found");
3593 return null;
3594 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003595 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003596 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3597 return null;
3598 }
3599 }
3600
3601 PendingAssistExtras pae;
3602 Bundle extras = new Bundle();
3603 if (args != null) {
3604 extras.putAll(args);
3605 }
3606 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608
3609 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3610 userHandle);
3611 pae.isHome = activity.isActivityTypeHome();
3612
3613 // Increment the sessionId if necessary
3614 if (newSessionId) {
3615 mViSessionId++;
3616 }
3617 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003618 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3619 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003621 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 } catch (RemoteException e) {
3623 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3624 return null;
3625 }
3626 return pae;
3627 }
3628 }
3629
3630 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3631 if (result != null) {
3632 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3633 }
3634 if (pae.hint != null) {
3635 pae.extras.putBoolean(pae.hint, true);
3636 }
3637 }
3638
3639 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3640 IAssistDataReceiver receiver;
3641 synchronized (mGlobalLock) {
3642 mPendingAssistExtras.remove(pae);
3643 receiver = pae.receiver;
3644 }
3645 if (receiver != null) {
3646 // Caller wants result sent back to them.
3647 Bundle sendBundle = new Bundle();
3648 // At least return the receiver extras
3649 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3650 try {
3651 pae.receiver.onHandleAssistData(sendBundle);
3652 } catch (RemoteException e) {
3653 }
3654 }
3655 }
3656
3657 public class PendingAssistExtras extends Binder implements Runnable {
3658 public final ActivityRecord activity;
3659 public boolean isHome;
3660 public final Bundle extras;
3661 public final Intent intent;
3662 public final String hint;
3663 public final IAssistDataReceiver receiver;
3664 public final int userHandle;
3665 public boolean haveResult = false;
3666 public Bundle result = null;
3667 public AssistStructure structure = null;
3668 public AssistContent content = null;
3669 public Bundle receiverExtras;
3670
3671 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3672 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3673 int _userHandle) {
3674 activity = _activity;
3675 extras = _extras;
3676 intent = _intent;
3677 hint = _hint;
3678 receiver = _receiver;
3679 receiverExtras = _receiverExtras;
3680 userHandle = _userHandle;
3681 }
3682
3683 @Override
3684 public void run() {
3685 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3686 synchronized (this) {
3687 haveResult = true;
3688 notifyAll();
3689 }
3690 pendingAssistExtrasTimedOut(this);
3691 }
3692 }
3693
3694 @Override
3695 public boolean isAssistDataAllowedOnCurrentActivity() {
3696 int userId;
3697 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003698 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003699 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3700 return false;
3701 }
3702
3703 final ActivityRecord activity = focusedStack.getTopActivity();
3704 if (activity == null) {
3705 return false;
3706 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003707 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 }
3709 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3710 }
3711
3712 @Override
3713 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3714 long ident = Binder.clearCallingIdentity();
3715 try {
3716 synchronized (mGlobalLock) {
3717 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003718 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003719 if (top != caller) {
3720 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3721 + " is not current top " + top);
3722 return false;
3723 }
3724 if (!top.nowVisible) {
3725 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3726 + " is not visible");
3727 return false;
3728 }
3729 }
3730 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3731 token);
3732 } finally {
3733 Binder.restoreCallingIdentity(ident);
3734 }
3735 }
3736
3737 @Override
3738 public boolean isRootVoiceInteraction(IBinder token) {
3739 synchronized (mGlobalLock) {
3740 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3741 if (r == null) {
3742 return false;
3743 }
3744 return r.rootVoiceInteraction;
3745 }
3746 }
3747
Wale Ogunwalef6733932018-06-27 05:14:34 -07003748 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3749 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3750 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3751 if (activityToCallback == null) return;
3752 activityToCallback.setVoiceSessionLocked(voiceSession);
3753
3754 // Inform the activity
3755 try {
3756 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3757 voiceInteractor);
3758 long token = Binder.clearCallingIdentity();
3759 try {
3760 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3761 } finally {
3762 Binder.restoreCallingIdentity(token);
3763 }
3764 // TODO: VI Should we cache the activity so that it's easier to find later
3765 // rather than scan through all the stacks and activities?
3766 } catch (RemoteException re) {
3767 activityToCallback.clearVoiceSessionLocked();
3768 // TODO: VI Should this terminate the voice session?
3769 }
3770 }
3771
3772 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3773 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3774 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3775 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3776 boolean wasRunningVoice = mRunningVoice != null;
3777 mRunningVoice = session;
3778 if (!wasRunningVoice) {
3779 mVoiceWakeLock.acquire();
3780 updateSleepIfNeededLocked();
3781 }
3782 }
3783 }
3784
3785 void finishRunningVoiceLocked() {
3786 if (mRunningVoice != null) {
3787 mRunningVoice = null;
3788 mVoiceWakeLock.release();
3789 updateSleepIfNeededLocked();
3790 }
3791 }
3792
3793 @Override
3794 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3795 synchronized (mGlobalLock) {
3796 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3797 if (keepAwake) {
3798 mVoiceWakeLock.acquire();
3799 } else {
3800 mVoiceWakeLock.release();
3801 }
3802 }
3803 }
3804 }
3805
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 @Override
3807 public ComponentName getActivityClassForToken(IBinder token) {
3808 synchronized (mGlobalLock) {
3809 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3810 if (r == null) {
3811 return null;
3812 }
3813 return r.intent.getComponent();
3814 }
3815 }
3816
3817 @Override
3818 public String getPackageForToken(IBinder token) {
3819 synchronized (mGlobalLock) {
3820 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3821 if (r == null) {
3822 return null;
3823 }
3824 return r.packageName;
3825 }
3826 }
3827
3828 @Override
3829 public void showLockTaskEscapeMessage(IBinder token) {
3830 synchronized (mGlobalLock) {
3831 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3832 if (r == null) {
3833 return;
3834 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003835 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 }
3837 }
3838
3839 @Override
3840 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003841 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842 final long token = Binder.clearCallingIdentity();
3843 try {
3844 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003845 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 }
3847 } finally {
3848 Binder.restoreCallingIdentity(token);
3849 }
3850 }
3851
3852 /**
3853 * Try to place task to provided position. The final position might be different depending on
3854 * current user and stacks state. The task will be moved to target stack if it's currently in
3855 * different stack.
3856 */
3857 @Override
3858 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003859 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003860 synchronized (mGlobalLock) {
3861 long ident = Binder.clearCallingIdentity();
3862 try {
3863 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3864 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003865 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003866 if (task == null) {
3867 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3868 + taskId);
3869 }
3870
Wale Ogunwaled32da472018-11-16 07:19:28 -08003871 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872
3873 if (stack == null) {
3874 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3875 + stackId);
3876 }
3877 if (!stack.isActivityTypeStandardOrUndefined()) {
3878 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3879 + " the position of task " + taskId + " in/to non-standard stack");
3880 }
3881
3882 // TODO: Have the callers of this API call a separate reparent method if that is
3883 // what they intended to do vs. having this method also do reparenting.
3884 if (task.getStack() == stack) {
3885 // Change position in current stack.
3886 stack.positionChildAt(task, position);
3887 } else {
3888 // Reparent to new stack.
3889 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3890 !DEFER_RESUME, "positionTaskInStack");
3891 }
3892 } finally {
3893 Binder.restoreCallingIdentity(ident);
3894 }
3895 }
3896 }
3897
3898 @Override
3899 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3900 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3901 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3902 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3903 synchronized (mGlobalLock) {
3904 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3905 if (record == null) {
3906 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3907 + "found for: " + token);
3908 }
3909 record.setSizeConfigurations(horizontalSizeConfiguration,
3910 verticalSizeConfigurations, smallestSizeConfigurations);
3911 }
3912 }
3913
3914 /**
3915 * Dismisses split-screen multi-window mode.
3916 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3917 */
3918 @Override
3919 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003920 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3922 final long ident = Binder.clearCallingIdentity();
3923 try {
3924 synchronized (mGlobalLock) {
3925 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003926 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 if (stack == null) {
3928 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3929 return;
3930 }
3931
3932 if (toTop) {
3933 // Caller wants the current split-screen primary stack to be the top stack after
3934 // it goes fullscreen, so move it to the front.
3935 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003936 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003937 // In this case the current split-screen primary stack shouldn't be the top
3938 // stack after it goes fullscreen, but it current has focus, so we move the
3939 // focus to the top-most split-screen secondary stack next to it.
3940 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3941 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3942 if (otherStack != null) {
3943 otherStack.moveToFront("dismissSplitScreenMode_other");
3944 }
3945 }
3946
Evan Rosky10475742018-09-05 19:02:48 -07003947 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 }
3949 } finally {
3950 Binder.restoreCallingIdentity(ident);
3951 }
3952 }
3953
3954 /**
3955 * Dismisses Pip
3956 * @param animate True if the dismissal should be animated.
3957 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3958 * default animation duration should be used.
3959 */
3960 @Override
3961 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003962 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 final long ident = Binder.clearCallingIdentity();
3964 try {
3965 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003966 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003967 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003968 if (stack == null) {
3969 Slog.w(TAG, "dismissPip: pinned stack not found.");
3970 return;
3971 }
3972 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3973 throw new IllegalArgumentException("Stack: " + stack
3974 + " doesn't support animated resize.");
3975 }
3976 if (animate) {
3977 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3978 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3979 } else {
3980 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3981 }
3982 }
3983 } finally {
3984 Binder.restoreCallingIdentity(ident);
3985 }
3986 }
3987
3988 @Override
3989 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003990 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 synchronized (mGlobalLock) {
3992 mSuppressResizeConfigChanges = suppress;
3993 }
3994 }
3995
3996 /**
3997 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3998 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3999 * activity and clearing the task at the same time.
4000 */
4001 @Override
4002 // TODO: API should just be about changing windowing modes...
4003 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 "moveTasksToFullscreenStack()");
4006 synchronized (mGlobalLock) {
4007 final long origId = Binder.clearCallingIdentity();
4008 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004009 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 if (stack != null){
4011 if (!stack.isActivityTypeStandardOrUndefined()) {
4012 throw new IllegalArgumentException(
4013 "You can't move tasks from non-standard stacks.");
4014 }
4015 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4016 }
4017 } finally {
4018 Binder.restoreCallingIdentity(origId);
4019 }
4020 }
4021 }
4022
4023 /**
4024 * Moves the top activity in the input stackId to the pinned stack.
4025 *
4026 * @param stackId Id of stack to move the top activity to pinned stack.
4027 * @param bounds Bounds to use for pinned stack.
4028 *
4029 * @return True if the top activity of the input stack was successfully moved to the pinned
4030 * stack.
4031 */
4032 @Override
4033 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 "moveTopActivityToPinnedStack()");
4036 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4039 + "Device doesn't support picture-in-picture mode");
4040 }
4041
4042 long ident = Binder.clearCallingIdentity();
4043 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004044 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 } finally {
4046 Binder.restoreCallingIdentity(ident);
4047 }
4048 }
4049 }
4050
4051 @Override
4052 public boolean isInMultiWindowMode(IBinder token) {
4053 final long origId = Binder.clearCallingIdentity();
4054 try {
4055 synchronized (mGlobalLock) {
4056 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4057 if (r == null) {
4058 return false;
4059 }
4060 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4061 return r.inMultiWindowMode();
4062 }
4063 } finally {
4064 Binder.restoreCallingIdentity(origId);
4065 }
4066 }
4067
4068 @Override
4069 public boolean isInPictureInPictureMode(IBinder token) {
4070 final long origId = Binder.clearCallingIdentity();
4071 try {
4072 synchronized (mGlobalLock) {
4073 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4074 }
4075 } finally {
4076 Binder.restoreCallingIdentity(origId);
4077 }
4078 }
4079
4080 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004081 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4082 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 return false;
4084 }
4085
4086 // If we are animating to fullscreen then we have already dispatched the PIP mode
4087 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004088 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4089 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 }
4091
4092 @Override
4093 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4094 final long origId = Binder.clearCallingIdentity();
4095 try {
4096 synchronized (mGlobalLock) {
4097 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4098 "enterPictureInPictureMode", token, params);
4099
4100 // If the activity is already in picture in picture mode, then just return early
4101 if (isInPictureInPictureMode(r)) {
4102 return true;
4103 }
4104
4105 // Activity supports picture-in-picture, now check that we can enter PiP at this
4106 // point, if it is
4107 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4108 false /* beforeStopping */)) {
4109 return false;
4110 }
4111
4112 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004113 synchronized (mGlobalLock) {
4114 // Only update the saved args from the args that are set
4115 r.pictureInPictureArgs.copyOnlySet(params);
4116 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4117 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4118 // Adjust the source bounds by the insets for the transition down
4119 final Rect sourceBounds = new Rect(
4120 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004121 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004122 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004123 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004124 stack.setPictureInPictureAspectRatio(aspectRatio);
4125 stack.setPictureInPictureActions(actions);
4126 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4127 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4128 logPictureInPictureArgs(params);
4129 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 };
4131
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004132 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 // If the keyguard is showing or occluded, then try and dismiss it before
4134 // entering picture-in-picture (this will prompt the user to authenticate if the
4135 // device is currently locked).
4136 dismissKeyguard(token, new KeyguardDismissCallback() {
4137 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004138 public void onDismissSucceeded() {
4139 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 }
4141 }, null /* message */);
4142 } else {
4143 // Enter picture in picture immediately otherwise
4144 enterPipRunnable.run();
4145 }
4146 return true;
4147 }
4148 } finally {
4149 Binder.restoreCallingIdentity(origId);
4150 }
4151 }
4152
4153 @Override
4154 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4155 final long origId = Binder.clearCallingIdentity();
4156 try {
4157 synchronized (mGlobalLock) {
4158 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4159 "setPictureInPictureParams", token, params);
4160
4161 // Only update the saved args from the args that are set
4162 r.pictureInPictureArgs.copyOnlySet(params);
4163 if (r.inPinnedWindowingMode()) {
4164 // If the activity is already in picture-in-picture, update the pinned stack now
4165 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4166 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004167 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 if (!stack.isAnimatingBoundsToFullscreen()) {
4169 stack.setPictureInPictureAspectRatio(
4170 r.pictureInPictureArgs.getAspectRatio());
4171 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4172 }
4173 }
4174 logPictureInPictureArgs(params);
4175 }
4176 } finally {
4177 Binder.restoreCallingIdentity(origId);
4178 }
4179 }
4180
4181 @Override
4182 public int getMaxNumPictureInPictureActions(IBinder token) {
4183 // Currently, this is a static constant, but later, we may change this to be dependent on
4184 // the context of the activity
4185 return 3;
4186 }
4187
4188 private void logPictureInPictureArgs(PictureInPictureParams params) {
4189 if (params.hasSetActions()) {
4190 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4191 params.getActions().size());
4192 }
4193 if (params.hasSetAspectRatio()) {
4194 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4195 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4196 MetricsLogger.action(lm);
4197 }
4198 }
4199
4200 /**
4201 * Checks the state of the system and the activity associated with the given {@param token} to
4202 * verify that picture-in-picture is supported for that activity.
4203 *
4204 * @return the activity record for the given {@param token} if all the checks pass.
4205 */
4206 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4207 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 throw new IllegalStateException(caller
4210 + ": Device doesn't support picture-in-picture mode.");
4211 }
4212
4213 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4214 if (r == null) {
4215 throw new IllegalStateException(caller
4216 + ": Can't find activity for token=" + token);
4217 }
4218
4219 if (!r.supportsPictureInPicture()) {
4220 throw new IllegalStateException(caller
4221 + ": Current activity does not support picture-in-picture.");
4222 }
4223
4224 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004225 && !mWindowManager.isValidPictureInPictureAspectRatio(
4226 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 final float minAspectRatio = mContext.getResources().getFloat(
4228 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4229 final float maxAspectRatio = mContext.getResources().getFloat(
4230 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4231 throw new IllegalArgumentException(String.format(caller
4232 + ": Aspect ratio is too extreme (must be between %f and %f).",
4233 minAspectRatio, maxAspectRatio));
4234 }
4235
4236 // Truncate the number of actions if necessary
4237 params.truncateActions(getMaxNumPictureInPictureActions(token));
4238
4239 return r;
4240 }
4241
4242 @Override
4243 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 synchronized (mGlobalLock) {
4246 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4247 if (r == null) {
4248 throw new IllegalArgumentException("Activity does not exist; token="
4249 + activityToken);
4250 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004251 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 }
4253 }
4254
4255 @Override
4256 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4257 Rect tempDockedTaskInsetBounds,
4258 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004259 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004260 long ident = Binder.clearCallingIdentity();
4261 try {
4262 synchronized (mGlobalLock) {
4263 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4264 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4265 PRESERVE_WINDOWS);
4266 }
4267 } finally {
4268 Binder.restoreCallingIdentity(ident);
4269 }
4270 }
4271
4272 @Override
4273 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004274 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 final long ident = Binder.clearCallingIdentity();
4276 try {
4277 synchronized (mGlobalLock) {
4278 mStackSupervisor.setSplitScreenResizing(resizing);
4279 }
4280 } finally {
4281 Binder.restoreCallingIdentity(ident);
4282 }
4283 }
4284
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004285 /**
4286 * Check that we have the features required for VR-related API calls, and throw an exception if
4287 * not.
4288 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004289 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004290 if (!mContext.getPackageManager().hasSystemFeature(
4291 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4292 throw new UnsupportedOperationException("VR mode not supported on this device!");
4293 }
4294 }
4295
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 @Override
4297 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004298 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299
4300 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4301
4302 ActivityRecord r;
4303 synchronized (mGlobalLock) {
4304 r = ActivityRecord.isInStackLocked(token);
4305 }
4306
4307 if (r == null) {
4308 throw new IllegalArgumentException();
4309 }
4310
4311 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004312 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 VrManagerInternal.NO_ERROR) {
4314 return err;
4315 }
4316
4317 // Clear the binder calling uid since this path may call moveToTask().
4318 final long callingId = Binder.clearCallingIdentity();
4319 try {
4320 synchronized (mGlobalLock) {
4321 r.requestedVrComponent = (enabled) ? packageName : null;
4322
4323 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004324 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004325 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004326 }
4327 return 0;
4328 }
4329 } finally {
4330 Binder.restoreCallingIdentity(callingId);
4331 }
4332 }
4333
4334 @Override
4335 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4336 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4337 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004338 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4340 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4341 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004342 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 || activity.voiceSession != null) {
4344 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4345 return;
4346 }
4347 if (activity.pendingVoiceInteractionStart) {
4348 Slog.w(TAG, "Pending start of voice interaction already.");
4349 return;
4350 }
4351 activity.pendingVoiceInteractionStart = true;
4352 }
4353 LocalServices.getService(VoiceInteractionManagerInternal.class)
4354 .startLocalVoiceInteraction(callingActivity, options);
4355 }
4356
4357 @Override
4358 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4359 LocalServices.getService(VoiceInteractionManagerInternal.class)
4360 .stopLocalVoiceInteraction(callingActivity);
4361 }
4362
4363 @Override
4364 public boolean supportsLocalVoiceInteraction() {
4365 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4366 .supportsLocalVoiceInteraction();
4367 }
4368
4369 /** Notifies all listeners when the pinned stack animation starts. */
4370 @Override
4371 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374
4375 /** Notifies all listeners when the pinned stack animation ends. */
4376 @Override
4377 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380
4381 @Override
4382 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004383 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 final long ident = Binder.clearCallingIdentity();
4385 try {
4386 synchronized (mGlobalLock) {
4387 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4388 }
4389 } finally {
4390 Binder.restoreCallingIdentity(ident);
4391 }
4392 }
4393
4394 @Override
4395 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004396 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397
4398 synchronized (mGlobalLock) {
4399 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004400 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 // Call might come when display is not yet added or has already been removed.
4402 if (DEBUG_CONFIGURATION) {
4403 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4404 + displayId);
4405 }
4406 return false;
4407 }
4408
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004409 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 }
4413
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004415 final Message msg = PooledLambda.obtainMessage(
4416 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4417 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 }
4419
4420 final long origId = Binder.clearCallingIdentity();
4421 try {
4422 if (values != null) {
4423 Settings.System.clearConfiguration(values);
4424 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4427 return mTmpUpdateConfigurationResult.changes != 0;
4428 } finally {
4429 Binder.restoreCallingIdentity(origId);
4430 }
4431 }
4432 }
4433
4434 @Override
4435 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004436 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437
4438 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 }
4443
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004445 final Message msg = PooledLambda.obtainMessage(
4446 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4447 DEFAULT_DISPLAY);
4448 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449 }
4450
4451 final long origId = Binder.clearCallingIdentity();
4452 try {
4453 if (values != null) {
4454 Settings.System.clearConfiguration(values);
4455 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 UserHandle.USER_NULL, false /* deferResume */,
4458 mTmpUpdateConfigurationResult);
4459 return mTmpUpdateConfigurationResult.changes != 0;
4460 } finally {
4461 Binder.restoreCallingIdentity(origId);
4462 }
4463 }
4464 }
4465
4466 @Override
4467 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4468 CharSequence message) {
4469 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004470 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004471 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4472 }
4473 final long callingId = Binder.clearCallingIdentity();
4474 try {
4475 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004476 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 }
4478 } finally {
4479 Binder.restoreCallingIdentity(callingId);
4480 }
4481 }
4482
4483 @Override
4484 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004485 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 "cancelTaskWindowTransition()");
4487 final long ident = Binder.clearCallingIdentity();
4488 try {
4489 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004490 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 MATCH_TASK_IN_STACKS_ONLY);
4492 if (task == null) {
4493 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4494 return;
4495 }
4496 task.cancelWindowTransition();
4497 }
4498 } finally {
4499 Binder.restoreCallingIdentity(ident);
4500 }
4501 }
4502
4503 @Override
4504 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004505 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 final long ident = Binder.clearCallingIdentity();
4507 try {
4508 final TaskRecord task;
4509 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004510 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4512 if (task == null) {
4513 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4514 return null;
4515 }
4516 }
4517 // Don't call this while holding the lock as this operation might hit the disk.
4518 return task.getSnapshot(reducedResolution);
4519 } finally {
4520 Binder.restoreCallingIdentity(ident);
4521 }
4522 }
4523
4524 @Override
4525 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4526 synchronized (mGlobalLock) {
4527 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4528 if (r == null) {
4529 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4530 + token);
4531 return;
4532 }
4533 final long origId = Binder.clearCallingIdentity();
4534 try {
4535 r.setDisablePreviewScreenshots(disable);
4536 } finally {
4537 Binder.restoreCallingIdentity(origId);
4538 }
4539 }
4540 }
4541
4542 /** Return the user id of the last resumed activity. */
4543 @Override
4544 public @UserIdInt
4545 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004546 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4548 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004549 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004550 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004551 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004552 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 }
4554 }
4555
4556 @Override
4557 public void updateLockTaskFeatures(int userId, int flags) {
4558 final int callingUid = Binder.getCallingUid();
4559 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 "updateLockTaskFeatures()");
4562 }
4563 synchronized (mGlobalLock) {
4564 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4565 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004566 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 }
4568 }
4569
4570 @Override
4571 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4572 synchronized (mGlobalLock) {
4573 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4574 if (r == null) {
4575 return;
4576 }
4577 final long origId = Binder.clearCallingIdentity();
4578 try {
4579 r.setShowWhenLocked(showWhenLocked);
4580 } finally {
4581 Binder.restoreCallingIdentity(origId);
4582 }
4583 }
4584 }
4585
4586 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004587 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4588 synchronized (mGlobalLock) {
4589 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4590 if (r == null) {
4591 return;
4592 }
4593 final long origId = Binder.clearCallingIdentity();
4594 try {
4595 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4596 } finally {
4597 Binder.restoreCallingIdentity(origId);
4598 }
4599 }
4600 }
4601
4602 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004603 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4604 synchronized (mGlobalLock) {
4605 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4606 if (r == null) {
4607 return;
4608 }
4609 final long origId = Binder.clearCallingIdentity();
4610 try {
4611 r.setTurnScreenOn(turnScreenOn);
4612 } finally {
4613 Binder.restoreCallingIdentity(origId);
4614 }
4615 }
4616 }
4617
4618 @Override
4619 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004620 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004621 "registerRemoteAnimations");
4622 definition.setCallingPid(Binder.getCallingPid());
4623 synchronized (mGlobalLock) {
4624 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4625 if (r == null) {
4626 return;
4627 }
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
4630 r.registerRemoteAnimations(definition);
4631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
4636
4637 @Override
4638 public void registerRemoteAnimationForNextActivityStart(String packageName,
4639 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004641 "registerRemoteAnimationForNextActivityStart");
4642 adapter.setCallingPid(Binder.getCallingPid());
4643 synchronized (mGlobalLock) {
4644 final long origId = Binder.clearCallingIdentity();
4645 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004646 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004647 packageName, adapter);
4648 } finally {
4649 Binder.restoreCallingIdentity(origId);
4650 }
4651 }
4652 }
4653
Evan Rosky966759f2019-01-15 10:33:58 -08004654 @Override
4655 public void registerRemoteAnimationsForDisplay(int displayId,
4656 RemoteAnimationDefinition definition) {
4657 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4658 "registerRemoteAnimations");
4659 definition.setCallingPid(Binder.getCallingPid());
4660 synchronized (mGlobalLock) {
4661 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4662 if (display == null) {
4663 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4664 return;
4665 }
4666 final long origId = Binder.clearCallingIdentity();
4667 try {
4668 display.mDisplayContent.registerRemoteAnimations(definition);
4669 } finally {
4670 Binder.restoreCallingIdentity(origId);
4671 }
4672 }
4673 }
4674
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004675 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4676 @Override
4677 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4678 synchronized (mGlobalLock) {
4679 final long origId = Binder.clearCallingIdentity();
4680 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004681 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004682 } finally {
4683 Binder.restoreCallingIdentity(origId);
4684 }
4685 }
4686 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004687
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 @Override
4689 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004690 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004691 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004692 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004693 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004694 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004695 }
4696 }
4697
4698 @Override
4699 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004700 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004701 != PERMISSION_GRANTED) {
4702 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4703 + Binder.getCallingPid()
4704 + ", uid=" + Binder.getCallingUid()
4705 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4706 Slog.w(TAG, msg);
4707 throw new SecurityException(msg);
4708 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004709 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004710 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004711 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004712 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004713 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004714 }
4715 }
4716
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004717 @Override
4718 public void stopAppSwitches() {
4719 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4720 synchronized (mGlobalLock) {
4721 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4722 mDidAppSwitch = false;
4723 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4724 }
4725 }
4726
4727 @Override
4728 public void resumeAppSwitches() {
4729 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4730 synchronized (mGlobalLock) {
4731 // Note that we don't execute any pending app switches... we will
4732 // let those wait until either the timeout, or the next start
4733 // activity request.
4734 mAppSwitchesAllowedTime = 0;
4735 }
4736 }
4737
4738 void onStartActivitySetDidAppSwitch() {
4739 if (mDidAppSwitch) {
4740 // This is the second allowed switch since we stopped switches, so now just generally
4741 // allow switches. Use case:
4742 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4743 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4744 // anyone to switch again).
4745 mAppSwitchesAllowedTime = 0;
4746 } else {
4747 mDidAppSwitch = true;
4748 }
4749 }
4750
4751 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004752 boolean shouldDisableNonVrUiLocked() {
4753 return mVrController.shouldDisableNonVrUiLocked();
4754 }
4755
Wale Ogunwale53783742018-09-16 10:21:51 -07004756 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004757 // VR apps are expected to run in a main display. If an app is turning on VR for
4758 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4759 // fullscreen stack before enabling VR Mode.
4760 // TODO: The goal of this code is to keep the VR app on the main display. When the
4761 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4762 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4763 // option would be a better choice here.
4764 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4765 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4766 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004767 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004768 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004769 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004770 }
4771 mH.post(() -> {
4772 if (!mVrController.onVrModeChanged(r)) {
4773 return;
4774 }
4775 synchronized (mGlobalLock) {
4776 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4777 mWindowManager.disableNonVrUi(disableNonVrUi);
4778 if (disableNonVrUi) {
4779 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4780 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004781 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 }
4783 }
4784 });
4785 }
4786
Wale Ogunwale53783742018-09-16 10:21:51 -07004787 @Override
4788 public int getPackageScreenCompatMode(String packageName) {
4789 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4790 synchronized (mGlobalLock) {
4791 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4792 }
4793 }
4794
4795 @Override
4796 public void setPackageScreenCompatMode(String packageName, int mode) {
4797 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4798 "setPackageScreenCompatMode");
4799 synchronized (mGlobalLock) {
4800 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4801 }
4802 }
4803
4804 @Override
4805 public boolean getPackageAskScreenCompat(String packageName) {
4806 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4807 synchronized (mGlobalLock) {
4808 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4809 }
4810 }
4811
4812 @Override
4813 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4814 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4815 "setPackageAskScreenCompat");
4816 synchronized (mGlobalLock) {
4817 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4818 }
4819 }
4820
Wale Ogunwale64258362018-10-16 15:13:37 -07004821 public static String relaunchReasonToString(int relaunchReason) {
4822 switch (relaunchReason) {
4823 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4824 return "window_resize";
4825 case RELAUNCH_REASON_FREE_RESIZE:
4826 return "free_resize";
4827 default:
4828 return null;
4829 }
4830 }
4831
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004832 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004833 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004834 }
4835
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004836 /** Pokes the task persister. */
4837 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4838 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4839 }
4840
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004841 boolean isKeyguardLocked() {
4842 return mKeyguardController.isKeyguardLocked();
4843 }
4844
Garfield Tan01548632018-11-27 10:15:48 -08004845 /**
4846 * Clears launch params for the given package.
4847 * @param packageNames the names of the packages of which the launch params are to be cleared
4848 */
4849 @Override
4850 public void clearLaunchParamsForPackages(List<String> packageNames) {
4851 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4852 "clearLaunchParamsForPackages");
4853 synchronized (mGlobalLock) {
4854 for (int i = 0; i < packageNames.size(); ++i) {
4855 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4856 }
4857 }
4858 }
4859
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004860 /**
4861 * Makes the display with the given id a single task instance display. I.e the display can only
4862 * contain one task.
4863 */
4864 @Override
4865 public void setDisplayToSingleTaskInstance(int displayId) {
4866 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4867 "setDisplayToSingleTaskInstance");
4868 final long origId = Binder.clearCallingIdentity();
4869 try {
4870 final ActivityDisplay display =
4871 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4872 if (display != null) {
4873 display.setDisplayToSingleTaskInstance();
4874 }
4875 } finally {
4876 Binder.restoreCallingIdentity(origId);
4877 }
4878 }
4879
Wale Ogunwale31913b52018-10-13 08:29:31 -07004880 void dumpLastANRLocked(PrintWriter pw) {
4881 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4882 if (mLastANRState == null) {
4883 pw.println(" <no ANR has occurred since boot>");
4884 } else {
4885 pw.println(mLastANRState);
4886 }
4887 }
4888
4889 void dumpLastANRTracesLocked(PrintWriter pw) {
4890 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4891
4892 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4893 if (ArrayUtils.isEmpty(files)) {
4894 pw.println(" <no ANR has occurred since boot>");
4895 return;
4896 }
4897 // Find the latest file.
4898 File latest = null;
4899 for (File f : files) {
4900 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4901 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004902 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004903 }
4904 pw.print("File: ");
4905 pw.print(latest.getName());
4906 pw.println();
4907 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4908 String line;
4909 while ((line = in.readLine()) != null) {
4910 pw.println(line);
4911 }
4912 } catch (IOException e) {
4913 pw.print("Unable to read: ");
4914 pw.print(e);
4915 pw.println();
4916 }
4917 }
4918
4919 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4920 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4921 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4922 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4923 }
4924
4925 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4926 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4927 pw.println(header);
4928
Wale Ogunwaled32da472018-11-16 07:19:28 -08004929 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004930 dumpPackage);
4931 boolean needSep = printedAnything;
4932
4933 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004934 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004935 " ResumedActivity: ");
4936 if (printed) {
4937 printedAnything = true;
4938 needSep = false;
4939 }
4940
4941 if (dumpPackage == null) {
4942 if (needSep) {
4943 pw.println();
4944 }
4945 printedAnything = true;
4946 mStackSupervisor.dump(pw, " ");
4947 }
4948
4949 if (!printedAnything) {
4950 pw.println(" (nothing)");
4951 }
4952 }
4953
4954 void dumpActivityContainersLocked(PrintWriter pw) {
4955 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004956 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004957 pw.println(" ");
4958 }
4959
4960 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4961 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4962 getActivityStartController().dump(pw, "", dumpPackage);
4963 }
4964
4965 /**
4966 * There are three things that cmd can be:
4967 * - a flattened component name that matches an existing activity
4968 * - the cmd arg isn't the flattened component name of an existing activity:
4969 * dump all activity whose component contains the cmd as a substring
4970 * - A hex number of the ActivityRecord object instance.
4971 *
4972 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4973 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4974 */
4975 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4976 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4977 ArrayList<ActivityRecord> activities;
4978
4979 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004980 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004981 dumpFocusedStackOnly);
4982 }
4983
4984 if (activities.size() <= 0) {
4985 return false;
4986 }
4987
4988 String[] newArgs = new String[args.length - opti];
4989 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4990
4991 TaskRecord lastTask = null;
4992 boolean needSep = false;
4993 for (int i = activities.size() - 1; i >= 0; i--) {
4994 ActivityRecord r = activities.get(i);
4995 if (needSep) {
4996 pw.println();
4997 }
4998 needSep = true;
4999 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005000 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005001 if (lastTask != task) {
5002 lastTask = task;
5003 pw.print("TASK "); pw.print(lastTask.affinity);
5004 pw.print(" id="); pw.print(lastTask.taskId);
5005 pw.print(" userId="); pw.println(lastTask.userId);
5006 if (dumpAll) {
5007 lastTask.dump(pw, " ");
5008 }
5009 }
5010 }
5011 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5012 }
5013 return true;
5014 }
5015
5016 /**
5017 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5018 * there is a thread associated with the activity.
5019 */
5020 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5021 final ActivityRecord r, String[] args, boolean dumpAll) {
5022 String innerPrefix = prefix + " ";
5023 synchronized (mGlobalLock) {
5024 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5025 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5026 pw.print(" pid=");
5027 if (r.hasProcess()) pw.println(r.app.getPid());
5028 else pw.println("(not running)");
5029 if (dumpAll) {
5030 r.dump(pw, innerPrefix);
5031 }
5032 }
5033 if (r.attachedToProcess()) {
5034 // flush anything that is already in the PrintWriter since the thread is going
5035 // to write to the file descriptor directly
5036 pw.flush();
5037 try {
5038 TransferPipe tp = new TransferPipe();
5039 try {
5040 r.app.getThread().dumpActivity(tp.getWriteFd(),
5041 r.appToken, innerPrefix, args);
5042 tp.go(fd);
5043 } finally {
5044 tp.kill();
5045 }
5046 } catch (IOException e) {
5047 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5048 } catch (RemoteException e) {
5049 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5050 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005051 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005052 }
5053
sanryhuang498e77e2018-12-06 14:57:01 +08005054 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5055 boolean testPssMode) {
5056 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5057 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5058 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005059 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005060 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5061 st.toString());
5062 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005063 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5064 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5065 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005066 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5067 testPssMode);
5068 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005069 }
5070
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071 int getCurrentUserId() {
5072 return mAmInternal.getCurrentUserId();
5073 }
5074
5075 private void enforceNotIsolatedCaller(String caller) {
5076 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5077 throw new SecurityException("Isolated process not allowed to call " + caller);
5078 }
5079 }
5080
Wale Ogunwalef6733932018-06-27 05:14:34 -07005081 public Configuration getConfiguration() {
5082 Configuration ci;
5083 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005084 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005085 ci.userSetLocale = false;
5086 }
5087 return ci;
5088 }
5089
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005090 /**
5091 * Current global configuration information. Contains general settings for the entire system,
5092 * also corresponds to the merged configuration of the default display.
5093 */
5094 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005095 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005096 }
5097
5098 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5099 boolean initLocale) {
5100 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5101 }
5102
5103 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5104 boolean initLocale, boolean deferResume) {
5105 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5106 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5107 UserHandle.USER_NULL, deferResume);
5108 }
5109
Wale Ogunwale59507092018-10-29 09:00:30 -07005110 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005111 final long origId = Binder.clearCallingIdentity();
5112 try {
5113 synchronized (mGlobalLock) {
5114 updateConfigurationLocked(values, null, false, true, userId,
5115 false /* deferResume */);
5116 }
5117 } finally {
5118 Binder.restoreCallingIdentity(origId);
5119 }
5120 }
5121
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005122 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5123 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5124 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5125 deferResume, null /* result */);
5126 }
5127
5128 /**
5129 * Do either or both things: (1) change the current configuration, and (2)
5130 * make sure the given activity is running with the (now) current
5131 * configuration. Returns true if the activity has been left running, or
5132 * false if <var>starting</var> is being destroyed to match the new
5133 * configuration.
5134 *
5135 * @param userId is only used when persistent parameter is set to true to persist configuration
5136 * for that particular user
5137 */
5138 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5139 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5140 ActivityTaskManagerService.UpdateConfigurationResult result) {
5141 int changes = 0;
5142 boolean kept = true;
5143
5144 if (mWindowManager != null) {
5145 mWindowManager.deferSurfaceLayout();
5146 }
5147 try {
5148 if (values != null) {
5149 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5150 deferResume);
5151 }
5152
5153 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5154 } finally {
5155 if (mWindowManager != null) {
5156 mWindowManager.continueSurfaceLayout();
5157 }
5158 }
5159
5160 if (result != null) {
5161 result.changes = changes;
5162 result.activityRelaunched = !kept;
5163 }
5164 return kept;
5165 }
5166
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005167 /** Update default (global) configuration and notify listeners about changes. */
5168 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5169 boolean persistent, int userId, boolean deferResume) {
5170 mTempConfig.setTo(getGlobalConfiguration());
5171 final int changes = mTempConfig.updateFrom(values);
5172 if (changes == 0) {
5173 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5174 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5175 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5176 // (even if there are no actual changes) to unfreeze the window.
5177 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5178 return 0;
5179 }
5180
5181 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5182 "Updating global configuration to: " + values);
5183
5184 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5185 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5186 values.colorMode,
5187 values.densityDpi,
5188 values.fontScale,
5189 values.hardKeyboardHidden,
5190 values.keyboard,
5191 values.keyboardHidden,
5192 values.mcc,
5193 values.mnc,
5194 values.navigation,
5195 values.navigationHidden,
5196 values.orientation,
5197 values.screenHeightDp,
5198 values.screenLayout,
5199 values.screenWidthDp,
5200 values.smallestScreenWidthDp,
5201 values.touchscreen,
5202 values.uiMode);
5203
5204
5205 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5206 final LocaleList locales = values.getLocales();
5207 int bestLocaleIndex = 0;
5208 if (locales.size() > 1) {
5209 if (mSupportedSystemLocales == null) {
5210 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5211 }
5212 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5213 }
5214 SystemProperties.set("persist.sys.locale",
5215 locales.get(bestLocaleIndex).toLanguageTag());
5216 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005217
5218 final Message m = PooledLambda.obtainMessage(
5219 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5220 locales.get(bestLocaleIndex));
5221 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222 }
5223
Yunfan Chen75157d72018-07-27 14:47:21 +09005224 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225
5226 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005227 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228
5229 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5230 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005231 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232
5233 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005234 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235
5236 AttributeCache ac = AttributeCache.instance();
5237 if (ac != null) {
5238 ac.updateConfiguration(mTempConfig);
5239 }
5240
5241 // Make sure all resources in our process are updated right now, so that anyone who is going
5242 // to retrieve resource values after we return will be sure to get the new ones. This is
5243 // especially important during boot, where the first config change needs to guarantee all
5244 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005245 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246
5247 // We need another copy of global config because we're scheduling some calls instead of
5248 // running them in place. We need to be sure that object we send will be handled unchanged.
5249 final Configuration configCopy = new Configuration(mTempConfig);
5250 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005251 final Message msg = PooledLambda.obtainMessage(
5252 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5253 this, userId, configCopy);
5254 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005255 }
5256
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005257 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5258 for (int i = pidMap.size() - 1; i >= 0; i--) {
5259 final int pid = pidMap.keyAt(i);
5260 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005261 if (DEBUG_CONFIGURATION) {
5262 Slog.v(TAG_CONFIGURATION, "Update process config of "
5263 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005264 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005265 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 }
5267
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005268 final Message msg = PooledLambda.obtainMessage(
5269 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5270 mAmInternal, changes, initLocale);
5271 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005272
5273 // Override configuration of the default display duplicates global config, so we need to
5274 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005275 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005276 DEFAULT_DISPLAY);
5277
5278 return changes;
5279 }
5280
5281 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5282 boolean deferResume, int displayId) {
5283 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5284 displayId, null /* result */);
5285 }
5286
5287 /**
5288 * Updates override configuration specific for the selected display. If no config is provided,
5289 * new one will be computed in WM based on current display info.
5290 */
5291 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5292 ActivityRecord starting, boolean deferResume, int displayId,
5293 ActivityTaskManagerService.UpdateConfigurationResult result) {
5294 int changes = 0;
5295 boolean kept = true;
5296
5297 if (mWindowManager != null) {
5298 mWindowManager.deferSurfaceLayout();
5299 }
5300 try {
5301 if (values != null) {
5302 if (displayId == DEFAULT_DISPLAY) {
5303 // Override configuration of the default display duplicates global config, so
5304 // we're calling global config update instead for default display. It will also
5305 // apply the correct override config.
5306 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5307 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5308 } else {
5309 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5310 }
5311 }
5312
5313 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5314 } finally {
5315 if (mWindowManager != null) {
5316 mWindowManager.continueSurfaceLayout();
5317 }
5318 }
5319
5320 if (result != null) {
5321 result.changes = changes;
5322 result.activityRelaunched = !kept;
5323 }
5324 return kept;
5325 }
5326
5327 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5328 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005329 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005330 final int changes = mTempConfig.updateFrom(values);
5331 if (changes != 0) {
5332 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5333 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005334 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005335
5336 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5337 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005338 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005339
Wale Ogunwale5c918702018-10-18 11:06:33 -07005340 // Post message to start process to avoid possible deadlock of calling into AMS with
5341 // the ATMS lock held.
5342 final Message msg = PooledLambda.obtainMessage(
5343 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005344 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005345 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005346 }
5347 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005348 return changes;
5349 }
5350
Wale Ogunwalef6733932018-06-27 05:14:34 -07005351 private void updateEventDispatchingLocked(boolean booted) {
5352 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5353 }
5354
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005355 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5356 final ContentResolver resolver = mContext.getContentResolver();
5357 Settings.System.putConfigurationForUser(resolver, config, userId);
5358 }
5359
5360 private void sendLocaleToMountDaemonMsg(Locale l) {
5361 try {
5362 IBinder service = ServiceManager.getService("mount");
5363 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5364 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5365 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5366 } catch (RemoteException e) {
5367 Log.e(TAG, "Error storing locale for decryption UI", e);
5368 }
5369 }
5370
Alison Cichowlas3e340502018-08-07 17:15:01 -04005371 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5372 mStartActivitySources.remove(permissionToken);
5373 mExpiredStartAsCallerTokens.add(permissionToken);
5374 }
5375
5376 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5377 mExpiredStartAsCallerTokens.remove(permissionToken);
5378 }
5379
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005380 boolean isActivityStartsLoggingEnabled() {
5381 return mAmInternal.isActivityStartsLoggingEnabled();
5382 }
5383
Michal Karpinski8596ded2018-11-14 14:43:48 +00005384 boolean isBackgroundActivityStartsEnabled() {
5385 return mAmInternal.isBackgroundActivityStartsEnabled();
5386 }
5387
Ricky Waiaca8a772019-04-04 16:01:06 +01005388 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5389 if (packageName == null) {
5390 return false;
5391 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005392 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5393 }
5394
Wale Ogunwalef6733932018-06-27 05:14:34 -07005395 void enableScreenAfterBoot(boolean booted) {
5396 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5397 SystemClock.uptimeMillis());
5398 mWindowManager.enableScreenAfterBoot();
5399
5400 synchronized (mGlobalLock) {
5401 updateEventDispatchingLocked(booted);
5402 }
5403 }
5404
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005405 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5406 if (r == null || !r.hasProcess()) {
5407 return KEY_DISPATCHING_TIMEOUT_MS;
5408 }
5409 return getInputDispatchingTimeoutLocked(r.app);
5410 }
5411
5412 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005413 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005414 }
5415
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 /**
5417 * Decide based on the configuration whether we should show the ANR,
5418 * crash, etc dialogs. The idea is that if there is no affordance to
5419 * press the on-screen buttons, or the user experience would be more
5420 * greatly impacted than the crash itself, we shouldn't show the dialog.
5421 *
5422 * A thought: SystemUI might also want to get told about this, the Power
5423 * dialog / global actions also might want different behaviors.
5424 */
5425 private void updateShouldShowDialogsLocked(Configuration config) {
5426 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5427 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5428 && config.navigation == Configuration.NAVIGATION_NONAV);
5429 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5430 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5431 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5432 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5433 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5434 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5435 HIDE_ERROR_DIALOGS, 0) != 0;
5436 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5437 }
5438
5439 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5440 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5441 FONT_SCALE, 1.0f, userId);
5442
5443 synchronized (this) {
5444 if (getGlobalConfiguration().fontScale == scaleFactor) {
5445 return;
5446 }
5447
5448 final Configuration configuration
5449 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5450 configuration.fontScale = scaleFactor;
5451 updatePersistentConfiguration(configuration, userId);
5452 }
5453 }
5454
5455 // Actually is sleeping or shutting down or whatever else in the future
5456 // is an inactive state.
5457 boolean isSleepingOrShuttingDownLocked() {
5458 return isSleepingLocked() || mShuttingDown;
5459 }
5460
5461 boolean isSleepingLocked() {
5462 return mSleeping;
5463 }
5464
Riddle Hsu16567132018-08-16 21:37:47 +08005465 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005467 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468 if (task.isActivityTypeStandard()) {
5469 if (mCurAppTimeTracker != r.appTimeTracker) {
5470 // We are switching app tracking. Complete the current one.
5471 if (mCurAppTimeTracker != null) {
5472 mCurAppTimeTracker.stop();
5473 mH.obtainMessage(
5474 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005475 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005476 mCurAppTimeTracker = null;
5477 }
5478 if (r.appTimeTracker != null) {
5479 mCurAppTimeTracker = r.appTimeTracker;
5480 startTimeTrackingFocusedActivityLocked();
5481 }
5482 } else {
5483 startTimeTrackingFocusedActivityLocked();
5484 }
5485 } else {
5486 r.appTimeTracker = null;
5487 }
5488 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5489 // TODO: Probably not, because we don't want to resume voice on switching
5490 // back to this activity
5491 if (task.voiceInteractor != null) {
5492 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5493 } else {
5494 finishRunningVoiceLocked();
5495
5496 if (mLastResumedActivity != null) {
5497 final IVoiceInteractionSession session;
5498
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005499 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 if (lastResumedActivityTask != null
5501 && lastResumedActivityTask.voiceSession != null) {
5502 session = lastResumedActivityTask.voiceSession;
5503 } else {
5504 session = mLastResumedActivity.voiceSession;
5505 }
5506
5507 if (session != null) {
5508 // We had been in a voice interaction session, but now focused has
5509 // move to something different. Just finish the session, we can't
5510 // return to it and retain the proper state and synchronization with
5511 // the voice interaction service.
5512 finishVoiceTask(session);
5513 }
5514 }
5515 }
5516
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005517 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5518 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005519 }
5520 updateResumedAppTrace(r);
5521 mLastResumedActivity = r;
5522
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005523 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005524
5525 applyUpdateLockStateLocked(r);
5526 applyUpdateVrModeLocked(r);
5527
5528 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005529 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005530 r == null ? "NULL" : r.shortComponentName,
5531 reason);
5532 }
5533
5534 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5535 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005536 final ActivityTaskManagerInternal.SleepToken token =
5537 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 updateSleepIfNeededLocked();
5539 return token;
5540 }
5541 }
5542
5543 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005544 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 final boolean wasSleeping = mSleeping;
5546 boolean updateOomAdj = false;
5547
5548 if (!shouldSleep) {
5549 // If wasSleeping is true, we need to wake up activity manager state from when
5550 // we started sleeping. In either case, we need to apply the sleep tokens, which
5551 // will wake up stacks or put them to sleep as appropriate.
5552 if (wasSleeping) {
5553 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005554 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5555 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 startTimeTrackingFocusedActivityLocked();
5557 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005558 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5560 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005561 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 if (wasSleeping) {
5563 updateOomAdj = true;
5564 }
5565 } else if (!mSleeping && shouldSleep) {
5566 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005567 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5568 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 if (mCurAppTimeTracker != null) {
5570 mCurAppTimeTracker.stop();
5571 }
5572 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005573 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 mStackSupervisor.goingToSleepLocked();
5575 updateResumedAppTrace(null /* resumed */);
5576 updateOomAdj = true;
5577 }
5578 if (updateOomAdj) {
5579 mH.post(mAmInternal::updateOomAdj);
5580 }
5581 }
5582
5583 void updateOomAdj() {
5584 mH.post(mAmInternal::updateOomAdj);
5585 }
5586
Wale Ogunwale53783742018-09-16 10:21:51 -07005587 void updateCpuStats() {
5588 mH.post(mAmInternal::updateCpuStats);
5589 }
5590
Hui Yu03d12402018-12-06 18:00:37 -08005591 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5592 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005593 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5594 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005595 mH.sendMessage(m);
5596 }
5597
Hui Yu03d12402018-12-06 18:00:37 -08005598 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005599 ComponentName taskRoot = null;
5600 final TaskRecord task = activity.getTaskRecord();
5601 if (task != null) {
5602 final ActivityRecord rootActivity = task.getRootActivity();
5603 if (rootActivity != null) {
5604 taskRoot = rootActivity.mActivityComponent;
5605 }
5606 }
5607
Hui Yu03d12402018-12-06 18:00:37 -08005608 final Message m = PooledLambda.obtainMessage(
5609 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005610 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005611 mH.sendMessage(m);
5612 }
5613
Wale Ogunwale53783742018-09-16 10:21:51 -07005614 void setBooting(boolean booting) {
5615 mAmInternal.setBooting(booting);
5616 }
5617
5618 boolean isBooting() {
5619 return mAmInternal.isBooting();
5620 }
5621
5622 void setBooted(boolean booted) {
5623 mAmInternal.setBooted(booted);
5624 }
5625
5626 boolean isBooted() {
5627 return mAmInternal.isBooted();
5628 }
5629
5630 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5631 mH.post(() -> {
5632 if (finishBooting) {
5633 mAmInternal.finishBooting();
5634 }
5635 if (enableScreen) {
5636 mInternal.enableScreenAfterBoot(isBooted());
5637 }
5638 });
5639 }
5640
5641 void setHeavyWeightProcess(ActivityRecord root) {
5642 mHeavyWeightProcess = root.app;
5643 final Message m = PooledLambda.obtainMessage(
5644 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005645 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005646 mH.sendMessage(m);
5647 }
5648
5649 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5650 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5651 return;
5652 }
5653
5654 mHeavyWeightProcess = null;
5655 final Message m = PooledLambda.obtainMessage(
5656 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5657 proc.mUserId);
5658 mH.sendMessage(m);
5659 }
5660
5661 private void cancelHeavyWeightProcessNotification(int userId) {
5662 final INotificationManager inm = NotificationManager.getService();
5663 if (inm == null) {
5664 return;
5665 }
5666 try {
5667 inm.cancelNotificationWithTag("android", null,
5668 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5669 } catch (RuntimeException e) {
5670 Slog.w(TAG, "Error canceling notification for service", e);
5671 } catch (RemoteException e) {
5672 }
5673
5674 }
5675
5676 private void postHeavyWeightProcessNotification(
5677 WindowProcessController proc, Intent intent, int userId) {
5678 if (proc == null) {
5679 return;
5680 }
5681
5682 final INotificationManager inm = NotificationManager.getService();
5683 if (inm == null) {
5684 return;
5685 }
5686
5687 try {
5688 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5689 String text = mContext.getString(R.string.heavy_weight_notification,
5690 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5691 Notification notification =
5692 new Notification.Builder(context,
5693 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5694 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5695 .setWhen(0)
5696 .setOngoing(true)
5697 .setTicker(text)
5698 .setColor(mContext.getColor(
5699 com.android.internal.R.color.system_notification_accent_color))
5700 .setContentTitle(text)
5701 .setContentText(
5702 mContext.getText(R.string.heavy_weight_notification_detail))
5703 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5704 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5705 new UserHandle(userId)))
5706 .build();
5707 try {
5708 inm.enqueueNotificationWithTag("android", "android", null,
5709 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5710 } catch (RuntimeException e) {
5711 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5712 } catch (RemoteException e) {
5713 }
5714 } catch (PackageManager.NameNotFoundException e) {
5715 Slog.w(TAG, "Unable to create context for heavy notification", e);
5716 }
5717
5718 }
5719
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005720 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5721 IBinder token, String resultWho, int requestCode, Intent[] intents,
5722 String[] resolvedTypes, int flags, Bundle bOptions) {
5723
5724 ActivityRecord activity = null;
5725 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5726 activity = ActivityRecord.isInStackLocked(token);
5727 if (activity == null) {
5728 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5729 return null;
5730 }
5731 if (activity.finishing) {
5732 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5733 return null;
5734 }
5735 }
5736
5737 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5738 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5739 bOptions);
5740 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5741 if (noCreate) {
5742 return rec;
5743 }
5744 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5745 if (activity.pendingResults == null) {
5746 activity.pendingResults = new HashSet<>();
5747 }
5748 activity.pendingResults.add(rec.ref);
5749 }
5750 return rec;
5751 }
5752
Andrii Kulian52d255c2018-07-13 11:32:19 -07005753 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005754 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005755 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005756 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5757 mCurAppTimeTracker.start(resumedActivity.packageName);
5758 }
5759 }
5760
5761 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5762 if (mTracedResumedActivity != null) {
5763 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5764 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5765 }
5766 if (resumed != null) {
5767 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5768 constructResumedTraceName(resumed.packageName), 0);
5769 }
5770 mTracedResumedActivity = resumed;
5771 }
5772
5773 private String constructResumedTraceName(String packageName) {
5774 return "focused app: " + packageName;
5775 }
5776
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005777 /** Applies latest configuration and/or visibility updates if needed. */
5778 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5779 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005780 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005781 // mainStack is null during startup.
5782 if (mainStack != null) {
5783 if (changes != 0 && starting == null) {
5784 // If the configuration changed, and the caller is not already
5785 // in the process of starting an activity, then find the top
5786 // activity to check if its configuration needs to change.
5787 starting = mainStack.topRunningActivityLocked();
5788 }
5789
5790 if (starting != null) {
5791 kept = starting.ensureActivityConfiguration(changes,
5792 false /* preserveWindow */);
5793 // And we need to make sure at this point that all other activities
5794 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005795 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005796 !PRESERVE_WINDOWS);
5797 }
5798 }
5799
5800 return kept;
5801 }
5802
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005803 void scheduleAppGcsLocked() {
5804 mH.post(() -> mAmInternal.scheduleAppGcs());
5805 }
5806
Wale Ogunwale53783742018-09-16 10:21:51 -07005807 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5808 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5809 }
5810
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005811 /**
5812 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5813 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5814 * on demand.
5815 */
5816 IPackageManager getPackageManager() {
5817 return AppGlobals.getPackageManager();
5818 }
5819
5820 PackageManagerInternal getPackageManagerInternalLocked() {
5821 if (mPmInternal == null) {
5822 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5823 }
5824 return mPmInternal;
5825 }
5826
Wale Ogunwale008163e2018-07-23 23:11:08 -07005827 AppWarnings getAppWarningsLocked() {
5828 return mAppWarnings;
5829 }
5830
Wale Ogunwale214f3482018-10-04 11:00:47 -07005831 Intent getHomeIntent() {
5832 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5833 intent.setComponent(mTopComponent);
5834 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5835 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5836 intent.addCategory(Intent.CATEGORY_HOME);
5837 }
5838 return intent;
5839 }
5840
Chilun2ef71f72018-11-16 17:57:15 +08005841 /**
5842 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5843 * activities.
5844 *
5845 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5846 * component defined in config_secondaryHomeComponent.
5847 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5848 */
5849 Intent getSecondaryHomeIntent(String preferredPackage) {
5850 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005851 if (preferredPackage == null) {
5852 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005853 final String secondaryHomeComponent = mContext.getResources().getString(
5854 com.android.internal.R.string.config_secondaryHomeComponent);
5855 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5856 } else {
5857 intent.setPackage(preferredPackage);
5858 }
5859 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5860 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5861 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5862 }
5863 return intent;
5864 }
5865
Wale Ogunwale214f3482018-10-04 11:00:47 -07005866 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5867 if (info == null) return null;
5868 ApplicationInfo newInfo = new ApplicationInfo(info);
5869 newInfo.initForUser(userId);
5870 return newInfo;
5871 }
5872
Wale Ogunwale9c103022018-10-18 07:44:54 -07005873 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005874 if (uid == SYSTEM_UID) {
5875 // The system gets to run in any process. If there are multiple processes with the same
5876 // uid, just pick the first (this should never happen).
5877 final SparseArray<WindowProcessController> procs =
5878 mProcessNames.getMap().get(processName);
5879 if (procs == null) return null;
5880 final int procCount = procs.size();
5881 for (int i = 0; i < procCount; i++) {
5882 final int procUid = procs.keyAt(i);
5883 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5884 // Don't use an app process or different user process for system component.
5885 continue;
5886 }
5887 return procs.valueAt(i);
5888 }
5889 }
5890
5891 return mProcessNames.get(processName, uid);
5892 }
5893
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005894 WindowProcessController getProcessController(IApplicationThread thread) {
5895 if (thread == null) {
5896 return null;
5897 }
5898
5899 final IBinder threadBinder = thread.asBinder();
5900 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5901 for (int i = pmap.size()-1; i >= 0; i--) {
5902 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5903 for (int j = procs.size() - 1; j >= 0; j--) {
5904 final WindowProcessController proc = procs.valueAt(j);
5905 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5906 return proc;
5907 }
5908 }
5909 }
5910
5911 return null;
5912 }
5913
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005914 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005915 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005916 if (proc == null) return null;
5917 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5918 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005919 }
5920 return null;
5921 }
5922
Riddle Hsua0536432019-02-16 00:38:59 +08005923 int getUidState(int uid) {
5924 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005925 }
5926
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005927 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005928 // A uid is considered to be foreground if it has a visible non-toast window.
5929 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005930 }
5931
Ricky Wai96f5c352019-04-10 18:40:17 +01005932 boolean isDeviceOwner(int uid) {
5933 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005934 }
5935
Ricky Wai96f5c352019-04-10 18:40:17 +01005936 void setDeviceOwnerUid(int uid) {
5937 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005938 }
5939
Wale Ogunwale9de19442018-10-18 19:05:03 -07005940 /**
5941 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5942 * the whitelist
5943 */
5944 String getPendingTempWhitelistTagForUidLocked(int uid) {
5945 return mPendingTempWhitelist.get(uid);
5946 }
5947
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005948 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5949 if (true || Build.IS_USER) {
5950 return;
5951 }
5952
5953 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5954 StrictMode.allowThreadDiskWrites();
5955 try {
5956 File tracesDir = new File("/data/anr");
5957 File tracesFile = null;
5958 try {
5959 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5960
5961 StringBuilder sb = new StringBuilder();
5962 Time tobj = new Time();
5963 tobj.set(System.currentTimeMillis());
5964 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5965 sb.append(": ");
5966 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5967 sb.append(" since ");
5968 sb.append(msg);
5969 FileOutputStream fos = new FileOutputStream(tracesFile);
5970 fos.write(sb.toString().getBytes());
5971 if (app == null) {
5972 fos.write("\n*** No application process!".getBytes());
5973 }
5974 fos.close();
5975 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5976 } catch (IOException e) {
5977 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5978 return;
5979 }
5980
5981 if (app != null && app.getPid() > 0) {
5982 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5983 firstPids.add(app.getPid());
5984 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5985 }
5986
5987 File lastTracesFile = null;
5988 File curTracesFile = null;
5989 for (int i=9; i>=0; i--) {
5990 String name = String.format(Locale.US, "slow%02d.txt", i);
5991 curTracesFile = new File(tracesDir, name);
5992 if (curTracesFile.exists()) {
5993 if (lastTracesFile != null) {
5994 curTracesFile.renameTo(lastTracesFile);
5995 } else {
5996 curTracesFile.delete();
5997 }
5998 }
5999 lastTracesFile = curTracesFile;
6000 }
6001 tracesFile.renameTo(curTracesFile);
6002 } finally {
6003 StrictMode.setThreadPolicy(oldPolicy);
6004 }
6005 }
6006
Michal Karpinskida34cd42019-04-02 19:46:52 +01006007 boolean isAssociatedCompanionApp(int userId, int uid) {
6008 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6009 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006010 return false;
6011 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006012 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006013 }
6014
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006015 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006016 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006017
6018
Wale Ogunwale98875612018-10-12 07:53:02 -07006019 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6020 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006021
Riddle Hsud93a6c42018-11-29 21:50:06 +08006022 H(Looper looper) {
6023 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006024 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006025
6026 @Override
6027 public void handleMessage(Message msg) {
6028 switch (msg.what) {
6029 case REPORT_TIME_TRACKER_MSG: {
6030 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6031 tracker.deliverResult(mContext);
6032 } break;
6033 }
6034 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006035 }
6036
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006037 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006038 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006039
6040 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006041 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006042 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006043
6044 @Override
6045 public void handleMessage(Message msg) {
6046 switch (msg.what) {
6047 case DISMISS_DIALOG_UI_MSG: {
6048 final Dialog d = (Dialog) msg.obj;
6049 d.dismiss();
6050 break;
6051 }
6052 }
6053 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006054 }
6055
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 final class LocalService extends ActivityTaskManagerInternal {
6057 @Override
6058 public SleepToken acquireSleepToken(String tag, int displayId) {
6059 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006060 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062
6063 @Override
6064 public ComponentName getHomeActivityForUser(int userId) {
6065 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006066 final ActivityRecord homeActivity =
6067 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006068 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006069 }
6070 }
6071
6072 @Override
6073 public void onLocalVoiceInteractionStarted(IBinder activity,
6074 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6075 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006076 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 }
6078 }
6079
6080 @Override
6081 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6082 synchronized (mGlobalLock) {
6083 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6084 reasons, timestamp);
6085 }
6086 }
6087
6088 @Override
6089 public void notifyAppTransitionFinished() {
6090 synchronized (mGlobalLock) {
6091 mStackSupervisor.notifyAppTransitionDone();
6092 }
6093 }
6094
6095 @Override
6096 public void notifyAppTransitionCancelled() {
6097 synchronized (mGlobalLock) {
6098 mStackSupervisor.notifyAppTransitionDone();
6099 }
6100 }
6101
6102 @Override
6103 public List<IBinder> getTopVisibleActivities() {
6104 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006105 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 }
6107 }
6108
6109 @Override
6110 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6111 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006112 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006113 }
6114 }
6115
6116 @Override
6117 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6118 Bundle bOptions) {
6119 Preconditions.checkNotNull(intents, "intents");
6120 final String[] resolvedTypes = new String[intents.length];
6121
6122 // UID of the package on user userId.
6123 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6124 // packageUid may not be initialized.
6125 int packageUid = 0;
6126 final long ident = Binder.clearCallingIdentity();
6127
6128 try {
6129 for (int i = 0; i < intents.length; i++) {
6130 resolvedTypes[i] =
6131 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6132 }
6133
6134 packageUid = AppGlobals.getPackageManager().getPackageUid(
6135 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6136 } catch (RemoteException e) {
6137 // Shouldn't happen.
6138 } finally {
6139 Binder.restoreCallingIdentity(ident);
6140 }
6141
Riddle Hsu591bf612019-02-14 17:55:31 +08006142 return getActivityStartController().startActivitiesInPackage(
6143 packageUid, packageName,
6144 intents, resolvedTypes, null /* resultTo */,
6145 SafeActivityOptions.fromBundle(bOptions), userId,
6146 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6147 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149
6150 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006151 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6152 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6153 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6154 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006155 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006156 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006157 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6158 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6159 userId, validateIncomingUser, originatingPendingIntent,
6160 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006161 }
6162 }
6163
6164 @Override
6165 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6166 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6167 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6168 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006169 PendingIntentRecord originatingPendingIntent,
6170 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006171 synchronized (mGlobalLock) {
6172 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6173 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6174 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006175 validateIncomingUser, originatingPendingIntent,
6176 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006177 }
6178 }
6179
6180 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6182 Intent intent, Bundle options, int userId) {
6183 return ActivityTaskManagerService.this.startActivityAsUser(
6184 caller, callerPacakge, intent,
6185 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6186 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6187 false /*validateIncomingUser*/);
6188 }
6189
6190 @Override
lumark588a3e82018-07-20 18:53:54 +08006191 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 synchronized (mGlobalLock) {
6193
6194 // We might change the visibilities here, so prepare an empty app transition which
6195 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006196 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006197 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006198 if (activityDisplay == null) {
6199 return;
6200 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006201 final DisplayContent dc = activityDisplay.mDisplayContent;
6202 final boolean wasTransitionSet =
6203 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006205 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006207 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208
6209 // If there was a transition set already we don't want to interfere with it as we
6210 // might be starting it too early.
6211 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006212 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006213 }
6214 }
6215 if (callback != null) {
6216 callback.run();
6217 }
6218 }
6219
6220 @Override
6221 public void notifyKeyguardTrustedChanged() {
6222 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006223 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006224 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006225 }
6226 }
6227 }
6228
6229 /**
6230 * Called after virtual display Id is updated by
6231 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6232 * {@param vrVr2dDisplayId}.
6233 */
6234 @Override
6235 public void setVr2dDisplayId(int vr2dDisplayId) {
6236 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006238 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006239 }
6240 }
6241
6242 @Override
6243 public void setFocusedActivity(IBinder token) {
6244 synchronized (mGlobalLock) {
6245 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6246 if (r == null) {
6247 throw new IllegalArgumentException(
6248 "setFocusedActivity: No activity record matching token=" + token);
6249 }
Louis Chang19443452018-10-09 12:10:21 +08006250 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006251 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006252 }
6253 }
6254 }
6255
6256 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006257 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006258 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 }
6260
6261 @Override
6262 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006263 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006264 }
6265
6266 @Override
6267 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006268 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 }
6270
6271 @Override
6272 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6273 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6274 }
6275
6276 @Override
6277 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006278 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006280
6281 @Override
6282 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6283 synchronized (mGlobalLock) {
6284 mActiveVoiceInteractionServiceComponent = component;
6285 }
6286 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006287
6288 @Override
6289 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6290 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6291 return;
6292 }
6293 synchronized (mGlobalLock) {
6294 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6295 if (types == null) {
6296 if (uid < 0) {
6297 return;
6298 }
6299 types = new ArrayMap<>();
6300 mAllowAppSwitchUids.put(userId, types);
6301 }
6302 if (uid < 0) {
6303 types.remove(type);
6304 } else {
6305 types.put(type, uid);
6306 }
6307 }
6308 }
6309
6310 @Override
6311 public void onUserStopped(int userId) {
6312 synchronized (mGlobalLock) {
6313 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6314 mAllowAppSwitchUids.remove(userId);
6315 }
6316 }
6317
6318 @Override
6319 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6320 synchronized (mGlobalLock) {
6321 return ActivityTaskManagerService.this.isGetTasksAllowed(
6322 caller, callingPid, callingUid);
6323 }
6324 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006325
Riddle Hsua0536432019-02-16 00:38:59 +08006326 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006327 @Override
6328 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006329 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006330 mProcessNames.put(proc.mName, proc.mUid, proc);
6331 }
6332 }
6333
Riddle Hsua0536432019-02-16 00:38:59 +08006334 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006335 @Override
6336 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006337 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006338 mProcessNames.remove(name, uid);
6339 }
6340 }
6341
Riddle Hsua0536432019-02-16 00:38:59 +08006342 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006343 @Override
6344 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006345 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006346 if (proc == mHomeProcess) {
6347 mHomeProcess = null;
6348 }
6349 if (proc == mPreviousProcess) {
6350 mPreviousProcess = null;
6351 }
6352 }
6353 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006354
Riddle Hsua0536432019-02-16 00:38:59 +08006355 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006356 @Override
6357 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006358 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006359 return mTopProcessState;
6360 }
6361 }
6362
Riddle Hsua0536432019-02-16 00:38:59 +08006363 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006364 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006365 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006366 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006367 return proc == mHeavyWeightProcess;
6368 }
6369 }
6370
Riddle Hsua0536432019-02-16 00:38:59 +08006371 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006372 @Override
6373 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006374 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006375 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6376 }
6377 }
6378
6379 @Override
6380 public void finishHeavyWeightApp() {
6381 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006382 if (mHeavyWeightProcess != null) {
6383 mHeavyWeightProcess.finishActivities();
6384 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006385 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6386 mHeavyWeightProcess);
6387 }
6388 }
6389
Riddle Hsua0536432019-02-16 00:38:59 +08006390 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006391 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006392 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006393 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006394 return isSleepingLocked();
6395 }
6396 }
6397
6398 @Override
6399 public boolean isShuttingDown() {
6400 synchronized (mGlobalLock) {
6401 return mShuttingDown;
6402 }
6403 }
6404
6405 @Override
6406 public boolean shuttingDown(boolean booted, int timeout) {
6407 synchronized (mGlobalLock) {
6408 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006409 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006410 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006411 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006412 return mStackSupervisor.shutdownLocked(timeout);
6413 }
6414 }
6415
6416 @Override
6417 public void enableScreenAfterBoot(boolean booted) {
6418 synchronized (mGlobalLock) {
6419 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6420 SystemClock.uptimeMillis());
6421 mWindowManager.enableScreenAfterBoot();
6422 updateEventDispatchingLocked(booted);
6423 }
6424 }
6425
6426 @Override
6427 public boolean showStrictModeViolationDialog() {
6428 synchronized (mGlobalLock) {
6429 return mShowDialogs && !mSleeping && !mShuttingDown;
6430 }
6431 }
6432
6433 @Override
6434 public void showSystemReadyErrorDialogsIfNeeded() {
6435 synchronized (mGlobalLock) {
6436 try {
6437 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6438 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6439 + " data partition or your device will be unstable.");
6440 mUiHandler.post(() -> {
6441 if (mShowDialogs) {
6442 AlertDialog d = new BaseErrorDialog(mUiContext);
6443 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6444 d.setCancelable(false);
6445 d.setTitle(mUiContext.getText(R.string.android_system_label));
6446 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6447 d.setButton(DialogInterface.BUTTON_POSITIVE,
6448 mUiContext.getText(R.string.ok),
6449 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6450 d.show();
6451 }
6452 });
6453 }
6454 } catch (RemoteException e) {
6455 }
6456
6457 if (!Build.isBuildConsistent()) {
6458 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6459 mUiHandler.post(() -> {
6460 if (mShowDialogs) {
6461 AlertDialog d = new BaseErrorDialog(mUiContext);
6462 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6463 d.setCancelable(false);
6464 d.setTitle(mUiContext.getText(R.string.android_system_label));
6465 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6466 d.setButton(DialogInterface.BUTTON_POSITIVE,
6467 mUiContext.getText(R.string.ok),
6468 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6469 d.show();
6470 }
6471 });
6472 }
6473 }
6474 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006475
6476 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006477 public void onProcessMapped(int pid, WindowProcessController proc) {
6478 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006479 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006480 }
6481 }
6482
6483 @Override
6484 public void onProcessUnMapped(int pid) {
6485 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006486 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006487 }
6488 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006489
6490 @Override
6491 public void onPackageDataCleared(String name) {
6492 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006493 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006494 mAppWarnings.onPackageDataCleared(name);
6495 }
6496 }
6497
6498 @Override
6499 public void onPackageUninstalled(String name) {
6500 synchronized (mGlobalLock) {
6501 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006502 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006503 }
6504 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006505
6506 @Override
6507 public void onPackageAdded(String name, boolean replacing) {
6508 synchronized (mGlobalLock) {
6509 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6510 }
6511 }
6512
6513 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006514 public void onPackageReplaced(ApplicationInfo aInfo) {
6515 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006516 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006517 }
6518 }
6519
6520 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006521 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6522 synchronized (mGlobalLock) {
6523 return compatibilityInfoForPackageLocked(ai);
6524 }
6525 }
6526
Yunfan Chen75157d72018-07-27 14:47:21 +09006527 /**
6528 * Set the corresponding display information for the process global configuration. To be
6529 * called when we need to show IME on a different display.
6530 *
6531 * @param pid The process id associated with the IME window.
6532 * @param displayId The ID of the display showing the IME.
6533 */
6534 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006535 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006536 // Don't update process-level configuration for Multi-Client IME process since other
6537 // IMEs on other displays will also receive this configuration change due to IME
6538 // services use the same application config/context.
6539 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006540
Yunfan Chen75157d72018-07-27 14:47:21 +09006541 if (pid == MY_PID || pid < 0) {
6542 if (DEBUG_CONFIGURATION) {
6543 Slog.w(TAG,
6544 "Trying to update display configuration for system/invalid process.");
6545 }
6546 return;
6547 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006548 synchronized (mGlobalLock) {
6549 final ActivityDisplay activityDisplay =
6550 mRootActivityContainer.getActivityDisplay(displayId);
6551 if (activityDisplay == null) {
6552 // Call might come when display is not yet added or has been removed.
6553 if (DEBUG_CONFIGURATION) {
6554 Slog.w(TAG, "Trying to update display configuration for non-existing "
6555 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006556 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006557 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006558 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006559 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006560 if (process == null) {
6561 if (DEBUG_CONFIGURATION) {
6562 Slog.w(TAG, "Trying to update display configuration for invalid "
6563 + "process, pid=" + pid);
6564 }
6565 return;
6566 }
6567 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6568 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006569 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006570
6571 @Override
6572 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6573 int requestCode, int resultCode, Intent data) {
6574 synchronized (mGlobalLock) {
6575 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006576 if (r != null && r.getActivityStack() != null) {
6577 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6578 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006579 }
6580 }
6581 }
6582
6583 @Override
6584 public void clearPendingResultForActivity(IBinder activityToken,
6585 WeakReference<PendingIntentRecord> pir) {
6586 synchronized (mGlobalLock) {
6587 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6588 if (r != null && r.pendingResults != null) {
6589 r.pendingResults.remove(pir);
6590 }
6591 }
6592 }
6593
6594 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006595 public ActivityTokens getTopActivityForTask(int taskId) {
6596 synchronized (mGlobalLock) {
6597 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6598 if (taskRecord == null) {
6599 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6600 + " Requested task not found");
6601 return null;
6602 }
6603 final ActivityRecord activity = taskRecord.getTopActivity();
6604 if (activity == null) {
6605 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6606 + " Requested activity not found");
6607 return null;
6608 }
6609 if (!activity.attachedToProcess()) {
6610 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6611 + activity);
6612 return null;
6613 }
6614 return new ActivityTokens(activity.appToken, activity.assistToken,
6615 activity.app.getThread());
6616 }
6617 }
6618
6619 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006620 public IIntentSender getIntentSender(int type, String packageName,
6621 int callingUid, int userId, IBinder token, String resultWho,
6622 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6623 Bundle bOptions) {
6624 synchronized (mGlobalLock) {
6625 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6626 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6627 }
6628 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006629
6630 @Override
6631 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6632 synchronized (mGlobalLock) {
6633 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6634 if (r == null) {
6635 return null;
6636 }
6637 if (r.mServiceConnectionsHolder == null) {
6638 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6639 ActivityTaskManagerService.this, r);
6640 }
6641
6642 return r.mServiceConnectionsHolder;
6643 }
6644 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006645
6646 @Override
6647 public Intent getHomeIntent() {
6648 synchronized (mGlobalLock) {
6649 return ActivityTaskManagerService.this.getHomeIntent();
6650 }
6651 }
6652
6653 @Override
6654 public boolean startHomeActivity(int userId, String reason) {
6655 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006656 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006657 }
6658 }
6659
6660 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006661 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006662 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006663 synchronized (mGlobalLock) {
6664 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006665 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006666 }
Chilun8b1f1be2019-03-13 17:14:36 +08006667 }
6668
6669 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006670 public boolean startHomeOnAllDisplays(int userId, String reason) {
6671 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006672 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006673 }
6674 }
6675
Riddle Hsua0536432019-02-16 00:38:59 +08006676 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006677 @Override
6678 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006679 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006680 if (mFactoryTest == FACTORY_TEST_OFF) {
6681 return false;
6682 }
6683 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6684 && wpc.mName.equals(mTopComponent.getPackageName())) {
6685 return true;
6686 }
6687 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6688 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6689 }
6690 }
6691
6692 @Override
6693 public void updateTopComponentForFactoryTest() {
6694 synchronized (mGlobalLock) {
6695 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6696 return;
6697 }
6698 final ResolveInfo ri = mContext.getPackageManager()
6699 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6700 final CharSequence errorMsg;
6701 if (ri != null) {
6702 final ActivityInfo ai = ri.activityInfo;
6703 final ApplicationInfo app = ai.applicationInfo;
6704 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6705 mTopAction = Intent.ACTION_FACTORY_TEST;
6706 mTopData = null;
6707 mTopComponent = new ComponentName(app.packageName, ai.name);
6708 errorMsg = null;
6709 } else {
6710 errorMsg = mContext.getResources().getText(
6711 com.android.internal.R.string.factorytest_not_system);
6712 }
6713 } else {
6714 errorMsg = mContext.getResources().getText(
6715 com.android.internal.R.string.factorytest_no_action);
6716 }
6717 if (errorMsg == null) {
6718 return;
6719 }
6720
6721 mTopAction = null;
6722 mTopData = null;
6723 mTopComponent = null;
6724 mUiHandler.post(() -> {
6725 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6726 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006727 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006728 });
6729 }
6730 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731
Riddle Hsua0536432019-02-16 00:38:59 +08006732 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006733 @Override
6734 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6735 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006736 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006738 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006739
6740 wpc.clearRecentTasks();
6741 wpc.clearActivities();
6742
6743 if (wpc.isInstrumenting()) {
6744 finishInstrumentationCallback.run();
6745 }
6746
Jorim Jaggid0752812018-10-16 16:07:20 +02006747 if (!restarting && hasVisibleActivities) {
6748 mWindowManager.deferSurfaceLayout();
6749 try {
6750 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6751 // If there was nothing to resume, and we are not already restarting
6752 // this process, but there is a visible activity that is hosted by the
6753 // process...then make sure all visible activities are running, taking
6754 // care of restarting this process.
6755 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6756 !PRESERVE_WINDOWS);
6757 }
6758 } finally {
6759 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006760 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 }
6762 }
6763 }
6764
6765 @Override
6766 public void closeSystemDialogs(String reason) {
6767 enforceNotIsolatedCaller("closeSystemDialogs");
6768
6769 final int pid = Binder.getCallingPid();
6770 final int uid = Binder.getCallingUid();
6771 final long origId = Binder.clearCallingIdentity();
6772 try {
6773 synchronized (mGlobalLock) {
6774 // Only allow this from foreground processes, so that background
6775 // applications can't abuse it to prevent system UI from being shown.
6776 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006777 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 if (!proc.isPerceptible()) {
6779 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6780 + " from background process " + proc);
6781 return;
6782 }
6783 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 mWindowManager.closeSystemDialogs(reason);
6785
Wale Ogunwaled32da472018-11-16 07:19:28 -08006786 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006788 // Call into AM outside the synchronized block.
6789 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 } finally {
6791 Binder.restoreCallingIdentity(origId);
6792 }
6793 }
6794
6795 @Override
6796 public void cleanupDisabledPackageComponents(
6797 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6798 synchronized (mGlobalLock) {
6799 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006800 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006802 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 mStackSupervisor.scheduleIdleLocked();
6804 }
6805
6806 // Clean-up disabled tasks
6807 getRecentTasks().cleanupDisabledPackageTasksLocked(
6808 packageName, disabledClasses, userId);
6809 }
6810 }
6811
6812 @Override
6813 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6814 int userId) {
6815 synchronized (mGlobalLock) {
6816
6817 boolean didSomething =
6818 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006819 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 null, doit, evenPersistent, userId);
6821 return didSomething;
6822 }
6823 }
6824
6825 @Override
6826 public void resumeTopActivities(boolean scheduleIdle) {
6827 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006828 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 if (scheduleIdle) {
6830 mStackSupervisor.scheduleIdleLocked();
6831 }
6832 }
6833 }
6834
Riddle Hsua0536432019-02-16 00:38:59 +08006835 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 @Override
6837 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006838 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6840 }
6841 }
6842
Riddle Hsua0536432019-02-16 00:38:59 +08006843 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844 @Override
6845 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006846 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006847 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 }
6849 }
6850
6851 @Override
6852 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6853 try {
6854 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6855 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6856 }
6857 } catch (RemoteException ex) {
6858 throw new SecurityException("Fail to check is caller a privileged app", ex);
6859 }
6860
6861 synchronized (mGlobalLock) {
6862 final long ident = Binder.clearCallingIdentity();
6863 try {
6864 if (mAmInternal.shouldConfirmCredentials(userId)) {
6865 if (mKeyguardController.isKeyguardLocked()) {
6866 // Showing launcher to avoid user entering credential twice.
6867 startHomeActivity(currentUserId, "notifyLockedProfile");
6868 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006869 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 }
6871 } finally {
6872 Binder.restoreCallingIdentity(ident);
6873 }
6874 }
6875 }
6876
6877 @Override
6878 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6879 mAmInternal.enforceCallingPermission(
6880 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6881
6882 synchronized (mGlobalLock) {
6883 final long ident = Binder.clearCallingIdentity();
6884 try {
6885 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6886 FLAG_ACTIVITY_TASK_ON_HOME);
6887 ActivityOptions activityOptions = options != null
6888 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006889 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006890 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006891 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006892 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006893 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6895 UserHandle.CURRENT);
6896 } finally {
6897 Binder.restoreCallingIdentity(ident);
6898 }
6899 }
6900 }
6901
6902 @Override
6903 public void writeActivitiesToProto(ProtoOutputStream proto) {
6904 synchronized (mGlobalLock) {
6905 // The output proto of "activity --proto activities"
6906 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006907 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006908 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6909 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006910 }
6911 }
6912
6913 @Override
6914 public void saveANRState(String reason) {
6915 synchronized (mGlobalLock) {
6916 final StringWriter sw = new StringWriter();
6917 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6918 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6919 if (reason != null) {
6920 pw.println(" Reason: " + reason);
6921 }
6922 pw.println();
6923 getActivityStartController().dump(pw, " ", null);
6924 pw.println();
6925 pw.println("-------------------------------------------------------------------------------");
6926 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6927 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6928 "" /* header */);
6929 pw.println();
6930 pw.close();
6931
6932 mLastANRState = sw.toString();
6933 }
6934 }
6935
6936 @Override
6937 public void clearSavedANRState() {
6938 synchronized (mGlobalLock) {
6939 mLastANRState = null;
6940 }
6941 }
6942
6943 @Override
6944 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6945 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6946 synchronized (mGlobalLock) {
6947 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6948 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6949 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6950 dumpLastANRLocked(pw);
6951 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6952 dumpLastANRTracesLocked(pw);
6953 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6954 dumpActivityStarterLocked(pw, dumpPackage);
6955 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6956 dumpActivityContainersLocked(pw);
6957 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6958 if (getRecentTasks() != null) {
6959 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6960 }
6961 }
6962 }
6963 }
6964
6965 @Override
6966 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6967 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6968 int wakefulness) {
6969 synchronized (mGlobalLock) {
6970 if (mHomeProcess != null && (dumpPackage == null
6971 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6972 if (needSep) {
6973 pw.println();
6974 needSep = false;
6975 }
6976 pw.println(" mHomeProcess: " + mHomeProcess);
6977 }
6978 if (mPreviousProcess != null && (dumpPackage == null
6979 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6980 if (needSep) {
6981 pw.println();
6982 needSep = false;
6983 }
6984 pw.println(" mPreviousProcess: " + mPreviousProcess);
6985 }
6986 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6987 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6988 StringBuilder sb = new StringBuilder(128);
6989 sb.append(" mPreviousProcessVisibleTime: ");
6990 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6991 pw.println(sb);
6992 }
6993 if (mHeavyWeightProcess != null && (dumpPackage == null
6994 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6995 if (needSep) {
6996 pw.println();
6997 needSep = false;
6998 }
6999 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7000 }
7001 if (dumpPackage == null) {
7002 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007003 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007004 }
7005 if (dumpAll) {
7006 if (dumpPackage == null) {
7007 pw.println(" mConfigWillChange: "
7008 + getTopDisplayFocusedStack().mConfigWillChange);
7009 }
7010 if (mCompatModePackages.getPackages().size() > 0) {
7011 boolean printed = false;
7012 for (Map.Entry<String, Integer> entry
7013 : mCompatModePackages.getPackages().entrySet()) {
7014 String pkg = entry.getKey();
7015 int mode = entry.getValue();
7016 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7017 continue;
7018 }
7019 if (!printed) {
7020 pw.println(" mScreenCompatPackages:");
7021 printed = true;
7022 }
7023 pw.println(" " + pkg + ": " + mode);
7024 }
7025 }
7026 }
7027
7028 if (dumpPackage == null) {
7029 pw.println(" mWakefulness="
7030 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007031 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007032 if (mRunningVoice != null) {
7033 pw.println(" mRunningVoice=" + mRunningVoice);
7034 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7035 }
7036 pw.println(" mSleeping=" + mSleeping);
7037 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7038 pw.println(" mVrController=" + mVrController);
7039 }
7040 if (mCurAppTimeTracker != null) {
7041 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7042 }
7043 if (mAllowAppSwitchUids.size() > 0) {
7044 boolean printed = false;
7045 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7046 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7047 for (int j = 0; j < types.size(); j++) {
7048 if (dumpPackage == null ||
7049 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7050 if (needSep) {
7051 pw.println();
7052 needSep = false;
7053 }
7054 if (!printed) {
7055 pw.println(" mAllowAppSwitchUids:");
7056 printed = true;
7057 }
7058 pw.print(" User ");
7059 pw.print(mAllowAppSwitchUids.keyAt(i));
7060 pw.print(": Type ");
7061 pw.print(types.keyAt(j));
7062 pw.print(" = ");
7063 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7064 pw.println();
7065 }
7066 }
7067 }
7068 }
7069 if (dumpPackage == null) {
7070 if (mController != null) {
7071 pw.println(" mController=" + mController
7072 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7073 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007074 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7075 pw.println(" mLaunchingActivityWakeLock="
7076 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 }
7078
7079 return needSep;
7080 }
7081 }
7082
7083 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007084 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7085 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007086 synchronized (mGlobalLock) {
7087 if (dumpPackage == null) {
7088 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7089 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007090 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7091 if (mRunningVoice != null) {
7092 final long vrToken = proto.start(
7093 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7094 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7095 mRunningVoice.toString());
7096 mVoiceWakeLock.writeToProto(
7097 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7098 proto.end(vrToken);
7099 }
7100 mVrController.writeToProto(proto,
7101 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 if (mController != null) {
7103 final long token = proto.start(CONTROLLER);
7104 proto.write(CONTROLLER, mController.toString());
7105 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7106 proto.end(token);
7107 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007108 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7109 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7110 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007111 }
7112
7113 if (mHomeProcess != null && (dumpPackage == null
7114 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007115 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007116 }
7117
7118 if (mPreviousProcess != null && (dumpPackage == null
7119 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007120 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7122 }
7123
7124 if (mHeavyWeightProcess != null && (dumpPackage == null
7125 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007126 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128
7129 for (Map.Entry<String, Integer> entry
7130 : mCompatModePackages.getPackages().entrySet()) {
7131 String pkg = entry.getKey();
7132 int mode = entry.getValue();
7133 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7134 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7135 proto.write(PACKAGE, pkg);
7136 proto.write(MODE, mode);
7137 proto.end(compatToken);
7138 }
7139 }
7140
7141 if (mCurAppTimeTracker != null) {
7142 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7143 }
7144
7145 }
7146 }
7147
7148 @Override
7149 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7150 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7151 boolean dumpFocusedStackOnly) {
7152 synchronized (mGlobalLock) {
7153 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7154 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7155 }
7156 }
7157
7158 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007159 public void dumpForOom(PrintWriter pw) {
7160 synchronized (mGlobalLock) {
7161 pw.println(" mHomeProcess: " + mHomeProcess);
7162 pw.println(" mPreviousProcess: " + mPreviousProcess);
7163 if (mHeavyWeightProcess != null) {
7164 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7165 }
7166 }
7167 }
7168
7169 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 public boolean canGcNow() {
7171 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007172 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007173 }
7174 }
7175
Riddle Hsua0536432019-02-16 00:38:59 +08007176 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007177 @Override
7178 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007179 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007180 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 return top != null ? top.app : null;
7182 }
7183 }
7184
Riddle Hsua0536432019-02-16 00:38:59 +08007185 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007186 @Override
7187 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007188 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007189 if (mRootActivityContainer != null) {
7190 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 }
7192 }
7193 }
7194
7195 @Override
7196 public void scheduleDestroyAllActivities(String reason) {
7197 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007198 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007199 }
7200 }
7201
7202 @Override
7203 public void removeUser(int userId) {
7204 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007205 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 }
7207 }
7208
7209 @Override
7210 public boolean switchUser(int userId, UserState userState) {
7211 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007212 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007213 }
7214 }
7215
7216 @Override
7217 public void onHandleAppCrash(WindowProcessController wpc) {
7218 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007219 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007220 }
7221 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007222
7223 @Override
7224 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7225 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007226 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007227 }
7228 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007229
Riddle Hsua0536432019-02-16 00:38:59 +08007230 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007231 @Override
7232 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007233 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007234 }
7235
Riddle Hsua0536432019-02-16 00:38:59 +08007236 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007237 @Override
7238 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007239 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007240 }
7241
Riddle Hsua0536432019-02-16 00:38:59 +08007242 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007243 @Override
7244 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007245 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007246 }
7247
Riddle Hsua0536432019-02-16 00:38:59 +08007248 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007249 @Override
7250 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007251 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007252 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007253
7254 @Override
7255 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007256 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007257 mPendingTempWhitelist.put(uid, tag);
7258 }
7259 }
7260
7261 @Override
7262 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007263 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007264 mPendingTempWhitelist.remove(uid);
7265 }
7266 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007267
7268 @Override
7269 public boolean handleAppCrashInActivityController(String processName, int pid,
7270 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7271 Runnable killCrashingAppCallback) {
7272 synchronized (mGlobalLock) {
7273 if (mController == null) {
7274 return false;
7275 }
7276
7277 try {
7278 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7279 stackTrace)) {
7280 killCrashingAppCallback.run();
7281 return true;
7282 }
7283 } catch (RemoteException e) {
7284 mController = null;
7285 Watchdog.getInstance().setActivityController(null);
7286 }
7287 return false;
7288 }
7289 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007290
7291 @Override
7292 public void removeRecentTasksByPackageName(String packageName, int userId) {
7293 synchronized (mGlobalLock) {
7294 mRecentTasks.removeTasksByPackageName(packageName, userId);
7295 }
7296 }
7297
7298 @Override
7299 public void cleanupRecentTasksForUser(int userId) {
7300 synchronized (mGlobalLock) {
7301 mRecentTasks.cleanupLocked(userId);
7302 }
7303 }
7304
7305 @Override
7306 public void loadRecentTasksForUser(int userId) {
7307 synchronized (mGlobalLock) {
7308 mRecentTasks.loadUserRecentsLocked(userId);
7309 }
7310 }
7311
7312 @Override
7313 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7314 synchronized (mGlobalLock) {
7315 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7316 }
7317 }
7318
7319 @Override
7320 public void flushRecentTasks() {
7321 mRecentTasks.flush();
7322 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007323
7324 @Override
7325 public WindowProcessController getHomeProcess() {
7326 synchronized (mGlobalLock) {
7327 return mHomeProcess;
7328 }
7329 }
7330
7331 @Override
7332 public WindowProcessController getPreviousProcess() {
7333 synchronized (mGlobalLock) {
7334 return mPreviousProcess;
7335 }
7336 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007337
7338 @Override
7339 public void clearLockedTasks(String reason) {
7340 synchronized (mGlobalLock) {
7341 getLockTaskController().clearLockedTasks(reason);
7342 }
7343 }
7344
7345 @Override
7346 public void updateUserConfiguration() {
7347 synchronized (mGlobalLock) {
7348 final Configuration configuration = new Configuration(getGlobalConfiguration());
7349 final int currentUserId = mAmInternal.getCurrentUserId();
7350 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7351 configuration, currentUserId, Settings.System.canWrite(mContext));
7352 updateConfigurationLocked(configuration, null /* starting */,
7353 false /* initLocale */, false /* persistent */, currentUserId,
7354 false /* deferResume */);
7355 }
7356 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007357
7358 @Override
7359 public boolean canShowErrorDialogs() {
7360 synchronized (mGlobalLock) {
7361 return mShowDialogs && !mSleeping && !mShuttingDown
7362 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7363 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7364 mAmInternal.getCurrentUserId())
7365 && !(UserManager.isDeviceInDemoMode(mContext)
7366 && mAmInternal.getCurrentUser().isDemo());
7367 }
7368 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007369
7370 @Override
7371 public void setProfileApp(String profileApp) {
7372 synchronized (mGlobalLock) {
7373 mProfileApp = profileApp;
7374 }
7375 }
7376
7377 @Override
7378 public void setProfileProc(WindowProcessController wpc) {
7379 synchronized (mGlobalLock) {
7380 mProfileProc = wpc;
7381 }
7382 }
7383
7384 @Override
7385 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7386 synchronized (mGlobalLock) {
7387 mProfilerInfo = profilerInfo;
7388 }
7389 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007390
7391 @Override
7392 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7393 synchronized (mGlobalLock) {
7394 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7395 }
7396 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007397
7398 @Override
7399 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7400 synchronized (mGlobalLock) {
7401 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7402 }
7403 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007404
7405 @Override
7406 public boolean isUidForeground(int uid) {
7407 synchronized (mGlobalLock) {
7408 return ActivityTaskManagerService.this.isUidForeground(uid);
7409 }
7410 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007411
7412 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007413 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007414 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007415 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007416 }
7417 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007418
7419 @Override
7420 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007421 // Translate package names into UIDs
7422 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007423 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007424 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7425 if (uid >= 0) {
7426 result.add(uid);
7427 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007428 }
7429 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007430 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007431 }
7432 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007433 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007434}