blob: 772e5e646825e6450766284e8e86fac6ed5d0421 [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 Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import 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;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800350 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800351 @VisibleForTesting
352 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 PowerManagerInternal mPowerManagerInternal;
354 private UsageStatsManagerInternal mUsageStatsInternal;
355
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700356 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 IntentFirewall mIntentFirewall;
358
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700359 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800360 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800361 /**
362 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
363 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
364 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
365 *
366 * @see WindowManagerThreadPriorityBooster
367 */
368 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700369 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800370 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700371 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700372 private UserManagerService mUserManager;
373 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700374 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800375 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700376 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /** All processes currently running that might have a window organized by name. */
378 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100379 /** All processes we currently have running mapped by pid and uid */
380 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** This is the process holding what we currently consider to be the "home" activity. */
382 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700383 /** The currently running heavy-weight process, if any. */
384 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700385 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /**
387 * This is the process holding the activity the user last visited that is in a different process
388 * from the one they are currently in.
389 */
390 WindowProcessController mPreviousProcess;
391 /** The time at which the previous process was last visible. */
392 long mPreviousProcessVisibleTime;
393
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700394 /** List of intents that were used to start the most recent tasks. */
395 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700396 /** State of external calls telling us if the device is awake or asleep. */
397 private boolean mKeyguardShown = false;
398
399 // Wrapper around VoiceInteractionServiceManager
400 private AssistUtils mAssistUtils;
401
402 // VoiceInteraction session ID that changes for each new request except when
403 // being called for multi-window assist in a single session.
404 private int mViSessionId = 1000;
405
406 // How long to wait in getAssistContextExtras for the activity and foreground services
407 // to respond with the result.
408 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
409
410 // How long top wait when going through the modern assist (which doesn't need to block
411 // on getting this result before starting to launch its UI).
412 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
413
414 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
415 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
416
Alison Cichowlas3e340502018-08-07 17:15:01 -0400417 // Permission tokens are used to temporarily granted a trusted app the ability to call
418 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
419 // showing any appropriate error messages to the user.
420 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
421 10 * MINUTE_IN_MILLIS;
422
423 // How long before the service actually expires a token. This is slightly longer than
424 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
425 // expiration exception.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
427 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
428
429 // How long the service will remember expired tokens, for the purpose of providing error
430 // messaging when a client uses an expired token.
431 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
432 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
433
Marvin Ramin830d4e32019-03-12 13:16:58 +0100434 // How long to whitelist the Services for when requested.
435 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
436
Alison Cichowlas3e340502018-08-07 17:15:01 -0400437 // Activity tokens of system activities that are delegating their call to
438 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
439 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
440
441 // Permission tokens that have expired, but we remember for error reporting.
442 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
443
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700444 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
445
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700446 // Keeps track of the active voice interaction service component, notified from
447 // VoiceInteractionManagerService
448 ComponentName mActiveVoiceInteractionServiceComponent;
449
Michal Karpinskida34cd42019-04-02 19:46:52 +0100450 // A map userId and all its companion app uids
451 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000452
Wale Ogunwalee2172292018-10-25 10:11:10 -0700453 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 KeyguardController mKeyguardController;
455 private final ClientLifecycleManager mLifecycleManager;
456 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700457 /** The controller for all operations related to locktask. */
458 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700459 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700461 boolean mSuppressResizeConfigChanges;
462
463 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
464 new UpdateConfigurationResult();
465
466 static final class UpdateConfigurationResult {
467 // Configuration changes that were updated.
468 int changes;
469 // If the activity was relaunched to match the new configuration.
470 boolean activityRelaunched;
471
472 void reset() {
473 changes = 0;
474 activityRelaunched = false;
475 }
476 }
477
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700478 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 private int mConfigurationSeq;
480 // To cache the list of supported system locales
481 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482
483 /**
484 * Temp object used when global and/or display override configuration is updated. It is also
485 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
486 * anyone...
487 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private Configuration mTempConfig = new Configuration();
489
Wale Ogunwalef6733932018-06-27 05:14:34 -0700490 /** Temporary to avoid allocations. */
491 final StringBuilder mStringBuilder = new StringBuilder(256);
492
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 // Amount of time after a call to stopAppSwitches() during which we will
494 // prevent further untrusted switches from happening.
495 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
496
497 /**
498 * The time at which we will allow normal application switches again,
499 * after a call to {@link #stopAppSwitches()}.
500 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
503 * This is set to true after the first switch after mAppSwitchesAllowedTime
504 * is set; any switches after that will clear the time.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507
508 IActivityController mController = null;
509 boolean mControllerIsAMonkey = false;
510
Wale Ogunwale214f3482018-10-04 11:00:47 -0700511 final int mFactoryTest;
512
513 /** Used to control how we initialize the service. */
514 ComponentName mTopComponent;
515 String mTopAction = Intent.ACTION_MAIN;
516 String mTopData;
517
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800518 /** Profiling app information. */
519 String mProfileApp = null;
520 WindowProcessController mProfileProc = null;
521 ProfilerInfo mProfilerInfo = null;
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700524 * Dump of the activity state at the time of the last ANR. Cleared after
525 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
526 */
527 String mLastANRState;
528
529 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530 * Used to retain an update lock when the foreground activity is in
531 * immersive mode.
532 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700533 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534
535 /**
536 * Packages that are being allowed to perform unrestricted app switches. Mapping is
537 * User -> Type -> uid.
538 */
539 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
540
541 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private int mThumbnailWidth;
543 private int mThumbnailHeight;
544 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Flag that indicates if multi-window is enabled.
548 *
549 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
550 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
551 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
552 * At least one of the forms of multi-window must be enabled in order for this flag to be
553 * initialized to 'true'.
554 *
555 * @see #mSupportsSplitScreenMultiWindow
556 * @see #mSupportsFreeformWindowManagement
557 * @see #mSupportsPictureInPicture
558 * @see #mSupportsMultiDisplay
559 */
560 boolean mSupportsMultiWindow;
561 boolean mSupportsSplitScreenMultiWindow;
562 boolean mSupportsFreeformWindowManagement;
563 boolean mSupportsPictureInPicture;
564 boolean mSupportsMultiDisplay;
565 boolean mForceResizableActivities;
566
567 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
568
569 // VR Vr2d Display Id.
570 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700571
Wale Ogunwalef6733932018-06-27 05:14:34 -0700572 /**
573 * Set while we are wanting to sleep, to prevent any
574 * activities from being started/resumed.
575 *
576 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
577 *
578 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
579 * while in the sleep state until there is a pending transition out of sleep, in which case
580 * mSleeping is set to false, and remains false while awake.
581 *
582 * Whether mSleeping can quickly toggled between true/false without the device actually
583 * display changing states is undefined.
584 */
585 private boolean mSleeping = false;
586
587 /**
588 * The process state used for processes that are running the top activities.
589 * This changes between TOP and TOP_SLEEPING to following mSleeping.
590 */
591 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
592
593 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
594 // automatically. Important for devices without direct input devices.
595 private boolean mShowDialogs = true;
596
597 /** Set if we are shutting down the system, similar to sleeping. */
598 boolean mShuttingDown = false;
599
600 /**
601 * We want to hold a wake lock while running a voice interaction session, since
602 * this may happen with the screen off and we need to keep the CPU running to
603 * be able to continue to interact with the user.
604 */
605 PowerManager.WakeLock mVoiceWakeLock;
606
607 /**
608 * Set while we are running a voice interaction. This overrides sleeping while it is active.
609 */
610 IVoiceInteractionSession mRunningVoice;
611
612 /**
613 * The last resumed activity. This is identical to the current resumed activity most
614 * of the time but could be different when we're pausing one activity before we resume
615 * another activity.
616 */
617 ActivityRecord mLastResumedActivity;
618
619 /**
620 * The activity that is currently being traced as the active resumed activity.
621 *
622 * @see #updateResumedAppTrace
623 */
624 private @Nullable ActivityRecord mTracedResumedActivity;
625
626 /** If non-null, we are tracking the time the user spends in the currently focused app. */
627 AppTimeTracker mCurAppTimeTracker;
628
Wale Ogunwale008163e2018-07-23 23:11:08 -0700629 private AppWarnings mAppWarnings;
630
Wale Ogunwale53783742018-09-16 10:21:51 -0700631 /**
632 * Packages that the user has asked to have run in screen size
633 * compatibility mode instead of filling the screen.
634 */
635 CompatModePackages mCompatModePackages;
636
Wale Ogunwalef6733932018-06-27 05:14:34 -0700637 private FontScaleSettingObserver mFontScaleSettingObserver;
638
Ricky Wai96f5c352019-04-10 18:40:17 +0100639 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000640
Wale Ogunwalef6733932018-06-27 05:14:34 -0700641 private final class FontScaleSettingObserver extends ContentObserver {
642 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
643 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
644
645 public FontScaleSettingObserver() {
646 super(mH);
647 final ContentResolver resolver = mContext.getContentResolver();
648 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
649 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
650 UserHandle.USER_ALL);
651 }
652
653 @Override
654 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
655 if (mFontScaleUri.equals(uri)) {
656 updateFontScaleIfNeeded(userId);
657 } else if (mHideErrorDialogsUri.equals(uri)) {
658 synchronized (mGlobalLock) {
659 updateShouldShowDialogsLocked(getGlobalConfiguration());
660 }
661 }
662 }
663 }
664
Riddle Hsua0536432019-02-16 00:38:59 +0800665 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
666 @Target(ElementType.METHOD)
667 @Retention(RetentionPolicy.SOURCE)
668 @interface HotPath {
669 int NONE = 0;
670 int OOM_ADJUSTMENT = 1;
671 int LRU_UPDATE = 2;
672 int PROCESS_CHANGE = 3;
673 int caller() default NONE;
674 }
675
Charles Chen8d98dd22018-12-26 17:36:54 +0800676 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
677 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700678 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700679 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700680 mSystemThread = ActivityThread.currentActivityThread();
681 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700682 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800683 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700684 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700685 }
686
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700687 public void onSystemReady() {
688 synchronized (mGlobalLock) {
689 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
690 PackageManager.FEATURE_CANT_SAVE_STATE);
691 mAssistUtils = new AssistUtils(mContext);
692 mVrController.onSystemReady();
693 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700694 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700696 }
697
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700698 public void onInitPowerManagement() {
699 synchronized (mGlobalLock) {
700 mStackSupervisor.initPowerManagement();
701 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
702 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
703 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
704 mVoiceWakeLock.setReferenceCounted(false);
705 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700706 }
707
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700708 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700709 mFontScaleSettingObserver = new FontScaleSettingObserver();
710 }
711
Wale Ogunwale59507092018-10-29 09:00:30 -0700712 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700713 final boolean freeformWindowManagement =
714 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
715 || Settings.Global.getInt(
716 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
717
718 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
719 final boolean supportsPictureInPicture = supportsMultiWindow &&
720 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
721 final boolean supportsSplitScreenMultiWindow =
722 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
723 final boolean supportsMultiDisplay = mContext.getPackageManager()
724 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
726 final boolean forceResizable = Settings.Global.getInt(
727 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700728 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729
730 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900731 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732
733 final Configuration configuration = new Configuration();
734 Settings.System.getConfiguration(resolver, configuration);
735 if (forceRtl) {
736 // This will take care of setting the correct layout direction flags
737 configuration.setLayoutDirection(configuration.locale);
738 }
739
740 synchronized (mGlobalLock) {
741 mForceResizableActivities = forceResizable;
742 final boolean multiWindowFormEnabled = freeformWindowManagement
743 || supportsSplitScreenMultiWindow
744 || supportsPictureInPicture
745 || supportsMultiDisplay;
746 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
747 mSupportsMultiWindow = true;
748 mSupportsFreeformWindowManagement = freeformWindowManagement;
749 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
750 mSupportsPictureInPicture = supportsPictureInPicture;
751 mSupportsMultiDisplay = supportsMultiDisplay;
752 } else {
753 mSupportsMultiWindow = false;
754 mSupportsFreeformWindowManagement = false;
755 mSupportsSplitScreenMultiWindow = false;
756 mSupportsPictureInPicture = false;
757 mSupportsMultiDisplay = false;
758 }
759 mWindowManager.setForceResizableTasks(mForceResizableActivities);
760 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700761 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
762 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700763 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 // This happens before any activities are started, so we can change global configuration
765 // in-place.
766 updateConfigurationLocked(configuration, null, true);
767 final Configuration globalConfig = getGlobalConfiguration();
768 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
769
770 // Load resources only after the current configuration has been set.
771 final Resources res = mContext.getResources();
772 mThumbnailWidth = res.getDimensionPixelSize(
773 com.android.internal.R.dimen.thumbnail_width);
774 mThumbnailHeight = res.getDimensionPixelSize(
775 com.android.internal.R.dimen.thumbnail_height);
776
777 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
778 mFullscreenThumbnailScale = (float) res
779 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
780 (float) globalConfig.screenWidthDp;
781 } else {
782 mFullscreenThumbnailScale = res.getFraction(
783 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
784 }
785 }
786 }
787
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800788 public WindowManagerGlobalLock getGlobalLock() {
789 return mGlobalLock;
790 }
791
Yunfan Chen585f2932019-01-29 16:04:45 +0900792 /** For test purpose only. */
793 @VisibleForTesting
794 public ActivityTaskManagerInternal getAtmInternal() {
795 return mInternal;
796 }
797
Riddle Hsud93a6c42018-11-29 21:50:06 +0800798 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
799 Looper looper) {
800 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700802 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700803 final File systemDir = SystemServiceManager.ensureSystemDir();
804 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
805 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700806 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700807
808 mTempConfig.setToDefaults();
809 mTempConfig.setLocales(LocaleList.getDefault());
810 mConfigurationSeq = mTempConfig.seq = 1;
811 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800812 mRootActivityContainer = new RootActivityContainer(this);
813 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700814
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700816 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700817 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700819 mRecentTasks = createRecentTasks();
820 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700822 mKeyguardController = mStackSupervisor.getKeyguardController();
823 }
824
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700825 public void onActivityManagerInternalAdded() {
826 synchronized (mGlobalLock) {
827 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
828 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
829 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700830 }
831
Yunfan Chen75157d72018-07-27 14:47:21 +0900832 int increaseConfigurationSeqLocked() {
833 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
834 return mConfigurationSeq;
835 }
836
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 protected ActivityStackSupervisor createStackSupervisor() {
838 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
839 supervisor.initialize();
840 return supervisor;
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void setWindowManager(WindowManagerService wm) {
844 synchronized (mGlobalLock) {
845 mWindowManager = wm;
846 mLockTaskController.setWindowManager(wm);
847 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800848 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
853 synchronized (mGlobalLock) {
854 mUsageStatsInternal = usageStatsManager;
855 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700856 }
857
Wale Ogunwalef6733932018-06-27 05:14:34 -0700858 UserManagerService getUserManager() {
859 if (mUserManager == null) {
860 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
861 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
862 }
863 return mUserManager;
864 }
865
866 AppOpsService getAppOpsService() {
867 if (mAppOpsService == null) {
868 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
869 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
870 }
871 return mAppOpsService;
872 }
873
874 boolean hasUserRestriction(String restriction, int userId) {
875 return getUserManager().hasUserRestriction(restriction, userId);
876 }
877
Michal Karpinski15486842019-04-25 17:33:42 +0100878 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
879 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
880 callingUid, callingPackage);
881 if (mode == AppOpsManager.MODE_DEFAULT) {
882 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
883 == PERMISSION_GRANTED;
884 }
885 return mode == AppOpsManager.MODE_ALLOWED;
886 }
887
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700888 protected RecentTasks createRecentTasks() {
889 return new RecentTasks(this, mStackSupervisor);
890 }
891
892 RecentTasks getRecentTasks() {
893 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700894 }
895
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700896 ClientLifecycleManager getLifecycleManager() {
897 return mLifecycleManager;
898 }
899
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700900 ActivityStartController getActivityStartController() {
901 return mActivityStartController;
902 }
903
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700904 TaskChangeNotificationController getTaskChangeNotificationController() {
905 return mTaskChangeNotificationController;
906 }
907
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700908 LockTaskController getLockTaskController() {
909 return mLockTaskController;
910 }
911
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 /**
913 * Return the global configuration used by the process corresponding to the input pid. This is
914 * usually the global configuration with some overrides specific to that process.
915 */
916 Configuration getGlobalConfigurationForCallingPid() {
917 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800918 return getGlobalConfigurationForPid(pid);
919 }
920
921 /**
922 * Return the global configuration used by the process corresponding to the given pid.
923 */
924 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900925 if (pid == MY_PID || pid < 0) {
926 return getGlobalConfiguration();
927 }
928 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100929 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 return app != null ? app.getConfiguration() : getGlobalConfiguration();
931 }
932 }
933
934 /**
935 * Return the device configuration info used by the process corresponding to the input pid.
936 * The value is consistent with the global configuration for the process.
937 */
938 @Override
939 public ConfigurationInfo getDeviceConfigurationInfo() {
940 ConfigurationInfo config = new ConfigurationInfo();
941 synchronized (mGlobalLock) {
942 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
943 config.reqTouchScreen = globalConfig.touchscreen;
944 config.reqKeyboardType = globalConfig.keyboard;
945 config.reqNavigation = globalConfig.navigation;
946 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
947 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
948 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
949 }
950 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
951 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
952 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
953 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700954 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 }
956 return config;
957 }
958
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700959 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700960 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 }
962
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700963 public static final class Lifecycle extends SystemService {
964 private final ActivityTaskManagerService mService;
965
966 public Lifecycle(Context context) {
967 super(context);
968 mService = new ActivityTaskManagerService(context);
969 }
970
971 @Override
972 public void onStart() {
973 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700974 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700975 }
976
Garfield Tan891146c2018-10-09 12:14:00 -0700977 @Override
978 public void onUnlockUser(int userId) {
979 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800980 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700981 }
982 }
983
984 @Override
985 public void onCleanupUser(int userId) {
986 synchronized (mService.getGlobalLock()) {
987 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
988 }
989 }
990
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700991 public ActivityTaskManagerService getService() {
992 return mService;
993 }
994 }
995
996 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997 public final int startActivity(IApplicationThread caller, String callingPackage,
998 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
999 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1000 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1001 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1002 UserHandle.getCallingUserId());
1003 }
1004
1005 @Override
1006 public final int startActivities(IApplicationThread caller, String callingPackage,
1007 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1008 int userId) {
1009 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001010 enforceNotIsolatedCaller(reason);
1011 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001013 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1014 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1015 reason, null /* originatingPendingIntent */,
1016 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 }
1018
1019 @Override
1020 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1021 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1022 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1023 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1024 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1025 true /*validateIncomingUser*/);
1026 }
1027
1028 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1029 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1030 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1031 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001034 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1036
1037 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001038 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 .setCaller(caller)
1040 .setCallingPackage(callingPackage)
1041 .setResolvedType(resolvedType)
1042 .setResultTo(resultTo)
1043 .setResultWho(resultWho)
1044 .setRequestCode(requestCode)
1045 .setStartFlags(startFlags)
1046 .setProfilerInfo(profilerInfo)
1047 .setActivityOptions(bOptions)
1048 .setMayWait(userId)
1049 .execute();
1050
1051 }
1052
1053 @Override
1054 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1055 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001056 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1057 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058 // Refuse possible leaked file descriptors
1059 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1060 throw new IllegalArgumentException("File descriptors passed in Intent");
1061 }
1062
1063 if (!(target instanceof PendingIntentRecord)) {
1064 throw new IllegalArgumentException("Bad PendingIntent object");
1065 }
1066
1067 PendingIntentRecord pir = (PendingIntentRecord)target;
1068
1069 synchronized (mGlobalLock) {
1070 // If this is coming from the currently resumed activity, it is
1071 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001072 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 if (stack.mResumedActivity != null &&
1074 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001075 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 }
1077 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 }
1081
1082 @Override
1083 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1084 Bundle bOptions) {
1085 // Refuse possible leaked file descriptors
1086 if (intent != null && intent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1090
1091 synchronized (mGlobalLock) {
1092 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1093 if (r == null) {
1094 SafeActivityOptions.abort(options);
1095 return false;
1096 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001097 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 // The caller is not running... d'oh!
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
1102 intent = new Intent(intent);
1103 // The caller is not allowed to change the data.
1104 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1105 // And we are resetting to find the next component...
1106 intent.setComponent(null);
1107
1108 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1109
1110 ActivityInfo aInfo = null;
1111 try {
1112 List<ResolveInfo> resolves =
1113 AppGlobals.getPackageManager().queryIntentActivities(
1114 intent, r.resolvedType,
1115 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1116 UserHandle.getCallingUserId()).getList();
1117
1118 // Look for the original activity in the list...
1119 final int N = resolves != null ? resolves.size() : 0;
1120 for (int i=0; i<N; i++) {
1121 ResolveInfo rInfo = resolves.get(i);
1122 if (rInfo.activityInfo.packageName.equals(r.packageName)
1123 && rInfo.activityInfo.name.equals(r.info.name)) {
1124 // We found the current one... the next matching is
1125 // after it.
1126 i++;
1127 if (i<N) {
1128 aInfo = resolves.get(i).activityInfo;
1129 }
1130 if (debug) {
1131 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1132 + "/" + r.info.name);
1133 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1134 ? "null" : aInfo.packageName + "/" + aInfo.name));
1135 }
1136 break;
1137 }
1138 }
1139 } catch (RemoteException e) {
1140 }
1141
1142 if (aInfo == null) {
1143 // Nobody who is next!
1144 SafeActivityOptions.abort(options);
1145 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1146 return false;
1147 }
1148
1149 intent.setComponent(new ComponentName(
1150 aInfo.applicationInfo.packageName, aInfo.name));
1151 intent.setFlags(intent.getFlags()&~(
1152 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1153 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1154 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1155 FLAG_ACTIVITY_NEW_TASK));
1156
1157 // Okay now we need to start the new activity, replacing the currently running activity.
1158 // This is a little tricky because we want to start the new one as if the current one is
1159 // finished, but not finish the current one first so that there is no flicker.
1160 // And thus...
1161 final boolean wasFinishing = r.finishing;
1162 r.finishing = true;
1163
1164 // Propagate reply information over to the new activity.
1165 final ActivityRecord resultTo = r.resultTo;
1166 final String resultWho = r.resultWho;
1167 final int requestCode = r.requestCode;
1168 r.resultTo = null;
1169 if (resultTo != null) {
1170 resultTo.removeResultsLocked(r, resultWho, requestCode);
1171 }
1172
1173 final long origId = Binder.clearCallingIdentity();
1174 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001175 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001176 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001177 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001178 .setResolvedType(r.resolvedType)
1179 .setActivityInfo(aInfo)
1180 .setResultTo(resultTo != null ? resultTo.appToken : null)
1181 .setResultWho(resultWho)
1182 .setRequestCode(requestCode)
1183 .setCallingPid(-1)
1184 .setCallingUid(r.launchedFromUid)
1185 .setCallingPackage(r.launchedFromPackage)
1186 .setRealCallingPid(-1)
1187 .setRealCallingUid(r.launchedFromUid)
1188 .setActivityOptions(options)
1189 .execute();
1190 Binder.restoreCallingIdentity(origId);
1191
1192 r.finishing = wasFinishing;
1193 if (res != ActivityManager.START_SUCCESS) {
1194 return false;
1195 }
1196 return true;
1197 }
1198 }
1199
1200 @Override
1201 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1202 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1203 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1204 final WaitResult res = new WaitResult();
1205 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001206 enforceNotIsolatedCaller("startActivityAndWait");
1207 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1208 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001210 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 .setCaller(caller)
1212 .setCallingPackage(callingPackage)
1213 .setResolvedType(resolvedType)
1214 .setResultTo(resultTo)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setStartFlags(startFlags)
1218 .setActivityOptions(bOptions)
1219 .setMayWait(userId)
1220 .setProfilerInfo(profilerInfo)
1221 .setWaitResult(res)
1222 .execute();
1223 }
1224 return res;
1225 }
1226
1227 @Override
1228 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, Configuration config, Bundle bOptions, int userId) {
1231 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001232 enforceNotIsolatedCaller("startActivityWithConfig");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1234 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001236 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setGlobalConfiguration(config)
1245 .setActivityOptions(bOptions)
1246 .setMayWait(userId)
1247 .execute();
1248 }
1249 }
1250
Alison Cichowlas3e340502018-08-07 17:15:01 -04001251
1252 @Override
1253 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1254 int callingUid = Binder.getCallingUid();
1255 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1256 throw new SecurityException("Only the system process can request a permission token, "
1257 + "received request from uid: " + callingUid);
1258 }
1259 IBinder permissionToken = new Binder();
1260 synchronized (mGlobalLock) {
1261 mStartActivitySources.put(permissionToken, delegatorToken);
1262 }
1263
1264 Message expireMsg = PooledLambda.obtainMessage(
1265 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1266 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1267
1268 Message forgetMsg = PooledLambda.obtainMessage(
1269 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1270 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1271
1272 return permissionToken;
1273 }
1274
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 @Override
1276 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1277 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001278 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1279 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001281 // permission grants) as any app that may launch one of your own activities. So we only
1282 // allow this in two cases:
1283 // 1) The caller is an activity that is part of the core framework, and then only when it
1284 // is running as the system.
1285 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1286 // can only be requested by a system activity, which may then delegate this call to
1287 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 final ActivityRecord sourceRecord;
1289 final int targetUid;
1290 final String targetPackage;
1291 final boolean isResolver;
1292 synchronized (mGlobalLock) {
1293 if (resultTo == null) {
1294 throw new SecurityException("Must be called from an activity");
1295 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001296 final IBinder sourceToken;
1297 if (permissionToken != null) {
1298 // To even attempt to use a permissionToken, an app must also have this signature
1299 // permission.
1300 mAmInternal.enforceCallingPermission(
1301 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1302 "startActivityAsCaller");
1303 // If called with a permissionToken, we want the sourceRecord from the delegator
1304 // activity that requested this token.
1305 sourceToken = mStartActivitySources.remove(permissionToken);
1306 if (sourceToken == null) {
1307 // Invalid permissionToken, check if it recently expired.
1308 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1309 throw new SecurityException("Called with expired permission token: "
1310 + permissionToken);
1311 } else {
1312 throw new SecurityException("Called with invalid permission token: "
1313 + permissionToken);
1314 }
1315 }
1316 } else {
1317 // This method was called directly by the source.
1318 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001320
Wale Ogunwaled32da472018-11-16 07:19:28 -08001321 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 if (sourceRecord == null) {
1323 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
1325 if (sourceRecord.app == null) {
1326 throw new SecurityException("Called without a process attached to activity");
1327 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001328
1329 // Whether called directly or from a delegate, the source activity must be from the
1330 // android package.
1331 if (!sourceRecord.info.packageName.equals("android")) {
1332 throw new SecurityException("Must be called from an activity that is "
1333 + "declared in the android package");
1334 }
1335
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001336 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 // This is still okay, as long as this activity is running under the
1338 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 + " must be system uid or original calling uid "
1343 + sourceRecord.launchedFromUid);
1344 }
1345 }
1346 if (ignoreTargetSecurity) {
1347 if (intent.getComponent() == null) {
1348 throw new SecurityException(
1349 "Component must be specified with ignoreTargetSecurity");
1350 }
1351 if (intent.getSelector() != null) {
1352 throw new SecurityException(
1353 "Selector not allowed with ignoreTargetSecurity");
1354 }
1355 }
1356 targetUid = sourceRecord.launchedFromUid;
1357 targetPackage = sourceRecord.launchedFromPackage;
1358 isResolver = sourceRecord.isResolverOrChildActivity();
1359 }
1360
1361 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 }
1364
1365 // TODO: Switch to user app stacks here.
1366 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(targetUid)
1369 .setCallingPackage(targetPackage)
1370 .setResolvedType(resolvedType)
1371 .setResultTo(resultTo)
1372 .setResultWho(resultWho)
1373 .setRequestCode(requestCode)
1374 .setStartFlags(startFlags)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1378 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001379 // The target may well be in the background, which would normally prevent it
1380 // from starting an activity. Here we definitely want the start to succeed.
1381 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 .execute();
1383 } catch (SecurityException e) {
1384 // XXX need to figure out how to propagate to original app.
1385 // A SecurityException here is generally actually a fault of the original
1386 // calling activity (such as a fairly granting permissions), so propagate it
1387 // back to them.
1388 /*
1389 StringBuilder msg = new StringBuilder();
1390 msg.append("While launching");
1391 msg.append(intent.toString());
1392 msg.append(": ");
1393 msg.append(e.getMessage());
1394 */
1395 throw e;
1396 }
1397 }
1398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1400 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1401 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1402 }
1403
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 @Override
1405 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1406 Intent intent, String resolvedType, IVoiceInteractionSession session,
1407 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1408 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 if (session == null || interactor == null) {
1411 throw new NullPointerException("null session or interactor");
1412 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001415 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 .setCallingUid(callingUid)
1417 .setCallingPackage(callingPackage)
1418 .setResolvedType(resolvedType)
1419 .setVoiceSession(session)
1420 .setVoiceInteractor(interactor)
1421 .setStartFlags(startFlags)
1422 .setProfilerInfo(profilerInfo)
1423 .setActivityOptions(bOptions)
1424 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001425 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .execute();
1427 }
1428
1429 @Override
1430 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1431 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1433 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001435 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 .setCallingUid(callingUid)
1437 .setCallingPackage(callingPackage)
1438 .setResolvedType(resolvedType)
1439 .setActivityOptions(bOptions)
1440 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001441 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .execute();
1443 }
1444
1445 @Override
1446 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1447 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001448 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 final int callingPid = Binder.getCallingPid();
1450 final long origId = Binder.clearCallingIdentity();
1451 try {
1452 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001453 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1454 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455
1456 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001457 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1458 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1460 recentsUid, assistDataReceiver);
1461 }
1462 } finally {
1463 Binder.restoreCallingIdentity(origId);
1464 }
1465 }
1466
1467 @Override
1468 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001469 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001470 "startActivityFromRecents()");
1471
1472 final int callingPid = Binder.getCallingPid();
1473 final int callingUid = Binder.getCallingUid();
1474 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1475 final long origId = Binder.clearCallingIdentity();
1476 try {
1477 synchronized (mGlobalLock) {
1478 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1479 safeOptions);
1480 }
1481 } finally {
1482 Binder.restoreCallingIdentity(origId);
1483 }
1484 }
1485
1486 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001487 * Public API to check if the client is allowed to start an activity on specified display.
1488 *
1489 * If the target display is private or virtual, some restrictions will apply.
1490 *
1491 * @param displayId Target display id.
1492 * @param intent Intent used to launch the activity.
1493 * @param resolvedType The MIME type of the intent.
1494 * @param userId The id of the user for whom the call is made.
1495 * @return {@code true} if a call to start an activity on the target display should succeed and
1496 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1497 */
1498 @Override
1499 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1500 String resolvedType, int userId) {
1501 final int callingUid = Binder.getCallingUid();
1502 final int callingPid = Binder.getCallingPid();
1503 final long origId = Binder.clearCallingIdentity();
1504
1505 try {
1506 // Collect information about the target of the Intent.
1507 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1508 0 /* startFlags */, null /* profilerInfo */, userId,
1509 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1510 UserHandle.USER_NULL));
1511 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1512
1513 synchronized (mGlobalLock) {
1514 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1515 aInfo);
1516 }
1517 } finally {
1518 Binder.restoreCallingIdentity(origId);
1519 }
1520 }
1521
1522 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 * This is the internal entry point for handling Activity.finish().
1524 *
1525 * @param token The Binder token referencing the Activity we want to finish.
1526 * @param resultCode Result code, if any, from this Activity.
1527 * @param resultData Result data (Intent), if any, from this Activity.
1528 * @param finishTask Whether to finish the task associated with this Activity.
1529 *
1530 * @return Returns true if the activity successfully finished, or false if it is still running.
1531 */
1532 @Override
1533 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1534 int finishTask) {
1535 // Refuse possible leaked file descriptors
1536 if (resultData != null && resultData.hasFileDescriptors()) {
1537 throw new IllegalArgumentException("File descriptors passed in Intent");
1538 }
1539
1540 synchronized (mGlobalLock) {
1541 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1542 if (r == null) {
1543 return true;
1544 }
1545 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001546 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 ActivityRecord rootR = tr.getRootActivity();
1548 if (rootR == null) {
1549 Slog.w(TAG, "Finishing task with all activities already finished");
1550 }
1551 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1552 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001553 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 return false;
1555 }
1556
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001557 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1558 // We should consolidate.
1559 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001561 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001562 if (next != null) {
1563 // ask watcher if this is allowed
1564 boolean resumeOK = true;
1565 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001566 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001568 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 Watchdog.getInstance().setActivityController(null);
1570 }
1571
1572 if (!resumeOK) {
1573 Slog.i(TAG, "Not finishing activity because controller resumed");
1574 return false;
1575 }
1576 }
1577 }
1578 final long origId = Binder.clearCallingIdentity();
1579 try {
1580 boolean res;
1581 final boolean finishWithRootActivity =
1582 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1583 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1584 || (finishWithRootActivity && r == rootR)) {
1585 // If requested, remove the task that is associated to this activity only if it
1586 // was the root activity in the task. The result code and data is ignored
1587 // because we don't support returning them across task boundaries. Also, to
1588 // keep backwards compatibility we remove the task from recents when finishing
1589 // task with root activity.
1590 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1591 finishWithRootActivity, "finish-activity");
1592 if (!res) {
1593 Slog.i(TAG, "Removing task failed to finish activity");
1594 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001595 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001596 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 } else {
1598 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1599 resultData, "app-request", true);
1600 if (!res) {
1601 Slog.i(TAG, "Failed to finish by app-request");
1602 }
1603 }
1604 return res;
1605 } finally {
1606 Binder.restoreCallingIdentity(origId);
1607 }
1608 }
1609 }
1610
1611 @Override
1612 public boolean finishActivityAffinity(IBinder token) {
1613 synchronized (mGlobalLock) {
1614 final long origId = Binder.clearCallingIdentity();
1615 try {
1616 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1617 if (r == null) {
1618 return false;
1619 }
1620
1621 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1622 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001623 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001624 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 return false;
1626 }
1627 return task.getStack().finishActivityAffinityLocked(r);
1628 } finally {
1629 Binder.restoreCallingIdentity(origId);
1630 }
1631 }
1632 }
1633
1634 @Override
1635 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1636 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001637 try {
1638 WindowProcessController proc = null;
1639 synchronized (mGlobalLock) {
1640 ActivityStack stack = ActivityRecord.getStackLocked(token);
1641 if (stack == null) {
1642 return;
1643 }
1644 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1645 false /* fromTimeout */, false /* processPausingActivities */, config);
1646 if (r != null) {
1647 proc = r.app;
1648 }
1649 if (stopProfiling && proc != null) {
1650 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 }
1652 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001653 } finally {
1654 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 }
1657
1658 @Override
1659 public final void activityResumed(IBinder token) {
1660 final long origId = Binder.clearCallingIdentity();
1661 synchronized (mGlobalLock) {
1662 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001663 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001664 }
1665 Binder.restoreCallingIdentity(origId);
1666 }
1667
1668 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001669 public final void activityTopResumedStateLost() {
1670 final long origId = Binder.clearCallingIdentity();
1671 synchronized (mGlobalLock) {
1672 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1673 }
1674 Binder.restoreCallingIdentity(origId);
1675 }
1676
1677 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 public final void activityPaused(IBinder token) {
1679 final long origId = Binder.clearCallingIdentity();
1680 synchronized (mGlobalLock) {
1681 ActivityStack stack = ActivityRecord.getStackLocked(token);
1682 if (stack != null) {
1683 stack.activityPausedLocked(token, false);
1684 }
1685 }
1686 Binder.restoreCallingIdentity(origId);
1687 }
1688
1689 @Override
1690 public final void activityStopped(IBinder token, Bundle icicle,
1691 PersistableBundle persistentState, CharSequence description) {
1692 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1693
1694 // Refuse possible leaked file descriptors
1695 if (icicle != null && icicle.hasFileDescriptors()) {
1696 throw new IllegalArgumentException("File descriptors passed in Bundle");
1697 }
1698
1699 final long origId = Binder.clearCallingIdentity();
1700
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001701 String restartingName = null;
1702 int restartingUid = 0;
1703 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001705 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001707 if (r.attachedToProcess()
1708 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1709 // The activity was requested to restart from
1710 // {@link #restartActivityProcessIfVisible}.
1711 restartingName = r.app.mName;
1712 restartingUid = r.app.mUid;
1713 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 r.activityStoppedLocked(icicle, persistentState, description);
1715 }
1716 }
1717
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001718 if (restartingName != null) {
1719 // In order to let the foreground activity can be restarted with its saved state from
1720 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1721 // until the activity reports stopped with the state. And the activity record will be
1722 // kept because the record state is restarting, then the activity will be restarted
1723 // immediately if it is still the top one.
1724 mStackSupervisor.removeRestartTimeouts(r);
1725 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1726 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001727 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 @Override
1733 public final void activityDestroyed(IBinder token) {
1734 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1735 synchronized (mGlobalLock) {
1736 ActivityStack stack = ActivityRecord.getStackLocked(token);
1737 if (stack != null) {
1738 stack.activityDestroyedLocked(token, "activityDestroyed");
1739 }
1740 }
1741 }
1742
1743 @Override
1744 public final void activityRelaunched(IBinder token) {
1745 final long origId = Binder.clearCallingIdentity();
1746 synchronized (mGlobalLock) {
1747 mStackSupervisor.activityRelaunchedLocked(token);
1748 }
1749 Binder.restoreCallingIdentity(origId);
1750 }
1751
1752 public final void activitySlept(IBinder token) {
1753 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1754
1755 final long origId = Binder.clearCallingIdentity();
1756
1757 synchronized (mGlobalLock) {
1758 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1759 if (r != null) {
1760 mStackSupervisor.activitySleptLocked(r);
1761 }
1762 }
1763
1764 Binder.restoreCallingIdentity(origId);
1765 }
1766
1767 @Override
1768 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1769 synchronized (mGlobalLock) {
1770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1771 if (r == null) {
1772 return;
1773 }
1774 final long origId = Binder.clearCallingIdentity();
1775 try {
1776 r.setRequestedOrientation(requestedOrientation);
1777 } finally {
1778 Binder.restoreCallingIdentity(origId);
1779 }
1780 }
1781 }
1782
1783 @Override
1784 public int getRequestedOrientation(IBinder token) {
1785 synchronized (mGlobalLock) {
1786 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1787 if (r == null) {
1788 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1789 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001790 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792 }
1793
1794 @Override
1795 public void setImmersive(IBinder token, boolean immersive) {
1796 synchronized (mGlobalLock) {
1797 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1798 if (r == null) {
1799 throw new IllegalArgumentException();
1800 }
1801 r.immersive = immersive;
1802
1803 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001804 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001806 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 }
1808 }
1809 }
1810
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 void applyUpdateLockStateLocked(ActivityRecord r) {
1812 // Modifications to the UpdateLock state are done on our handler, outside
1813 // the activity manager's locks. The new state is determined based on the
1814 // state *now* of the relevant activity record. The object is passed to
1815 // the handler solely for logging detail, not to be consulted/modified.
1816 final boolean nextState = r != null && r.immersive;
1817 mH.post(() -> {
1818 if (mUpdateLock.isHeld() != nextState) {
1819 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1820 "Applying new update lock state '" + nextState + "' for " + r);
1821 if (nextState) {
1822 mUpdateLock.acquire();
1823 } else {
1824 mUpdateLock.release();
1825 }
1826 }
1827 });
1828 }
1829
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 @Override
1831 public boolean isImmersive(IBinder token) {
1832 synchronized (mGlobalLock) {
1833 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1834 if (r == null) {
1835 throw new IllegalArgumentException();
1836 }
1837 return r.immersive;
1838 }
1839 }
1840
1841 @Override
1842 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001843 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001845 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 return (r != null) ? r.immersive : false;
1847 }
1848 }
1849
1850 @Override
1851 public void overridePendingTransition(IBinder token, String packageName,
1852 int enterAnim, int exitAnim) {
1853 synchronized (mGlobalLock) {
1854 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1855 if (self == null) {
1856 return;
1857 }
1858
1859 final long origId = Binder.clearCallingIdentity();
1860
1861 if (self.isState(
1862 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001863 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001864 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
1866
1867 Binder.restoreCallingIdentity(origId);
1868 }
1869 }
1870
1871 @Override
1872 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001873 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001875 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 if (r == null) {
1877 return ActivityManager.COMPAT_MODE_UNKNOWN;
1878 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001879 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 }
1881 }
1882
1883 @Override
1884 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001887 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001889 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001890 if (r == null) {
1891 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1892 return;
1893 }
1894 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001895 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
1897 }
1898
1899 @Override
1900 public int getLaunchedFromUid(IBinder activityToken) {
1901 ActivityRecord srec;
1902 synchronized (mGlobalLock) {
1903 srec = ActivityRecord.forTokenLocked(activityToken);
1904 }
1905 if (srec == null) {
1906 return -1;
1907 }
1908 return srec.launchedFromUid;
1909 }
1910
1911 @Override
1912 public String getLaunchedFromPackage(IBinder activityToken) {
1913 ActivityRecord srec;
1914 synchronized (mGlobalLock) {
1915 srec = ActivityRecord.forTokenLocked(activityToken);
1916 }
1917 if (srec == null) {
1918 return null;
1919 }
1920 return srec.launchedFromPackage;
1921 }
1922
1923 @Override
1924 public boolean convertFromTranslucent(IBinder token) {
1925 final long origId = Binder.clearCallingIdentity();
1926 try {
1927 synchronized (mGlobalLock) {
1928 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1929 if (r == null) {
1930 return false;
1931 }
1932 final boolean translucentChanged = r.changeWindowTranslucency(true);
1933 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001934 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 return translucentChanged;
1938 }
1939 } finally {
1940 Binder.restoreCallingIdentity(origId);
1941 }
1942 }
1943
1944 @Override
1945 public boolean convertToTranslucent(IBinder token, Bundle options) {
1946 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1947 final long origId = Binder.clearCallingIdentity();
1948 try {
1949 synchronized (mGlobalLock) {
1950 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1951 if (r == null) {
1952 return false;
1953 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001954 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 int index = task.mActivities.lastIndexOf(r);
1956 if (index > 0) {
1957 ActivityRecord under = task.mActivities.get(index - 1);
1958 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1959 }
1960 final boolean translucentChanged = r.changeWindowTranslucency(false);
1961 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001962 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001964 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001965 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 return translucentChanged;
1967 }
1968 } finally {
1969 Binder.restoreCallingIdentity(origId);
1970 }
1971 }
1972
1973 @Override
1974 public void notifyActivityDrawn(IBinder token) {
1975 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1976 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001977 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001979 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 }
1981 }
1982 }
1983
1984 @Override
1985 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1986 synchronized (mGlobalLock) {
1987 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1988 if (r == null) {
1989 return;
1990 }
1991 r.reportFullyDrawnLocked(restoredFromBundle);
1992 }
1993 }
1994
1995 @Override
1996 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1997 synchronized (mGlobalLock) {
1998 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1999 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2000 return stack.mDisplayId;
2001 }
2002 return DEFAULT_DISPLAY;
2003 }
2004 }
2005
2006 @Override
2007 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002008 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 long ident = Binder.clearCallingIdentity();
2010 try {
2011 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002012 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 }
2016 return null;
2017 }
2018 } finally {
2019 Binder.restoreCallingIdentity(ident);
2020 }
2021 }
2022
2023 @Override
2024 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002025 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2027 final long callingId = Binder.clearCallingIdentity();
2028 try {
2029 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002030 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 if (stack == null) {
2032 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2033 return;
2034 }
2035 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002036 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002037 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
2039 }
2040 } finally {
2041 Binder.restoreCallingIdentity(callingId);
2042 }
2043 }
2044
2045 @Override
2046 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002047 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002048 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2049 final long callingId = Binder.clearCallingIdentity();
2050 try {
2051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002052 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002053 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 if (task == null) {
2055 return;
2056 }
2057 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002058 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 }
2061 }
2062 } finally {
2063 Binder.restoreCallingIdentity(callingId);
2064 }
2065 }
2066
2067 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002068 public void restartActivityProcessIfVisible(IBinder activityToken) {
2069 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2070 final long callingId = Binder.clearCallingIdentity();
2071 try {
2072 synchronized (mGlobalLock) {
2073 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2074 if (r == null) {
2075 return;
2076 }
2077 r.restartProcessIfVisible();
2078 }
2079 } finally {
2080 Binder.restoreCallingIdentity(callingId);
2081 }
2082 }
2083
2084 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002086 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 synchronized (mGlobalLock) {
2088 final long ident = Binder.clearCallingIdentity();
2089 try {
2090 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2091 "remove-task");
2092 } finally {
2093 Binder.restoreCallingIdentity(ident);
2094 }
2095 }
2096 }
2097
2098 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002099 public void removeAllVisibleRecentTasks() {
2100 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2101 synchronized (mGlobalLock) {
2102 final long ident = Binder.clearCallingIdentity();
2103 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002104 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002105 } finally {
2106 Binder.restoreCallingIdentity(ident);
2107 }
2108 }
2109 }
2110
2111 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2113 synchronized (mGlobalLock) {
2114 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2115 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002116 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 }
2118 }
2119 return false;
2120 }
2121
2122 @Override
2123 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2124 Intent resultData) {
2125
2126 synchronized (mGlobalLock) {
2127 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2128 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002129 return r.getActivityStack().navigateUpToLocked(
2130 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 }
2132 return false;
2133 }
2134 }
2135
2136 /**
2137 * Attempts to move a task backwards in z-order (the order of activities within the task is
2138 * unchanged).
2139 *
2140 * There are several possible results of this call:
2141 * - if the task is locked, then we will show the lock toast
2142 * - if there is a task behind the provided task, then that task is made visible and resumed as
2143 * this task is moved to the back
2144 * - otherwise, if there are no other tasks in the stack:
2145 * - if this task is in the pinned stack, then we remove the stack completely, which will
2146 * have the effect of moving the task to the top or bottom of the fullscreen stack
2147 * (depending on whether it is visible)
2148 * - otherwise, we simply return home and hide this task
2149 *
2150 * @param token A reference to the activity we wish to move
2151 * @param nonRoot If false then this only works if the activity is the root
2152 * of a task; if true it will work for any activity in a task.
2153 * @return Returns true if the move completed, false if not.
2154 */
2155 @Override
2156 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 synchronized (mGlobalLock) {
2159 final long origId = Binder.clearCallingIdentity();
2160 try {
2161 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002162 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 if (task != null) {
2164 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2165 }
2166 } finally {
2167 Binder.restoreCallingIdentity(origId);
2168 }
2169 }
2170 return false;
2171 }
2172
2173 @Override
2174 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002175 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 long ident = Binder.clearCallingIdentity();
2177 Rect rect = new Rect();
2178 try {
2179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002180 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002181 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2182 if (task == null) {
2183 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2184 return rect;
2185 }
2186 if (task.getStack() != null) {
2187 // Return the bounds from window manager since it will be adjusted for various
2188 // things like the presense of a docked stack for tasks that aren't resizeable.
2189 task.getWindowContainerBounds(rect);
2190 } else {
2191 // Task isn't in window manager yet since it isn't associated with a stack.
2192 // Return the persist value from activity manager
2193 if (!task.matchParentBounds()) {
2194 rect.set(task.getBounds());
2195 } else if (task.mLastNonFullscreenBounds != null) {
2196 rect.set(task.mLastNonFullscreenBounds);
2197 }
2198 }
2199 }
2200 } finally {
2201 Binder.restoreCallingIdentity(ident);
2202 }
2203 return rect;
2204 }
2205
2206 @Override
2207 public ActivityManager.TaskDescription getTaskDescription(int id) {
2208 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002209 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002211 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2213 if (tr != null) {
2214 return tr.lastTaskDescription;
2215 }
2216 }
2217 return null;
2218 }
2219
2220 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002221 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2222 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2223 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2224 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2225 return;
2226 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002227 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002228 synchronized (mGlobalLock) {
2229 final long ident = Binder.clearCallingIdentity();
2230 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002231 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002232 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002233 if (task == null) {
2234 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2235 return;
2236 }
2237
2238 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2239 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2240
2241 if (!task.isActivityTypeStandardOrUndefined()) {
2242 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2243 + " non-standard task " + taskId + " to windowing mode="
2244 + windowingMode);
2245 }
2246
2247 final ActivityStack stack = task.getStack();
2248 if (toTop) {
2249 stack.moveToFront("setTaskWindowingMode", task);
2250 }
2251 stack.setWindowingMode(windowingMode);
2252 } finally {
2253 Binder.restoreCallingIdentity(ident);
2254 }
2255 }
2256 }
2257
2258 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002259 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002260 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002261 ActivityRecord r = getCallingRecordLocked(token);
2262 return r != null ? r.info.packageName : null;
2263 }
2264 }
2265
2266 @Override
2267 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 ActivityRecord r = getCallingRecordLocked(token);
2270 return r != null ? r.intent.getComponent() : null;
2271 }
2272 }
2273
2274 private ActivityRecord getCallingRecordLocked(IBinder token) {
2275 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2276 if (r == null) {
2277 return null;
2278 }
2279 return r.resultTo;
2280 }
2281
2282 @Override
2283 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285
2286 synchronized (mGlobalLock) {
2287 final long origId = Binder.clearCallingIdentity();
2288 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002289 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 } finally {
2291 Binder.restoreCallingIdentity(origId);
2292 }
2293 }
2294 }
2295
Mark Renouf446251d2019-04-26 10:22:41 -04002296 @Override
2297 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2298 synchronized (mGlobalLock) {
2299 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2300 if (r == null) {
2301 return;
2302 }
2303 ActivityStack stack = r.getActivityStack();
2304 if (stack != null && stack.isSingleTaskInstance()) {
2305 // Single-task stacks are used for activities which are presented in floating
2306 // windows above full screen activities. Instead of directly finishing the
2307 // task, a task change listener is used to notify SystemUI so the action can be
2308 // handled specially.
2309 final TaskRecord task = r.getTaskRecord();
2310 mTaskChangeNotificationController
2311 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2312 } else {
2313 try {
2314 callback.requestFinish();
2315 } catch (RemoteException e) {
2316 Slog.e(TAG, "Failed to invoke request finish callback", e);
2317 }
2318 }
2319 }
2320 }
2321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 /**
2323 * TODO: Add mController hook
2324 */
2325 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002326 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2327 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002328 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329
2330 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2331 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002332 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2333 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 }
2335 }
2336
Ricky Waiaca8a772019-04-04 16:01:06 +01002337 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2338 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 boolean fromRecents) {
2340
Ricky Waiaca8a772019-04-04 16:01:06 +01002341 final int callingPid = Binder.getCallingPid();
2342 final int callingUid = Binder.getCallingUid();
2343 if (!isSameApp(callingUid, callingPackage)) {
2344 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2345 + Binder.getCallingPid() + " as package " + callingPackage;
2346 Slog.w(TAG, msg);
2347 throw new SecurityException(msg);
2348 }
2349 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 SafeActivityOptions.abort(options);
2351 return;
2352 }
2353 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002354 WindowProcessController callerApp = null;
2355 if (appThread != null) {
2356 callerApp = getProcessController(appThread);
2357 }
2358 final ActivityStarter starter = getActivityStartController().obtainStarter(
2359 null /* intent */, "moveTaskToFront");
2360 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2361 -1, callerApp, null, false, null)) {
2362 boolean abort = !isBackgroundActivityStartsEnabled();
2363 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2364 if (abort) {
2365 return;
2366 }
2367 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002369 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 if (task == null) {
2371 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002372 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 return;
2374 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002375 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002377 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 return;
2379 }
2380 ActivityOptions realOptions = options != null
2381 ? options.getOptions(mStackSupervisor)
2382 : null;
2383 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2384 false /* forceNonResizable */);
2385
2386 final ActivityRecord topActivity = task.getTopActivity();
2387 if (topActivity != null) {
2388
2389 // We are reshowing a task, use a starting window to hide the initial draw delay
2390 // so the transition can start earlier.
2391 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2392 true /* taskSwitch */, fromRecents);
2393 }
2394 } finally {
2395 Binder.restoreCallingIdentity(origId);
2396 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 }
2398
Ricky Waiaca8a772019-04-04 16:01:06 +01002399 /**
2400 * Return true if callingUid is system, or packageName belongs to that callingUid.
2401 */
2402 boolean isSameApp(int callingUid, @Nullable String packageName) {
2403 try {
2404 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2405 if (packageName == null) {
2406 return false;
2407 }
2408 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2409 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2410 UserHandle.getUserId(callingUid));
2411 return UserHandle.isSameApp(callingUid, uid);
2412 }
2413 } catch (RemoteException e) {
2414 // Should not happen
2415 }
2416 return true;
2417 }
2418
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002419 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2420 int callingPid, int callingUid, String name) {
2421 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2422 return true;
2423 }
2424
2425 if (getRecentTasks().isCallerRecents(sourceUid)) {
2426 return true;
2427 }
2428
2429 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2430 if (perm == PackageManager.PERMISSION_GRANTED) {
2431 return true;
2432 }
2433 if (checkAllowAppSwitchUid(sourceUid)) {
2434 return true;
2435 }
2436
2437 // If the actual IPC caller is different from the logical source, then
2438 // also see if they are allowed to control app switches.
2439 if (callingUid != -1 && callingUid != sourceUid) {
2440 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2441 if (perm == PackageManager.PERMISSION_GRANTED) {
2442 return true;
2443 }
2444 if (checkAllowAppSwitchUid(callingUid)) {
2445 return true;
2446 }
2447 }
2448
2449 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2450 return false;
2451 }
2452
2453 private boolean checkAllowAppSwitchUid(int uid) {
2454 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2455 if (types != null) {
2456 for (int i = types.size() - 1; i >= 0; i--) {
2457 if (types.valueAt(i).intValue() == uid) {
2458 return true;
2459 }
2460 }
2461 }
2462 return false;
2463 }
2464
2465 @Override
2466 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2467 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2468 "setActivityController()");
2469 synchronized (mGlobalLock) {
2470 mController = controller;
2471 mControllerIsAMonkey = imAMonkey;
2472 Watchdog.getInstance().setActivityController(controller);
2473 }
2474 }
2475
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002476 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002477 synchronized (mGlobalLock) {
2478 return mController != null && mControllerIsAMonkey;
2479 }
2480 }
2481
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002482 @Override
2483 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2484 synchronized (mGlobalLock) {
2485 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2486 }
2487 }
2488
2489 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002490 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2491 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2492 }
2493
2494 @Override
2495 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2496 @WindowConfiguration.ActivityType int ignoreActivityType,
2497 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2498 final int callingUid = Binder.getCallingUid();
2499 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2500
2501 synchronized (mGlobalLock) {
2502 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2503
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002506 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002507 ignoreWindowingMode, callingUid, allowed);
2508 }
2509
2510 return list;
2511 }
2512
2513 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002514 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2515 synchronized (mGlobalLock) {
2516 final long origId = Binder.clearCallingIdentity();
2517 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2518 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002519 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002520 }
2521 Binder.restoreCallingIdentity(origId);
2522 }
2523 }
2524
2525 @Override
2526 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 ActivityStack stack = ActivityRecord.getStackLocked(token);
2529 if (stack != null) {
2530 return stack.willActivityBeVisibleLocked(token);
2531 }
2532 return false;
2533 }
2534 }
2535
2536 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002537 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002538 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 synchronized (mGlobalLock) {
2540 final long ident = Binder.clearCallingIdentity();
2541 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002542 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 if (task == null) {
2544 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2545 return;
2546 }
2547
2548 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2549 + " to stackId=" + stackId + " toTop=" + toTop);
2550
Wale Ogunwaled32da472018-11-16 07:19:28 -08002551 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 if (stack == null) {
2553 throw new IllegalStateException(
2554 "moveTaskToStack: No stack for stackId=" + stackId);
2555 }
2556 if (!stack.isActivityTypeStandardOrUndefined()) {
2557 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2558 + taskId + " to stack " + stackId);
2559 }
2560 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002562 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2563 }
2564 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2565 "moveTaskToStack");
2566 } finally {
2567 Binder.restoreCallingIdentity(ident);
2568 }
2569 }
2570 }
2571
2572 @Override
2573 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2574 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002575 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576
2577 final long ident = Binder.clearCallingIdentity();
2578 try {
2579 synchronized (mGlobalLock) {
2580 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002581 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002582 if (stack == null) {
2583 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2584 return;
2585 }
2586 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2587 throw new IllegalArgumentException("Stack: " + stackId
2588 + " doesn't support animated resize.");
2589 }
2590 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2591 animationDuration, false /* fromFullscreen */);
2592 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002593 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 if (stack == null) {
2595 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2596 return;
2597 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002598 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2600 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2601 }
2602 }
2603 } finally {
2604 Binder.restoreCallingIdentity(ident);
2605 }
2606 }
2607
wilsonshih5c4cf522019-01-25 09:03:47 +08002608 @Override
2609 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2610 int animationDuration) {
2611 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2612
2613 final long ident = Binder.clearCallingIdentity();
2614 try {
2615 synchronized (mGlobalLock) {
2616 if (xOffset == 0 && yOffset == 0) {
2617 return;
2618 }
2619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2620 if (stack == null) {
2621 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2622 return;
2623 }
2624 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2625 throw new IllegalArgumentException("Stack: " + stackId
2626 + " doesn't support animated resize.");
2627 }
2628 final Rect destBounds = new Rect();
2629 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002630 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002631 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2632 return;
2633 }
2634 destBounds.offset(xOffset, yOffset);
2635 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2636 animationDuration, false /* fromFullscreen */);
2637 }
2638 } finally {
2639 Binder.restoreCallingIdentity(ident);
2640 }
2641 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002642 /**
2643 * Moves the specified task to the primary-split-screen stack.
2644 *
2645 * @param taskId Id of task to move.
2646 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2647 * exist already. See
2648 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2649 * and
2650 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2651 * @param toTop If the task and stack should be moved to the top.
2652 * @param animate Whether we should play an animation for the moving the task.
2653 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2654 * stack. Pass {@code null} to use default bounds.
2655 * @param showRecents If the recents activity should be shown on the other side of the task
2656 * going into split-screen mode.
2657 */
2658 @Override
2659 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2660 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002661 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002662 "setTaskWindowingModeSplitScreenPrimary()");
2663 synchronized (mGlobalLock) {
2664 final long ident = Binder.clearCallingIdentity();
2665 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002666 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002667 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002668 if (task == null) {
2669 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2670 return false;
2671 }
2672 if (DEBUG_STACK) Slog.d(TAG_STACK,
2673 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2674 + " to createMode=" + createMode + " toTop=" + toTop);
2675 if (!task.isActivityTypeStandardOrUndefined()) {
2676 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2677 + " non-standard task " + taskId + " to split-screen windowing mode");
2678 }
2679
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002680 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002681 final int windowingMode = task.getWindowingMode();
2682 final ActivityStack stack = task.getStack();
2683 if (toTop) {
2684 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2685 }
2686 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002687 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2688 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002689 return windowingMode != task.getWindowingMode();
2690 } finally {
2691 Binder.restoreCallingIdentity(ident);
2692 }
2693 }
2694 }
2695
2696 /**
2697 * Removes stacks in the input windowing modes from the system if they are of activity type
2698 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2699 */
2700 @Override
2701 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002702 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 "removeStacksInWindowingModes()");
2704
2705 synchronized (mGlobalLock) {
2706 final long ident = Binder.clearCallingIdentity();
2707 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002708 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713 }
2714
2715 @Override
2716 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002717 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 "removeStacksWithActivityTypes()");
2719
2720 synchronized (mGlobalLock) {
2721 final long ident = Binder.clearCallingIdentity();
2722 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002723 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 } finally {
2725 Binder.restoreCallingIdentity(ident);
2726 }
2727 }
2728 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729
2730 @Override
2731 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2732 int userId) {
2733 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002734 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2735 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 final boolean detailed = checkGetTasksPermission(
2738 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2739 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 == PackageManager.PERMISSION_GRANTED;
2741
2742 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002743 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744 callingUid);
2745 }
2746 }
2747
2748 @Override
2749 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002750 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 long ident = Binder.clearCallingIdentity();
2752 try {
2753 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002754 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 }
2756 } finally {
2757 Binder.restoreCallingIdentity(ident);
2758 }
2759 }
2760
2761 @Override
2762 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002763 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 long ident = Binder.clearCallingIdentity();
2765 try {
2766 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002767 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 }
2769 } finally {
2770 Binder.restoreCallingIdentity(ident);
2771 }
2772 }
2773
2774 @Override
2775 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 final long callingUid = Binder.getCallingUid();
2778 final long origId = Binder.clearCallingIdentity();
2779 try {
2780 synchronized (mGlobalLock) {
2781 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002782 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2784 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2785 }
2786 } finally {
2787 Binder.restoreCallingIdentity(origId);
2788 }
2789 }
2790
2791 @Override
2792 public void startLockTaskModeByToken(IBinder token) {
2793 synchronized (mGlobalLock) {
2794 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2795 if (r == null) {
2796 return;
2797 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002798 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 }
2800 }
2801
2802 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002803 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 // This makes inner call to look as if it was initiated by system.
2806 long ident = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002809 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002810 MATCH_TASK_IN_STACKS_ONLY);
2811 if (task == null) {
2812 return;
2813 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814
2815 // When starting lock task mode the stack must be in front and focused
2816 task.getStack().moveToFront("startSystemLockTaskMode");
2817 startLockTaskModeLocked(task, true /* isSystemCaller */);
2818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
2825 public void stopLockTaskModeByToken(IBinder token) {
2826 synchronized (mGlobalLock) {
2827 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2828 if (r == null) {
2829 return;
2830 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002831 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 }
2833 }
2834
2835 /**
2836 * This API should be called by SystemUI only when user perform certain action to dismiss
2837 * lock task mode. We should only dismiss pinned lock task mode in this case.
2838 */
2839 @Override
2840 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002841 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2843 }
2844
2845 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2846 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2847 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2848 return;
2849 }
2850
Wale Ogunwaled32da472018-11-16 07:19:28 -08002851 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 if (stack == null || task != stack.topTask()) {
2853 throw new IllegalArgumentException("Invalid task, not in foreground");
2854 }
2855
2856 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2857 // system or a specific app.
2858 // * System-initiated requests will only start the pinned mode (screen pinning)
2859 // * App-initiated requests
2860 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2861 // - will start the pinned mode, otherwise
2862 final int callingUid = Binder.getCallingUid();
2863 long ident = Binder.clearCallingIdentity();
2864 try {
2865 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002866 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002868 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 } finally {
2870 Binder.restoreCallingIdentity(ident);
2871 }
2872 }
2873
2874 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2875 final int callingUid = Binder.getCallingUid();
2876 long ident = Binder.clearCallingIdentity();
2877 try {
2878 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002879 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 }
2881 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2882 // task and jumping straight into a call in the case of emergency call back.
2883 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2884 if (tm != null) {
2885 tm.showInCallScreen(false);
2886 }
2887 } finally {
2888 Binder.restoreCallingIdentity(ident);
2889 }
2890 }
2891
2892 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002893 public void updateLockTaskPackages(int userId, String[] packages) {
2894 final int callingUid = Binder.getCallingUid();
2895 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2896 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2897 "updateLockTaskPackages()");
2898 }
2899 synchronized (this) {
2900 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2901 + Arrays.toString(packages));
2902 getLockTaskController().updateLockTaskPackages(userId, packages);
2903 }
2904 }
2905
2906 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907 public boolean isInLockTaskMode() {
2908 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2909 }
2910
2911 @Override
2912 public int getLockTaskModeState() {
2913 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002914 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 }
2916 }
2917
2918 @Override
2919 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2920 synchronized (mGlobalLock) {
2921 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2922 if (r != null) {
2923 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002926 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 }
2928 }
2929 }
2930
2931 @Override
2932 public Bundle getActivityOptions(IBinder token) {
2933 final long origId = Binder.clearCallingIdentity();
2934 try {
2935 synchronized (mGlobalLock) {
2936 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2937 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002938 final ActivityOptions activityOptions = r.takeOptionsLocked(
2939 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 return activityOptions == null ? null : activityOptions.toBundle();
2941 }
2942 return null;
2943 }
2944 } finally {
2945 Binder.restoreCallingIdentity(origId);
2946 }
2947 }
2948
2949 @Override
2950 public List<IBinder> getAppTasks(String callingPackage) {
2951 int callingUid = Binder.getCallingUid();
2952 long ident = Binder.clearCallingIdentity();
2953 try {
2954 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002955 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 }
2957 } finally {
2958 Binder.restoreCallingIdentity(ident);
2959 }
2960 }
2961
2962 @Override
2963 public void finishVoiceTask(IVoiceInteractionSession session) {
2964 synchronized (mGlobalLock) {
2965 final long origId = Binder.clearCallingIdentity();
2966 try {
2967 // TODO: VI Consider treating local voice interactions and voice tasks
2968 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002969 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 } finally {
2971 Binder.restoreCallingIdentity(origId);
2972 }
2973 }
2974
2975 }
2976
2977 @Override
2978 public boolean isTopOfTask(IBinder token) {
2979 synchronized (mGlobalLock) {
2980 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002981 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 }
2983 }
2984
2985 @Override
2986 public void notifyLaunchTaskBehindComplete(IBinder token) {
2987 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2988 }
2989
2990 @Override
2991 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002992 mH.post(() -> {
2993 synchronized (mGlobalLock) {
2994 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002995 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002996 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002997 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002998 } catch (RemoteException e) {
2999 }
3000 }
3001 }
3002
3003 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005
3006 /** Called from an app when assist data is ready. */
3007 @Override
3008 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3009 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 synchronized (pae) {
3012 pae.result = extras;
3013 pae.structure = structure;
3014 pae.content = content;
3015 if (referrer != null) {
3016 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3017 }
3018 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003019 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003020 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3021 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 structure.setHomeActivity(pae.isHome);
3023 }
3024 pae.haveResult = true;
3025 pae.notifyAll();
3026 if (pae.intent == null && pae.receiver == null) {
3027 // Caller is just waiting for the result.
3028 return;
3029 }
3030 }
3031 // We are now ready to launch the assist activity.
3032 IAssistDataReceiver sendReceiver = null;
3033 Bundle sendBundle = null;
3034 synchronized (mGlobalLock) {
3035 buildAssistBundleLocked(pae, extras);
3036 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003037 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 if (!exists) {
3039 // Timed out.
3040 return;
3041 }
3042
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003043 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 // Caller wants result sent back to them.
3045 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003046 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3047 pae.activity.getTaskRecord().taskId);
3048 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3049 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3051 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3052 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3053 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3054 }
3055 }
3056 if (sendReceiver != null) {
3057 try {
3058 sendReceiver.onHandleAssistData(sendBundle);
3059 } catch (RemoteException e) {
3060 }
3061 return;
3062 }
3063
3064 final long ident = Binder.clearCallingIdentity();
3065 try {
3066 if (TextUtils.equals(pae.intent.getAction(),
3067 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3068 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003069
3070 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 } else {
3072 pae.intent.replaceExtras(pae.extras);
3073 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3074 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3075 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003076 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077
3078 try {
3079 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3080 } catch (ActivityNotFoundException e) {
3081 Slog.w(TAG, "No activity to handle assist action.", e);
3082 }
3083 }
3084 } finally {
3085 Binder.restoreCallingIdentity(ident);
3086 }
3087 }
3088
Marvin Ramin830d4e32019-03-12 13:16:58 +01003089 /**
3090 * Workaround for historical API which starts the Assist service with a non-foreground
3091 * {@code startService()} call.
3092 */
3093 private void startVoiceInteractionServiceAsUser(
3094 Intent intent, int userHandle, String reason) {
3095 // Resolve the intent to find out which package we need to whitelist.
3096 ResolveInfo resolveInfo =
3097 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3098 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3099 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3100 return;
3101 }
3102 intent.setPackage(resolveInfo.serviceInfo.packageName);
3103
3104 // Whitelist background services temporarily.
3105 LocalServices.getService(DeviceIdleController.LocalService.class)
3106 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3107 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3108
3109 // Finally, try to start the service.
3110 try {
3111 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3112 } catch (RuntimeException e) {
3113 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3114 }
3115 }
3116
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 @Override
3118 public int addAppTask(IBinder activityToken, Intent intent,
3119 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3120 final int callingUid = Binder.getCallingUid();
3121 final long callingIdent = Binder.clearCallingIdentity();
3122
3123 try {
3124 synchronized (mGlobalLock) {
3125 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3126 if (r == null) {
3127 throw new IllegalArgumentException("Activity does not exist; token="
3128 + activityToken);
3129 }
3130 ComponentName comp = intent.getComponent();
3131 if (comp == null) {
3132 throw new IllegalArgumentException("Intent " + intent
3133 + " must specify explicit component");
3134 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003135 if (thumbnail.getWidth() != mThumbnailWidth
3136 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 throw new IllegalArgumentException("Bad thumbnail size: got "
3138 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003139 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 }
3141 if (intent.getSelector() != null) {
3142 intent.setSelector(null);
3143 }
3144 if (intent.getSourceBounds() != null) {
3145 intent.setSourceBounds(null);
3146 }
3147 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3148 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3149 // The caller has added this as an auto-remove task... that makes no
3150 // sense, so turn off auto-remove.
3151 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3152 }
3153 }
3154 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3155 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3156 if (ainfo.applicationInfo.uid != callingUid) {
3157 throw new SecurityException(
3158 "Can't add task for another application: target uid="
3159 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3160 }
3161
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003162 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003164 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003166 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003167 // The app has too many tasks already and we can't add any more
3168 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3169 return INVALID_TASK_ID;
3170 }
3171 task.lastTaskDescription.copyFrom(description);
3172
3173 // TODO: Send the thumbnail to WM to store it.
3174
3175 return task.taskId;
3176 }
3177 } finally {
3178 Binder.restoreCallingIdentity(callingIdent);
3179 }
3180 }
3181
3182 @Override
3183 public Point getAppTaskThumbnailSize() {
3184 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003185 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 }
3187 }
3188
3189 @Override
3190 public void setTaskResizeable(int taskId, int resizeableMode) {
3191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003192 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3194 if (task == null) {
3195 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3196 return;
3197 }
3198 task.setResizeMode(resizeableMode);
3199 }
3200 }
3201
3202 @Override
3203 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003204 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 long ident = Binder.clearCallingIdentity();
3206 try {
3207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003208 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003209 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 if (task == null) {
3211 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3212 return;
3213 }
3214 // Place the task in the right stack if it isn't there already based on
3215 // the requested bounds.
3216 // The stack transition logic is:
3217 // - a null bounds on a freeform task moves that task to fullscreen
3218 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3219 // that task to freeform
3220 // - otherwise the task is not moved
3221 ActivityStack stack = task.getStack();
3222 if (!task.getWindowConfiguration().canResizeTask()) {
3223 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3224 }
3225 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3226 stack = stack.getDisplay().getOrCreateStack(
3227 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3228 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3229 stack = stack.getDisplay().getOrCreateStack(
3230 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3231 }
3232
3233 // Reparent the task to the right stack if necessary
3234 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3235 if (stack != task.getStack()) {
3236 // Defer resume until the task is resized below
3237 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3238 DEFER_RESUME, "resizeTask");
3239 preserveWindow = false;
3240 }
3241
3242 // After reparenting (which only resizes the task to the stack bounds), resize the
3243 // task to the actual bounds provided
3244 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3245 }
3246 } finally {
3247 Binder.restoreCallingIdentity(ident);
3248 }
3249 }
3250
3251 @Override
3252 public boolean releaseActivityInstance(IBinder token) {
3253 synchronized (mGlobalLock) {
3254 final long origId = Binder.clearCallingIdentity();
3255 try {
3256 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3257 if (r == null) {
3258 return false;
3259 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003260 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 } finally {
3262 Binder.restoreCallingIdentity(origId);
3263 }
3264 }
3265 }
3266
3267 @Override
3268 public void releaseSomeActivities(IApplicationThread appInt) {
3269 synchronized (mGlobalLock) {
3270 final long origId = Binder.clearCallingIdentity();
3271 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003272 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003273 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003274 } finally {
3275 Binder.restoreCallingIdentity(origId);
3276 }
3277 }
3278 }
3279
3280 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003281 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003282 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 != PackageManager.PERMISSION_GRANTED) {
3284 throw new SecurityException("Requires permission "
3285 + android.Manifest.permission.DEVICE_POWER);
3286 }
3287
3288 synchronized (mGlobalLock) {
3289 long ident = Binder.clearCallingIdentity();
3290 if (mKeyguardShown != keyguardShowing) {
3291 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003292 final Message msg = PooledLambda.obtainMessage(
3293 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3294 keyguardShowing);
3295 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 }
3297 try {
wilsonshih177261f2019-02-22 12:02:18 +08003298 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 } finally {
3300 Binder.restoreCallingIdentity(ident);
3301 }
3302 }
3303
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003304 mH.post(() -> {
3305 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3306 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3307 }
3308 });
3309 }
3310
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003311 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003312 mH.post(() -> {
3313 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3314 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3315 }
3316 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 }
3318
3319 @Override
3320 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003321 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3322 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323
3324 final File passedIconFile = new File(filePath);
3325 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3326 passedIconFile.getName());
3327 if (!legitIconFile.getPath().equals(filePath)
3328 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3329 throw new IllegalArgumentException("Bad file path: " + filePath
3330 + " passed for userId " + userId);
3331 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003332 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 }
3334
3335 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003336 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3338 final ActivityOptions activityOptions = safeOptions != null
3339 ? safeOptions.getOptions(mStackSupervisor)
3340 : null;
3341 if (activityOptions == null
3342 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3343 || activityOptions.getCustomInPlaceResId() == 0) {
3344 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3345 "with valid animation");
3346 }
lumark588a3e82018-07-20 18:53:54 +08003347 // Get top display of front most application.
3348 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3349 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003350 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3351 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3352 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003353 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003354 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003355 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 }
3357
3358 @Override
3359 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003360 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 synchronized (mGlobalLock) {
3362 final long ident = Binder.clearCallingIdentity();
3363 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003364 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 if (stack == null) {
3366 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3367 return;
3368 }
3369 if (!stack.isActivityTypeStandardOrUndefined()) {
3370 throw new IllegalArgumentException(
3371 "Removing non-standard stack is not allowed.");
3372 }
3373 mStackSupervisor.removeStack(stack);
3374 } finally {
3375 Binder.restoreCallingIdentity(ident);
3376 }
3377 }
3378 }
3379
3380 @Override
3381 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383
3384 synchronized (mGlobalLock) {
3385 final long ident = Binder.clearCallingIdentity();
3386 try {
3387 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3388 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003389 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 } finally {
3391 Binder.restoreCallingIdentity(ident);
3392 }
3393 }
3394 }
3395
3396 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003397 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 synchronized (mGlobalLock) {
3399 long ident = Binder.clearCallingIdentity();
3400 try {
3401 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3402 if (r == null) {
3403 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003404 "toggleFreeformWindowingMode: No activity record matching token="
3405 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 }
3407
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003408 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003409 if (stack == null) {
3410 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3411 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 }
3413
Yunfan Chend967af82019-01-17 18:30:18 +09003414 if (!stack.inFreeformWindowingMode()
3415 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3416 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3417 + "toggle between fullscreen and freeform.");
3418 }
3419
3420 if (stack.inFreeformWindowingMode()) {
3421 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003422 } else if (stack.getParent().inFreeformWindowingMode()) {
3423 // If the window is on a freeform display, set it to undefined. It will be
3424 // resolved to freeform and it can adjust windowing mode when the display mode
3425 // changes in runtime.
3426 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003427 } else {
3428 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3429 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
3433 }
3434 }
3435
3436 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3437 @Override
3438 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003439 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003441 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 }
3443
3444 /** Unregister a task stack listener so that it stops receiving callbacks. */
3445 @Override
3446 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003447 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003448 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003449 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 }
3451
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003452 @Override
3453 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3454 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3455 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3456 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3457 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3458 }
3459
3460 @Override
3461 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3462 IBinder activityToken, int flags) {
3463 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3464 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3465 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3466 }
3467
3468 @Override
3469 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3470 Bundle args) {
3471 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3472 true /* focused */, true /* newSessionId */, userHandle, args,
3473 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3474 }
3475
3476 @Override
3477 public Bundle getAssistContextExtras(int requestType) {
3478 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3479 null, null, true /* focused */, true /* newSessionId */,
3480 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3481 if (pae == null) {
3482 return null;
3483 }
3484 synchronized (pae) {
3485 while (!pae.haveResult) {
3486 try {
3487 pae.wait();
3488 } catch (InterruptedException e) {
3489 }
3490 }
3491 }
3492 synchronized (mGlobalLock) {
3493 buildAssistBundleLocked(pae, pae.result);
3494 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003495 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003496 }
3497 return pae.extras;
3498 }
3499
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003500 /**
3501 * Binder IPC calls go through the public entry point.
3502 * This can be called with or without the global lock held.
3503 */
3504 private static int checkCallingPermission(String permission) {
3505 return checkPermission(
3506 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3507 }
3508
3509 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003510 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003511 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3512 mAmInternal.enforceCallingPermission(permission, func);
3513 }
3514 }
3515
3516 @VisibleForTesting
3517 int checkGetTasksPermission(String permission, int pid, int uid) {
3518 return checkPermission(permission, pid, uid);
3519 }
3520
3521 static int checkPermission(String permission, int pid, int uid) {
3522 if (permission == null) {
3523 return PackageManager.PERMISSION_DENIED;
3524 }
3525 return checkComponentPermission(permission, pid, uid, -1, true);
3526 }
3527
Wale Ogunwale214f3482018-10-04 11:00:47 -07003528 public static int checkComponentPermission(String permission, int pid, int uid,
3529 int owningUid, boolean exported) {
3530 return ActivityManagerService.checkComponentPermission(
3531 permission, pid, uid, owningUid, exported);
3532 }
3533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003534 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3535 if (getRecentTasks().isCallerRecents(callingUid)) {
3536 // Always allow the recents component to get tasks
3537 return true;
3538 }
3539
3540 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3541 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3542 if (!allowed) {
3543 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3544 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3545 // Temporary compatibility: some existing apps on the system image may
3546 // still be requesting the old permission and not switched to the new
3547 // one; if so, we'll still allow them full access. This means we need
3548 // to see if they are holding the old permission and are a system app.
3549 try {
3550 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3551 allowed = true;
3552 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3553 + " is using old GET_TASKS but privileged; allowing");
3554 }
3555 } catch (RemoteException e) {
3556 }
3557 }
3558 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3559 + " does not hold REAL_GET_TASKS; limiting output");
3560 }
3561 return allowed;
3562 }
3563
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003564 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3565 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3566 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3567 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003568 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003569 "enqueueAssistContext()");
3570
3571 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003572 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003573 if (activity == null) {
3574 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3575 return null;
3576 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003577 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003578 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3579 return null;
3580 }
3581 if (focused) {
3582 if (activityToken != null) {
3583 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3584 if (activity != caller) {
3585 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3586 + " is not current top " + activity);
3587 return null;
3588 }
3589 }
3590 } else {
3591 activity = ActivityRecord.forTokenLocked(activityToken);
3592 if (activity == null) {
3593 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3594 + " couldn't be found");
3595 return null;
3596 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003597 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3599 return null;
3600 }
3601 }
3602
3603 PendingAssistExtras pae;
3604 Bundle extras = new Bundle();
3605 if (args != null) {
3606 extras.putAll(args);
3607 }
3608 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003609 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610
3611 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3612 userHandle);
3613 pae.isHome = activity.isActivityTypeHome();
3614
3615 // Increment the sessionId if necessary
3616 if (newSessionId) {
3617 mViSessionId++;
3618 }
3619 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003620 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3621 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003623 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 } catch (RemoteException e) {
3625 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3626 return null;
3627 }
3628 return pae;
3629 }
3630 }
3631
3632 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3633 if (result != null) {
3634 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3635 }
3636 if (pae.hint != null) {
3637 pae.extras.putBoolean(pae.hint, true);
3638 }
3639 }
3640
3641 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3642 IAssistDataReceiver receiver;
3643 synchronized (mGlobalLock) {
3644 mPendingAssistExtras.remove(pae);
3645 receiver = pae.receiver;
3646 }
3647 if (receiver != null) {
3648 // Caller wants result sent back to them.
3649 Bundle sendBundle = new Bundle();
3650 // At least return the receiver extras
3651 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3652 try {
3653 pae.receiver.onHandleAssistData(sendBundle);
3654 } catch (RemoteException e) {
3655 }
3656 }
3657 }
3658
3659 public class PendingAssistExtras extends Binder implements Runnable {
3660 public final ActivityRecord activity;
3661 public boolean isHome;
3662 public final Bundle extras;
3663 public final Intent intent;
3664 public final String hint;
3665 public final IAssistDataReceiver receiver;
3666 public final int userHandle;
3667 public boolean haveResult = false;
3668 public Bundle result = null;
3669 public AssistStructure structure = null;
3670 public AssistContent content = null;
3671 public Bundle receiverExtras;
3672
3673 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3674 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3675 int _userHandle) {
3676 activity = _activity;
3677 extras = _extras;
3678 intent = _intent;
3679 hint = _hint;
3680 receiver = _receiver;
3681 receiverExtras = _receiverExtras;
3682 userHandle = _userHandle;
3683 }
3684
3685 @Override
3686 public void run() {
3687 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3688 synchronized (this) {
3689 haveResult = true;
3690 notifyAll();
3691 }
3692 pendingAssistExtrasTimedOut(this);
3693 }
3694 }
3695
3696 @Override
3697 public boolean isAssistDataAllowedOnCurrentActivity() {
3698 int userId;
3699 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003700 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003701 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3702 return false;
3703 }
3704
3705 final ActivityRecord activity = focusedStack.getTopActivity();
3706 if (activity == null) {
3707 return false;
3708 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003709 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710 }
3711 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3712 }
3713
3714 @Override
3715 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3716 long ident = Binder.clearCallingIdentity();
3717 try {
3718 synchronized (mGlobalLock) {
3719 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003720 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 if (top != caller) {
3722 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3723 + " is not current top " + top);
3724 return false;
3725 }
3726 if (!top.nowVisible) {
3727 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3728 + " is not visible");
3729 return false;
3730 }
3731 }
3732 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3733 token);
3734 } finally {
3735 Binder.restoreCallingIdentity(ident);
3736 }
3737 }
3738
3739 @Override
3740 public boolean isRootVoiceInteraction(IBinder token) {
3741 synchronized (mGlobalLock) {
3742 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3743 if (r == null) {
3744 return false;
3745 }
3746 return r.rootVoiceInteraction;
3747 }
3748 }
3749
Wale Ogunwalef6733932018-06-27 05:14:34 -07003750 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3751 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3752 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3753 if (activityToCallback == null) return;
3754 activityToCallback.setVoiceSessionLocked(voiceSession);
3755
3756 // Inform the activity
3757 try {
3758 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3759 voiceInteractor);
3760 long token = Binder.clearCallingIdentity();
3761 try {
3762 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3763 } finally {
3764 Binder.restoreCallingIdentity(token);
3765 }
3766 // TODO: VI Should we cache the activity so that it's easier to find later
3767 // rather than scan through all the stacks and activities?
3768 } catch (RemoteException re) {
3769 activityToCallback.clearVoiceSessionLocked();
3770 // TODO: VI Should this terminate the voice session?
3771 }
3772 }
3773
3774 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3775 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3776 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3777 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3778 boolean wasRunningVoice = mRunningVoice != null;
3779 mRunningVoice = session;
3780 if (!wasRunningVoice) {
3781 mVoiceWakeLock.acquire();
3782 updateSleepIfNeededLocked();
3783 }
3784 }
3785 }
3786
3787 void finishRunningVoiceLocked() {
3788 if (mRunningVoice != null) {
3789 mRunningVoice = null;
3790 mVoiceWakeLock.release();
3791 updateSleepIfNeededLocked();
3792 }
3793 }
3794
3795 @Override
3796 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3797 synchronized (mGlobalLock) {
3798 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3799 if (keepAwake) {
3800 mVoiceWakeLock.acquire();
3801 } else {
3802 mVoiceWakeLock.release();
3803 }
3804 }
3805 }
3806 }
3807
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 @Override
3809 public ComponentName getActivityClassForToken(IBinder token) {
3810 synchronized (mGlobalLock) {
3811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3812 if (r == null) {
3813 return null;
3814 }
3815 return r.intent.getComponent();
3816 }
3817 }
3818
3819 @Override
3820 public String getPackageForToken(IBinder token) {
3821 synchronized (mGlobalLock) {
3822 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3823 if (r == null) {
3824 return null;
3825 }
3826 return r.packageName;
3827 }
3828 }
3829
3830 @Override
3831 public void showLockTaskEscapeMessage(IBinder token) {
3832 synchronized (mGlobalLock) {
3833 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3834 if (r == null) {
3835 return;
3836 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003837 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 }
3839 }
3840
3841 @Override
3842 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003843 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 final long token = Binder.clearCallingIdentity();
3845 try {
3846 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003847 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 }
3849 } finally {
3850 Binder.restoreCallingIdentity(token);
3851 }
3852 }
3853
3854 /**
3855 * Try to place task to provided position. The final position might be different depending on
3856 * current user and stacks state. The task will be moved to target stack if it's currently in
3857 * different stack.
3858 */
3859 @Override
3860 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003861 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 synchronized (mGlobalLock) {
3863 long ident = Binder.clearCallingIdentity();
3864 try {
3865 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3866 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003867 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003868 if (task == null) {
3869 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3870 + taskId);
3871 }
3872
Wale Ogunwaled32da472018-11-16 07:19:28 -08003873 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003874
3875 if (stack == null) {
3876 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3877 + stackId);
3878 }
3879 if (!stack.isActivityTypeStandardOrUndefined()) {
3880 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3881 + " the position of task " + taskId + " in/to non-standard stack");
3882 }
3883
3884 // TODO: Have the callers of this API call a separate reparent method if that is
3885 // what they intended to do vs. having this method also do reparenting.
3886 if (task.getStack() == stack) {
3887 // Change position in current stack.
3888 stack.positionChildAt(task, position);
3889 } else {
3890 // Reparent to new stack.
3891 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3892 !DEFER_RESUME, "positionTaskInStack");
3893 }
3894 } finally {
3895 Binder.restoreCallingIdentity(ident);
3896 }
3897 }
3898 }
3899
3900 @Override
3901 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3902 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3903 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3904 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3905 synchronized (mGlobalLock) {
3906 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3907 if (record == null) {
3908 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3909 + "found for: " + token);
3910 }
3911 record.setSizeConfigurations(horizontalSizeConfiguration,
3912 verticalSizeConfigurations, smallestSizeConfigurations);
3913 }
3914 }
3915
3916 /**
3917 * Dismisses split-screen multi-window mode.
3918 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3919 */
3920 @Override
3921 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3924 final long ident = Binder.clearCallingIdentity();
3925 try {
3926 synchronized (mGlobalLock) {
3927 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003928 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 if (stack == null) {
3930 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3931 return;
3932 }
3933
3934 if (toTop) {
3935 // Caller wants the current split-screen primary stack to be the top stack after
3936 // it goes fullscreen, so move it to the front.
3937 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003938 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 // In this case the current split-screen primary stack shouldn't be the top
3940 // stack after it goes fullscreen, but it current has focus, so we move the
3941 // focus to the top-most split-screen secondary stack next to it.
3942 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3943 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3944 if (otherStack != null) {
3945 otherStack.moveToFront("dismissSplitScreenMode_other");
3946 }
3947 }
3948
Evan Rosky10475742018-09-05 19:02:48 -07003949 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 }
3951 } finally {
3952 Binder.restoreCallingIdentity(ident);
3953 }
3954 }
3955
3956 /**
3957 * Dismisses Pip
3958 * @param animate True if the dismissal should be animated.
3959 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3960 * default animation duration should be used.
3961 */
3962 @Override
3963 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003964 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 final long ident = Binder.clearCallingIdentity();
3966 try {
3967 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003968 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003969 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003970 if (stack == null) {
3971 Slog.w(TAG, "dismissPip: pinned stack not found.");
3972 return;
3973 }
3974 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3975 throw new IllegalArgumentException("Stack: " + stack
3976 + " doesn't support animated resize.");
3977 }
3978 if (animate) {
3979 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3980 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3981 } else {
3982 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3983 }
3984 }
3985 } finally {
3986 Binder.restoreCallingIdentity(ident);
3987 }
3988 }
3989
3990 @Override
3991 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 synchronized (mGlobalLock) {
3994 mSuppressResizeConfigChanges = suppress;
3995 }
3996 }
3997
3998 /**
3999 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4000 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4001 * activity and clearing the task at the same time.
4002 */
4003 @Override
4004 // TODO: API should just be about changing windowing modes...
4005 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004006 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 "moveTasksToFullscreenStack()");
4008 synchronized (mGlobalLock) {
4009 final long origId = Binder.clearCallingIdentity();
4010 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004011 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 if (stack != null){
4013 if (!stack.isActivityTypeStandardOrUndefined()) {
4014 throw new IllegalArgumentException(
4015 "You can't move tasks from non-standard stacks.");
4016 }
4017 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4018 }
4019 } finally {
4020 Binder.restoreCallingIdentity(origId);
4021 }
4022 }
4023 }
4024
4025 /**
4026 * Moves the top activity in the input stackId to the pinned stack.
4027 *
4028 * @param stackId Id of stack to move the top activity to pinned stack.
4029 * @param bounds Bounds to use for pinned stack.
4030 *
4031 * @return True if the top activity of the input stack was successfully moved to the pinned
4032 * stack.
4033 */
4034 @Override
4035 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004036 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 "moveTopActivityToPinnedStack()");
4038 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004039 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4041 + "Device doesn't support picture-in-picture mode");
4042 }
4043
4044 long ident = Binder.clearCallingIdentity();
4045 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004046 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 } finally {
4048 Binder.restoreCallingIdentity(ident);
4049 }
4050 }
4051 }
4052
4053 @Override
4054 public boolean isInMultiWindowMode(IBinder token) {
4055 final long origId = Binder.clearCallingIdentity();
4056 try {
4057 synchronized (mGlobalLock) {
4058 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4059 if (r == null) {
4060 return false;
4061 }
4062 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4063 return r.inMultiWindowMode();
4064 }
4065 } finally {
4066 Binder.restoreCallingIdentity(origId);
4067 }
4068 }
4069
4070 @Override
4071 public boolean isInPictureInPictureMode(IBinder token) {
4072 final long origId = Binder.clearCallingIdentity();
4073 try {
4074 synchronized (mGlobalLock) {
4075 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4076 }
4077 } finally {
4078 Binder.restoreCallingIdentity(origId);
4079 }
4080 }
4081
4082 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004083 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4084 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 return false;
4086 }
4087
4088 // If we are animating to fullscreen then we have already dispatched the PIP mode
4089 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004090 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4091 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 }
4093
4094 @Override
4095 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4096 final long origId = Binder.clearCallingIdentity();
4097 try {
4098 synchronized (mGlobalLock) {
4099 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4100 "enterPictureInPictureMode", token, params);
4101
4102 // If the activity is already in picture in picture mode, then just return early
4103 if (isInPictureInPictureMode(r)) {
4104 return true;
4105 }
4106
4107 // Activity supports picture-in-picture, now check that we can enter PiP at this
4108 // point, if it is
4109 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4110 false /* beforeStopping */)) {
4111 return false;
4112 }
4113
4114 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004115 synchronized (mGlobalLock) {
4116 // Only update the saved args from the args that are set
4117 r.pictureInPictureArgs.copyOnlySet(params);
4118 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4119 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4120 // Adjust the source bounds by the insets for the transition down
4121 final Rect sourceBounds = new Rect(
4122 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004123 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004124 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004125 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004126 stack.setPictureInPictureAspectRatio(aspectRatio);
4127 stack.setPictureInPictureActions(actions);
4128 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4129 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4130 logPictureInPictureArgs(params);
4131 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 };
4133
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004134 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004135 // If the keyguard is showing or occluded, then try and dismiss it before
4136 // entering picture-in-picture (this will prompt the user to authenticate if the
4137 // device is currently locked).
4138 dismissKeyguard(token, new KeyguardDismissCallback() {
4139 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004140 public void onDismissSucceeded() {
4141 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004142 }
4143 }, null /* message */);
4144 } else {
4145 // Enter picture in picture immediately otherwise
4146 enterPipRunnable.run();
4147 }
4148 return true;
4149 }
4150 } finally {
4151 Binder.restoreCallingIdentity(origId);
4152 }
4153 }
4154
4155 @Override
4156 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4157 final long origId = Binder.clearCallingIdentity();
4158 try {
4159 synchronized (mGlobalLock) {
4160 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4161 "setPictureInPictureParams", token, params);
4162
4163 // Only update the saved args from the args that are set
4164 r.pictureInPictureArgs.copyOnlySet(params);
4165 if (r.inPinnedWindowingMode()) {
4166 // If the activity is already in picture-in-picture, update the pinned stack now
4167 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4168 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 if (!stack.isAnimatingBoundsToFullscreen()) {
4171 stack.setPictureInPictureAspectRatio(
4172 r.pictureInPictureArgs.getAspectRatio());
4173 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4174 }
4175 }
4176 logPictureInPictureArgs(params);
4177 }
4178 } finally {
4179 Binder.restoreCallingIdentity(origId);
4180 }
4181 }
4182
4183 @Override
4184 public int getMaxNumPictureInPictureActions(IBinder token) {
4185 // Currently, this is a static constant, but later, we may change this to be dependent on
4186 // the context of the activity
4187 return 3;
4188 }
4189
4190 private void logPictureInPictureArgs(PictureInPictureParams params) {
4191 if (params.hasSetActions()) {
4192 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4193 params.getActions().size());
4194 }
4195 if (params.hasSetAspectRatio()) {
4196 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4197 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4198 MetricsLogger.action(lm);
4199 }
4200 }
4201
4202 /**
4203 * Checks the state of the system and the activity associated with the given {@param token} to
4204 * verify that picture-in-picture is supported for that activity.
4205 *
4206 * @return the activity record for the given {@param token} if all the checks pass.
4207 */
4208 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4209 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004210 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 throw new IllegalStateException(caller
4212 + ": Device doesn't support picture-in-picture mode.");
4213 }
4214
4215 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4216 if (r == null) {
4217 throw new IllegalStateException(caller
4218 + ": Can't find activity for token=" + token);
4219 }
4220
4221 if (!r.supportsPictureInPicture()) {
4222 throw new IllegalStateException(caller
4223 + ": Current activity does not support picture-in-picture.");
4224 }
4225
4226 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004227 && !mWindowManager.isValidPictureInPictureAspectRatio(
4228 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 final float minAspectRatio = mContext.getResources().getFloat(
4230 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4231 final float maxAspectRatio = mContext.getResources().getFloat(
4232 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4233 throw new IllegalArgumentException(String.format(caller
4234 + ": Aspect ratio is too extreme (must be between %f and %f).",
4235 minAspectRatio, maxAspectRatio));
4236 }
4237
4238 // Truncate the number of actions if necessary
4239 params.truncateActions(getMaxNumPictureInPictureActions(token));
4240
4241 return r;
4242 }
4243
4244 @Override
4245 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004246 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 synchronized (mGlobalLock) {
4248 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4249 if (r == null) {
4250 throw new IllegalArgumentException("Activity does not exist; token="
4251 + activityToken);
4252 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004253 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
4255 }
4256
4257 @Override
4258 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4259 Rect tempDockedTaskInsetBounds,
4260 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 long ident = Binder.clearCallingIdentity();
4263 try {
4264 synchronized (mGlobalLock) {
4265 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4266 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4267 PRESERVE_WINDOWS);
4268 }
4269 } finally {
4270 Binder.restoreCallingIdentity(ident);
4271 }
4272 }
4273
4274 @Override
4275 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 final long ident = Binder.clearCallingIdentity();
4278 try {
4279 synchronized (mGlobalLock) {
4280 mStackSupervisor.setSplitScreenResizing(resizing);
4281 }
4282 } finally {
4283 Binder.restoreCallingIdentity(ident);
4284 }
4285 }
4286
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 /**
4288 * Check that we have the features required for VR-related API calls, and throw an exception if
4289 * not.
4290 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004291 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 if (!mContext.getPackageManager().hasSystemFeature(
4293 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4294 throw new UnsupportedOperationException("VR mode not supported on this device!");
4295 }
4296 }
4297
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 @Override
4299 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004300 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301
4302 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4303
4304 ActivityRecord r;
4305 synchronized (mGlobalLock) {
4306 r = ActivityRecord.isInStackLocked(token);
4307 }
4308
4309 if (r == null) {
4310 throw new IllegalArgumentException();
4311 }
4312
4313 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004314 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 VrManagerInternal.NO_ERROR) {
4316 return err;
4317 }
4318
4319 // Clear the binder calling uid since this path may call moveToTask().
4320 final long callingId = Binder.clearCallingIdentity();
4321 try {
4322 synchronized (mGlobalLock) {
4323 r.requestedVrComponent = (enabled) ? packageName : null;
4324
4325 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004326 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004327 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 }
4329 return 0;
4330 }
4331 } finally {
4332 Binder.restoreCallingIdentity(callingId);
4333 }
4334 }
4335
4336 @Override
4337 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4338 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4339 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004340 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4342 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4343 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004344 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 || activity.voiceSession != null) {
4346 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4347 return;
4348 }
4349 if (activity.pendingVoiceInteractionStart) {
4350 Slog.w(TAG, "Pending start of voice interaction already.");
4351 return;
4352 }
4353 activity.pendingVoiceInteractionStart = true;
4354 }
4355 LocalServices.getService(VoiceInteractionManagerInternal.class)
4356 .startLocalVoiceInteraction(callingActivity, options);
4357 }
4358
4359 @Override
4360 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4361 LocalServices.getService(VoiceInteractionManagerInternal.class)
4362 .stopLocalVoiceInteraction(callingActivity);
4363 }
4364
4365 @Override
4366 public boolean supportsLocalVoiceInteraction() {
4367 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4368 .supportsLocalVoiceInteraction();
4369 }
4370
4371 /** Notifies all listeners when the pinned stack animation starts. */
4372 @Override
4373 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004374 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 }
4376
4377 /** Notifies all listeners when the pinned stack animation ends. */
4378 @Override
4379 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004380 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 }
4382
4383 @Override
4384 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 final long ident = Binder.clearCallingIdentity();
4387 try {
4388 synchronized (mGlobalLock) {
4389 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4390 }
4391 } finally {
4392 Binder.restoreCallingIdentity(ident);
4393 }
4394 }
4395
4396 @Override
4397 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004398 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399
4400 synchronized (mGlobalLock) {
4401 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004402 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 // Call might come when display is not yet added or has already been removed.
4404 if (DEBUG_CONFIGURATION) {
4405 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4406 + displayId);
4407 }
4408 return false;
4409 }
4410
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 }
4415
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004416 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004417 final Message msg = PooledLambda.obtainMessage(
4418 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4419 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421
4422 final long origId = Binder.clearCallingIdentity();
4423 try {
4424 if (values != null) {
4425 Settings.System.clearConfiguration(values);
4426 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004427 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4429 return mTmpUpdateConfigurationResult.changes != 0;
4430 } finally {
4431 Binder.restoreCallingIdentity(origId);
4432 }
4433 }
4434 }
4435
4436 @Override
4437 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439
4440 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 }
4445
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004447 final Message msg = PooledLambda.obtainMessage(
4448 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4449 DEFAULT_DISPLAY);
4450 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 }
4452
4453 final long origId = Binder.clearCallingIdentity();
4454 try {
4455 if (values != null) {
4456 Settings.System.clearConfiguration(values);
4457 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004458 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 UserHandle.USER_NULL, false /* deferResume */,
4460 mTmpUpdateConfigurationResult);
4461 return mTmpUpdateConfigurationResult.changes != 0;
4462 } finally {
4463 Binder.restoreCallingIdentity(origId);
4464 }
4465 }
4466 }
4467
4468 @Override
4469 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4470 CharSequence message) {
4471 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4474 }
4475 final long callingId = Binder.clearCallingIdentity();
4476 try {
4477 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004478 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479 }
4480 } finally {
4481 Binder.restoreCallingIdentity(callingId);
4482 }
4483 }
4484
4485 @Override
4486 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004487 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 "cancelTaskWindowTransition()");
4489 final long ident = Binder.clearCallingIdentity();
4490 try {
4491 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004492 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 MATCH_TASK_IN_STACKS_ONLY);
4494 if (task == null) {
4495 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4496 return;
4497 }
4498 task.cancelWindowTransition();
4499 }
4500 } finally {
4501 Binder.restoreCallingIdentity(ident);
4502 }
4503 }
4504
4505 @Override
4506 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 final long ident = Binder.clearCallingIdentity();
4509 try {
4510 final TaskRecord task;
4511 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004512 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4514 if (task == null) {
4515 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4516 return null;
4517 }
4518 }
4519 // Don't call this while holding the lock as this operation might hit the disk.
4520 return task.getSnapshot(reducedResolution);
4521 } finally {
4522 Binder.restoreCallingIdentity(ident);
4523 }
4524 }
4525
4526 @Override
4527 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4528 synchronized (mGlobalLock) {
4529 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4530 if (r == null) {
4531 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4532 + token);
4533 return;
4534 }
4535 final long origId = Binder.clearCallingIdentity();
4536 try {
4537 r.setDisablePreviewScreenshots(disable);
4538 } finally {
4539 Binder.restoreCallingIdentity(origId);
4540 }
4541 }
4542 }
4543
4544 /** Return the user id of the last resumed activity. */
4545 @Override
4546 public @UserIdInt
4547 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004548 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4550 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004551 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004554 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004555 }
4556 }
4557
4558 @Override
4559 public void updateLockTaskFeatures(int userId, int flags) {
4560 final int callingUid = Binder.getCallingUid();
4561 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004562 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 "updateLockTaskFeatures()");
4564 }
4565 synchronized (mGlobalLock) {
4566 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4567 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004568 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 }
4570 }
4571
4572 @Override
4573 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4574 synchronized (mGlobalLock) {
4575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4576 if (r == null) {
4577 return;
4578 }
4579 final long origId = Binder.clearCallingIdentity();
4580 try {
4581 r.setShowWhenLocked(showWhenLocked);
4582 } finally {
4583 Binder.restoreCallingIdentity(origId);
4584 }
4585 }
4586 }
4587
4588 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004589 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4590 synchronized (mGlobalLock) {
4591 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4592 if (r == null) {
4593 return;
4594 }
4595 final long origId = Binder.clearCallingIdentity();
4596 try {
4597 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4598 } finally {
4599 Binder.restoreCallingIdentity(origId);
4600 }
4601 }
4602 }
4603
4604 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004605 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4606 synchronized (mGlobalLock) {
4607 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4608 if (r == null) {
4609 return;
4610 }
4611 final long origId = Binder.clearCallingIdentity();
4612 try {
4613 r.setTurnScreenOn(turnScreenOn);
4614 } finally {
4615 Binder.restoreCallingIdentity(origId);
4616 }
4617 }
4618 }
4619
4620 @Override
4621 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004622 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004623 "registerRemoteAnimations");
4624 definition.setCallingPid(Binder.getCallingPid());
4625 synchronized (mGlobalLock) {
4626 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4627 if (r == null) {
4628 return;
4629 }
4630 final long origId = Binder.clearCallingIdentity();
4631 try {
4632 r.registerRemoteAnimations(definition);
4633 } finally {
4634 Binder.restoreCallingIdentity(origId);
4635 }
4636 }
4637 }
4638
4639 @Override
4640 public void registerRemoteAnimationForNextActivityStart(String packageName,
4641 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004642 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004643 "registerRemoteAnimationForNextActivityStart");
4644 adapter.setCallingPid(Binder.getCallingPid());
4645 synchronized (mGlobalLock) {
4646 final long origId = Binder.clearCallingIdentity();
4647 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004648 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004649 packageName, adapter);
4650 } finally {
4651 Binder.restoreCallingIdentity(origId);
4652 }
4653 }
4654 }
4655
Evan Rosky966759f2019-01-15 10:33:58 -08004656 @Override
4657 public void registerRemoteAnimationsForDisplay(int displayId,
4658 RemoteAnimationDefinition definition) {
4659 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4660 "registerRemoteAnimations");
4661 definition.setCallingPid(Binder.getCallingPid());
4662 synchronized (mGlobalLock) {
4663 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4664 if (display == null) {
4665 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4666 return;
4667 }
4668 final long origId = Binder.clearCallingIdentity();
4669 try {
4670 display.mDisplayContent.registerRemoteAnimations(definition);
4671 } finally {
4672 Binder.restoreCallingIdentity(origId);
4673 }
4674 }
4675 }
4676
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004677 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4678 @Override
4679 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4680 synchronized (mGlobalLock) {
4681 final long origId = Binder.clearCallingIdentity();
4682 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004683 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004684 } finally {
4685 Binder.restoreCallingIdentity(origId);
4686 }
4687 }
4688 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004689
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004690 @Override
4691 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004692 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004693 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004694 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004695 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004696 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004697 }
4698 }
4699
4700 @Override
4701 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004702 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004703 != PERMISSION_GRANTED) {
4704 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4705 + Binder.getCallingPid()
4706 + ", uid=" + Binder.getCallingUid()
4707 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4708 Slog.w(TAG, msg);
4709 throw new SecurityException(msg);
4710 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004711 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004713 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004714 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004715 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004716 }
4717 }
4718
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004719 @Override
4720 public void stopAppSwitches() {
4721 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4722 synchronized (mGlobalLock) {
4723 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4724 mDidAppSwitch = false;
4725 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4726 }
4727 }
4728
4729 @Override
4730 public void resumeAppSwitches() {
4731 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4732 synchronized (mGlobalLock) {
4733 // Note that we don't execute any pending app switches... we will
4734 // let those wait until either the timeout, or the next start
4735 // activity request.
4736 mAppSwitchesAllowedTime = 0;
4737 }
4738 }
4739
4740 void onStartActivitySetDidAppSwitch() {
4741 if (mDidAppSwitch) {
4742 // This is the second allowed switch since we stopped switches, so now just generally
4743 // allow switches. Use case:
4744 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4745 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4746 // anyone to switch again).
4747 mAppSwitchesAllowedTime = 0;
4748 } else {
4749 mDidAppSwitch = true;
4750 }
4751 }
4752
4753 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004754 boolean shouldDisableNonVrUiLocked() {
4755 return mVrController.shouldDisableNonVrUiLocked();
4756 }
4757
Wale Ogunwale53783742018-09-16 10:21:51 -07004758 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004759 // VR apps are expected to run in a main display. If an app is turning on VR for
4760 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4761 // fullscreen stack before enabling VR Mode.
4762 // TODO: The goal of this code is to keep the VR app on the main display. When the
4763 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4764 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4765 // option would be a better choice here.
4766 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4767 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4768 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004769 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004770 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004771 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004772 }
4773 mH.post(() -> {
4774 if (!mVrController.onVrModeChanged(r)) {
4775 return;
4776 }
4777 synchronized (mGlobalLock) {
4778 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4779 mWindowManager.disableNonVrUi(disableNonVrUi);
4780 if (disableNonVrUi) {
4781 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4782 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004783 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004784 }
4785 }
4786 });
4787 }
4788
Wale Ogunwale53783742018-09-16 10:21:51 -07004789 @Override
4790 public int getPackageScreenCompatMode(String packageName) {
4791 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4792 synchronized (mGlobalLock) {
4793 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4794 }
4795 }
4796
4797 @Override
4798 public void setPackageScreenCompatMode(String packageName, int mode) {
4799 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4800 "setPackageScreenCompatMode");
4801 synchronized (mGlobalLock) {
4802 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4803 }
4804 }
4805
4806 @Override
4807 public boolean getPackageAskScreenCompat(String packageName) {
4808 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4809 synchronized (mGlobalLock) {
4810 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4811 }
4812 }
4813
4814 @Override
4815 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4816 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4817 "setPackageAskScreenCompat");
4818 synchronized (mGlobalLock) {
4819 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4820 }
4821 }
4822
Wale Ogunwale64258362018-10-16 15:13:37 -07004823 public static String relaunchReasonToString(int relaunchReason) {
4824 switch (relaunchReason) {
4825 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4826 return "window_resize";
4827 case RELAUNCH_REASON_FREE_RESIZE:
4828 return "free_resize";
4829 default:
4830 return null;
4831 }
4832 }
4833
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004834 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004835 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004836 }
4837
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004838 /** Pokes the task persister. */
4839 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4840 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4841 }
4842
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004843 boolean isKeyguardLocked() {
4844 return mKeyguardController.isKeyguardLocked();
4845 }
4846
Garfield Tan01548632018-11-27 10:15:48 -08004847 /**
4848 * Clears launch params for the given package.
4849 * @param packageNames the names of the packages of which the launch params are to be cleared
4850 */
4851 @Override
4852 public void clearLaunchParamsForPackages(List<String> packageNames) {
4853 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4854 "clearLaunchParamsForPackages");
4855 synchronized (mGlobalLock) {
4856 for (int i = 0; i < packageNames.size(); ++i) {
4857 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4858 }
4859 }
4860 }
4861
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004862 /**
4863 * Makes the display with the given id a single task instance display. I.e the display can only
4864 * contain one task.
4865 */
4866 @Override
4867 public void setDisplayToSingleTaskInstance(int displayId) {
4868 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4869 "setDisplayToSingleTaskInstance");
4870 final long origId = Binder.clearCallingIdentity();
4871 try {
4872 final ActivityDisplay display =
4873 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4874 if (display != null) {
4875 display.setDisplayToSingleTaskInstance();
4876 }
4877 } finally {
4878 Binder.restoreCallingIdentity(origId);
4879 }
4880 }
4881
Wale Ogunwale31913b52018-10-13 08:29:31 -07004882 void dumpLastANRLocked(PrintWriter pw) {
4883 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4884 if (mLastANRState == null) {
4885 pw.println(" <no ANR has occurred since boot>");
4886 } else {
4887 pw.println(mLastANRState);
4888 }
4889 }
4890
4891 void dumpLastANRTracesLocked(PrintWriter pw) {
4892 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4893
4894 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4895 if (ArrayUtils.isEmpty(files)) {
4896 pw.println(" <no ANR has occurred since boot>");
4897 return;
4898 }
4899 // Find the latest file.
4900 File latest = null;
4901 for (File f : files) {
4902 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4903 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004904 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004905 }
4906 pw.print("File: ");
4907 pw.print(latest.getName());
4908 pw.println();
4909 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4910 String line;
4911 while ((line = in.readLine()) != null) {
4912 pw.println(line);
4913 }
4914 } catch (IOException e) {
4915 pw.print("Unable to read: ");
4916 pw.print(e);
4917 pw.println();
4918 }
4919 }
4920
4921 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4922 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4923 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4924 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4925 }
4926
4927 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4928 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4929 pw.println(header);
4930
Wale Ogunwaled32da472018-11-16 07:19:28 -08004931 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004932 dumpPackage);
4933 boolean needSep = printedAnything;
4934
4935 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004936 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 " ResumedActivity: ");
4938 if (printed) {
4939 printedAnything = true;
4940 needSep = false;
4941 }
4942
4943 if (dumpPackage == null) {
4944 if (needSep) {
4945 pw.println();
4946 }
4947 printedAnything = true;
4948 mStackSupervisor.dump(pw, " ");
4949 }
4950
4951 if (!printedAnything) {
4952 pw.println(" (nothing)");
4953 }
4954 }
4955
4956 void dumpActivityContainersLocked(PrintWriter pw) {
4957 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004958 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004959 pw.println(" ");
4960 }
4961
4962 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4963 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4964 getActivityStartController().dump(pw, "", dumpPackage);
4965 }
4966
4967 /**
4968 * There are three things that cmd can be:
4969 * - a flattened component name that matches an existing activity
4970 * - the cmd arg isn't the flattened component name of an existing activity:
4971 * dump all activity whose component contains the cmd as a substring
4972 * - A hex number of the ActivityRecord object instance.
4973 *
4974 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4975 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4976 */
4977 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4978 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4979 ArrayList<ActivityRecord> activities;
4980
4981 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004982 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004983 dumpFocusedStackOnly);
4984 }
4985
4986 if (activities.size() <= 0) {
4987 return false;
4988 }
4989
4990 String[] newArgs = new String[args.length - opti];
4991 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4992
4993 TaskRecord lastTask = null;
4994 boolean needSep = false;
4995 for (int i = activities.size() - 1; i >= 0; i--) {
4996 ActivityRecord r = activities.get(i);
4997 if (needSep) {
4998 pw.println();
4999 }
5000 needSep = true;
5001 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005002 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005003 if (lastTask != task) {
5004 lastTask = task;
5005 pw.print("TASK "); pw.print(lastTask.affinity);
5006 pw.print(" id="); pw.print(lastTask.taskId);
5007 pw.print(" userId="); pw.println(lastTask.userId);
5008 if (dumpAll) {
5009 lastTask.dump(pw, " ");
5010 }
5011 }
5012 }
5013 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5014 }
5015 return true;
5016 }
5017
5018 /**
5019 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5020 * there is a thread associated with the activity.
5021 */
5022 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5023 final ActivityRecord r, String[] args, boolean dumpAll) {
5024 String innerPrefix = prefix + " ";
5025 synchronized (mGlobalLock) {
5026 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5027 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5028 pw.print(" pid=");
5029 if (r.hasProcess()) pw.println(r.app.getPid());
5030 else pw.println("(not running)");
5031 if (dumpAll) {
5032 r.dump(pw, innerPrefix);
5033 }
5034 }
5035 if (r.attachedToProcess()) {
5036 // flush anything that is already in the PrintWriter since the thread is going
5037 // to write to the file descriptor directly
5038 pw.flush();
5039 try {
5040 TransferPipe tp = new TransferPipe();
5041 try {
5042 r.app.getThread().dumpActivity(tp.getWriteFd(),
5043 r.appToken, innerPrefix, args);
5044 tp.go(fd);
5045 } finally {
5046 tp.kill();
5047 }
5048 } catch (IOException e) {
5049 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5050 } catch (RemoteException e) {
5051 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5052 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005053 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005054 }
5055
sanryhuang498e77e2018-12-06 14:57:01 +08005056 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5057 boolean testPssMode) {
5058 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5059 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5060 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005061 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005062 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5063 st.toString());
5064 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005065 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5066 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5067 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005068 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5069 testPssMode);
5070 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005071 }
5072
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 int getCurrentUserId() {
5074 return mAmInternal.getCurrentUserId();
5075 }
5076
5077 private void enforceNotIsolatedCaller(String caller) {
5078 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5079 throw new SecurityException("Isolated process not allowed to call " + caller);
5080 }
5081 }
5082
Wale Ogunwalef6733932018-06-27 05:14:34 -07005083 public Configuration getConfiguration() {
5084 Configuration ci;
5085 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005086 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005087 ci.userSetLocale = false;
5088 }
5089 return ci;
5090 }
5091
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005092 /**
5093 * Current global configuration information. Contains general settings for the entire system,
5094 * also corresponds to the merged configuration of the default display.
5095 */
5096 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005097 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005098 }
5099
5100 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5101 boolean initLocale) {
5102 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5103 }
5104
5105 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5106 boolean initLocale, boolean deferResume) {
5107 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5108 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5109 UserHandle.USER_NULL, deferResume);
5110 }
5111
Wale Ogunwale59507092018-10-29 09:00:30 -07005112 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005113 final long origId = Binder.clearCallingIdentity();
5114 try {
5115 synchronized (mGlobalLock) {
5116 updateConfigurationLocked(values, null, false, true, userId,
5117 false /* deferResume */);
5118 }
5119 } finally {
5120 Binder.restoreCallingIdentity(origId);
5121 }
5122 }
5123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5125 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5126 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5127 deferResume, null /* result */);
5128 }
5129
5130 /**
5131 * Do either or both things: (1) change the current configuration, and (2)
5132 * make sure the given activity is running with the (now) current
5133 * configuration. Returns true if the activity has been left running, or
5134 * false if <var>starting</var> is being destroyed to match the new
5135 * configuration.
5136 *
5137 * @param userId is only used when persistent parameter is set to true to persist configuration
5138 * for that particular user
5139 */
5140 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5141 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5142 ActivityTaskManagerService.UpdateConfigurationResult result) {
5143 int changes = 0;
5144 boolean kept = true;
5145
5146 if (mWindowManager != null) {
5147 mWindowManager.deferSurfaceLayout();
5148 }
5149 try {
5150 if (values != null) {
5151 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5152 deferResume);
5153 }
5154
5155 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5156 } finally {
5157 if (mWindowManager != null) {
5158 mWindowManager.continueSurfaceLayout();
5159 }
5160 }
5161
5162 if (result != null) {
5163 result.changes = changes;
5164 result.activityRelaunched = !kept;
5165 }
5166 return kept;
5167 }
5168
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005169 /** Update default (global) configuration and notify listeners about changes. */
5170 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5171 boolean persistent, int userId, boolean deferResume) {
5172 mTempConfig.setTo(getGlobalConfiguration());
5173 final int changes = mTempConfig.updateFrom(values);
5174 if (changes == 0) {
5175 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5176 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5177 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5178 // (even if there are no actual changes) to unfreeze the window.
5179 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5180 return 0;
5181 }
5182
5183 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5184 "Updating global configuration to: " + values);
5185
5186 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5187 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5188 values.colorMode,
5189 values.densityDpi,
5190 values.fontScale,
5191 values.hardKeyboardHidden,
5192 values.keyboard,
5193 values.keyboardHidden,
5194 values.mcc,
5195 values.mnc,
5196 values.navigation,
5197 values.navigationHidden,
5198 values.orientation,
5199 values.screenHeightDp,
5200 values.screenLayout,
5201 values.screenWidthDp,
5202 values.smallestScreenWidthDp,
5203 values.touchscreen,
5204 values.uiMode);
5205
5206
5207 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5208 final LocaleList locales = values.getLocales();
5209 int bestLocaleIndex = 0;
5210 if (locales.size() > 1) {
5211 if (mSupportedSystemLocales == null) {
5212 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5213 }
5214 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5215 }
5216 SystemProperties.set("persist.sys.locale",
5217 locales.get(bestLocaleIndex).toLanguageTag());
5218 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005219
5220 final Message m = PooledLambda.obtainMessage(
5221 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5222 locales.get(bestLocaleIndex));
5223 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 }
5225
Yunfan Chen75157d72018-07-27 14:47:21 +09005226 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227
5228 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005229 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230
5231 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5232 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005233 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234
5235 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005236 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237
5238 AttributeCache ac = AttributeCache.instance();
5239 if (ac != null) {
5240 ac.updateConfiguration(mTempConfig);
5241 }
5242
5243 // Make sure all resources in our process are updated right now, so that anyone who is going
5244 // to retrieve resource values after we return will be sure to get the new ones. This is
5245 // especially important during boot, where the first config change needs to guarantee all
5246 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005247 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248
5249 // We need another copy of global config because we're scheduling some calls instead of
5250 // running them in place. We need to be sure that object we send will be handled unchanged.
5251 final Configuration configCopy = new Configuration(mTempConfig);
5252 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005253 final Message msg = PooledLambda.obtainMessage(
5254 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5255 this, userId, configCopy);
5256 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005257 }
5258
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005259 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5260 for (int i = pidMap.size() - 1; i >= 0; i--) {
5261 final int pid = pidMap.keyAt(i);
5262 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005263 if (DEBUG_CONFIGURATION) {
5264 Slog.v(TAG_CONFIGURATION, "Update process config of "
5265 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005267 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268 }
5269
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005270 final Message msg = PooledLambda.obtainMessage(
5271 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5272 mAmInternal, changes, initLocale);
5273 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274
5275 // Override configuration of the default display duplicates global config, so we need to
5276 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005277 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 DEFAULT_DISPLAY);
5279
5280 return changes;
5281 }
5282
5283 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5284 boolean deferResume, int displayId) {
5285 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5286 displayId, null /* result */);
5287 }
5288
5289 /**
5290 * Updates override configuration specific for the selected display. If no config is provided,
5291 * new one will be computed in WM based on current display info.
5292 */
5293 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5294 ActivityRecord starting, boolean deferResume, int displayId,
5295 ActivityTaskManagerService.UpdateConfigurationResult result) {
5296 int changes = 0;
5297 boolean kept = true;
5298
5299 if (mWindowManager != null) {
5300 mWindowManager.deferSurfaceLayout();
5301 }
5302 try {
5303 if (values != null) {
5304 if (displayId == DEFAULT_DISPLAY) {
5305 // Override configuration of the default display duplicates global config, so
5306 // we're calling global config update instead for default display. It will also
5307 // apply the correct override config.
5308 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5309 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5310 } else {
5311 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5312 }
5313 }
5314
5315 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5316 } finally {
5317 if (mWindowManager != null) {
5318 mWindowManager.continueSurfaceLayout();
5319 }
5320 }
5321
5322 if (result != null) {
5323 result.changes = changes;
5324 result.activityRelaunched = !kept;
5325 }
5326 return kept;
5327 }
5328
5329 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5330 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005331 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005332 final int changes = mTempConfig.updateFrom(values);
5333 if (changes != 0) {
5334 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5335 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005336 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337
5338 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5339 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005340 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005341
Wale Ogunwale5c918702018-10-18 11:06:33 -07005342 // Post message to start process to avoid possible deadlock of calling into AMS with
5343 // the ATMS lock held.
5344 final Message msg = PooledLambda.obtainMessage(
5345 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005346 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005347 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005348 }
5349 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005350 return changes;
5351 }
5352
Wale Ogunwalef6733932018-06-27 05:14:34 -07005353 private void updateEventDispatchingLocked(boolean booted) {
5354 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5355 }
5356
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005357 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5358 final ContentResolver resolver = mContext.getContentResolver();
5359 Settings.System.putConfigurationForUser(resolver, config, userId);
5360 }
5361
5362 private void sendLocaleToMountDaemonMsg(Locale l) {
5363 try {
5364 IBinder service = ServiceManager.getService("mount");
5365 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5366 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5367 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5368 } catch (RemoteException e) {
5369 Log.e(TAG, "Error storing locale for decryption UI", e);
5370 }
5371 }
5372
Alison Cichowlas3e340502018-08-07 17:15:01 -04005373 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5374 mStartActivitySources.remove(permissionToken);
5375 mExpiredStartAsCallerTokens.add(permissionToken);
5376 }
5377
5378 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5379 mExpiredStartAsCallerTokens.remove(permissionToken);
5380 }
5381
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005382 boolean isActivityStartsLoggingEnabled() {
5383 return mAmInternal.isActivityStartsLoggingEnabled();
5384 }
5385
Michal Karpinski8596ded2018-11-14 14:43:48 +00005386 boolean isBackgroundActivityStartsEnabled() {
5387 return mAmInternal.isBackgroundActivityStartsEnabled();
5388 }
5389
Ricky Waiaca8a772019-04-04 16:01:06 +01005390 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5391 if (packageName == null) {
5392 return false;
5393 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005394 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5395 }
5396
Wale Ogunwalef6733932018-06-27 05:14:34 -07005397 void enableScreenAfterBoot(boolean booted) {
5398 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5399 SystemClock.uptimeMillis());
5400 mWindowManager.enableScreenAfterBoot();
5401
5402 synchronized (mGlobalLock) {
5403 updateEventDispatchingLocked(booted);
5404 }
5405 }
5406
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005407 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5408 if (r == null || !r.hasProcess()) {
5409 return KEY_DISPATCHING_TIMEOUT_MS;
5410 }
5411 return getInputDispatchingTimeoutLocked(r.app);
5412 }
5413
5414 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005415 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005416 }
5417
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 /**
5419 * Decide based on the configuration whether we should show the ANR,
5420 * crash, etc dialogs. The idea is that if there is no affordance to
5421 * press the on-screen buttons, or the user experience would be more
5422 * greatly impacted than the crash itself, we shouldn't show the dialog.
5423 *
5424 * A thought: SystemUI might also want to get told about this, the Power
5425 * dialog / global actions also might want different behaviors.
5426 */
5427 private void updateShouldShowDialogsLocked(Configuration config) {
5428 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5429 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5430 && config.navigation == Configuration.NAVIGATION_NONAV);
5431 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5432 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5433 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5434 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5435 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5436 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5437 HIDE_ERROR_DIALOGS, 0) != 0;
5438 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5439 }
5440
5441 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5442 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5443 FONT_SCALE, 1.0f, userId);
5444
5445 synchronized (this) {
5446 if (getGlobalConfiguration().fontScale == scaleFactor) {
5447 return;
5448 }
5449
5450 final Configuration configuration
5451 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5452 configuration.fontScale = scaleFactor;
5453 updatePersistentConfiguration(configuration, userId);
5454 }
5455 }
5456
5457 // Actually is sleeping or shutting down or whatever else in the future
5458 // is an inactive state.
5459 boolean isSleepingOrShuttingDownLocked() {
5460 return isSleepingLocked() || mShuttingDown;
5461 }
5462
5463 boolean isSleepingLocked() {
5464 return mSleeping;
5465 }
5466
Riddle Hsu16567132018-08-16 21:37:47 +08005467 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005469 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005470 if (task.isActivityTypeStandard()) {
5471 if (mCurAppTimeTracker != r.appTimeTracker) {
5472 // We are switching app tracking. Complete the current one.
5473 if (mCurAppTimeTracker != null) {
5474 mCurAppTimeTracker.stop();
5475 mH.obtainMessage(
5476 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005477 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 mCurAppTimeTracker = null;
5479 }
5480 if (r.appTimeTracker != null) {
5481 mCurAppTimeTracker = r.appTimeTracker;
5482 startTimeTrackingFocusedActivityLocked();
5483 }
5484 } else {
5485 startTimeTrackingFocusedActivityLocked();
5486 }
5487 } else {
5488 r.appTimeTracker = null;
5489 }
5490 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5491 // TODO: Probably not, because we don't want to resume voice on switching
5492 // back to this activity
5493 if (task.voiceInteractor != null) {
5494 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5495 } else {
5496 finishRunningVoiceLocked();
5497
5498 if (mLastResumedActivity != null) {
5499 final IVoiceInteractionSession session;
5500
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005501 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005502 if (lastResumedActivityTask != null
5503 && lastResumedActivityTask.voiceSession != null) {
5504 session = lastResumedActivityTask.voiceSession;
5505 } else {
5506 session = mLastResumedActivity.voiceSession;
5507 }
5508
5509 if (session != null) {
5510 // We had been in a voice interaction session, but now focused has
5511 // move to something different. Just finish the session, we can't
5512 // return to it and retain the proper state and synchronization with
5513 // the voice interaction service.
5514 finishVoiceTask(session);
5515 }
5516 }
5517 }
5518
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005519 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5520 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521 }
5522 updateResumedAppTrace(r);
5523 mLastResumedActivity = r;
5524
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005525 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005526
5527 applyUpdateLockStateLocked(r);
5528 applyUpdateVrModeLocked(r);
5529
5530 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005531 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005532 r == null ? "NULL" : r.shortComponentName,
5533 reason);
5534 }
5535
5536 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5537 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005538 final ActivityTaskManagerInternal.SleepToken token =
5539 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005540 updateSleepIfNeededLocked();
5541 return token;
5542 }
5543 }
5544
5545 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005546 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547 final boolean wasSleeping = mSleeping;
5548 boolean updateOomAdj = false;
5549
5550 if (!shouldSleep) {
5551 // If wasSleeping is true, we need to wake up activity manager state from when
5552 // we started sleeping. In either case, we need to apply the sleep tokens, which
5553 // will wake up stacks or put them to sleep as appropriate.
5554 if (wasSleeping) {
5555 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005556 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5557 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 startTimeTrackingFocusedActivityLocked();
5559 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005560 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005561 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5562 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005563 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 if (wasSleeping) {
5565 updateOomAdj = true;
5566 }
5567 } else if (!mSleeping && shouldSleep) {
5568 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005569 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5570 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 if (mCurAppTimeTracker != null) {
5572 mCurAppTimeTracker.stop();
5573 }
5574 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005575 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 mStackSupervisor.goingToSleepLocked();
5577 updateResumedAppTrace(null /* resumed */);
5578 updateOomAdj = true;
5579 }
5580 if (updateOomAdj) {
5581 mH.post(mAmInternal::updateOomAdj);
5582 }
5583 }
5584
5585 void updateOomAdj() {
5586 mH.post(mAmInternal::updateOomAdj);
5587 }
5588
Wale Ogunwale53783742018-09-16 10:21:51 -07005589 void updateCpuStats() {
5590 mH.post(mAmInternal::updateCpuStats);
5591 }
5592
Hui Yu03d12402018-12-06 18:00:37 -08005593 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5594 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005595 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5596 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005597 mH.sendMessage(m);
5598 }
5599
Hui Yu03d12402018-12-06 18:00:37 -08005600 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005601 ComponentName taskRoot = null;
5602 final TaskRecord task = activity.getTaskRecord();
5603 if (task != null) {
5604 final ActivityRecord rootActivity = task.getRootActivity();
5605 if (rootActivity != null) {
5606 taskRoot = rootActivity.mActivityComponent;
5607 }
5608 }
5609
Hui Yu03d12402018-12-06 18:00:37 -08005610 final Message m = PooledLambda.obtainMessage(
5611 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005612 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005613 mH.sendMessage(m);
5614 }
5615
Wale Ogunwale53783742018-09-16 10:21:51 -07005616 void setBooting(boolean booting) {
5617 mAmInternal.setBooting(booting);
5618 }
5619
5620 boolean isBooting() {
5621 return mAmInternal.isBooting();
5622 }
5623
5624 void setBooted(boolean booted) {
5625 mAmInternal.setBooted(booted);
5626 }
5627
5628 boolean isBooted() {
5629 return mAmInternal.isBooted();
5630 }
5631
5632 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5633 mH.post(() -> {
5634 if (finishBooting) {
5635 mAmInternal.finishBooting();
5636 }
5637 if (enableScreen) {
5638 mInternal.enableScreenAfterBoot(isBooted());
5639 }
5640 });
5641 }
5642
5643 void setHeavyWeightProcess(ActivityRecord root) {
5644 mHeavyWeightProcess = root.app;
5645 final Message m = PooledLambda.obtainMessage(
5646 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005647 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005648 mH.sendMessage(m);
5649 }
5650
5651 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5652 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5653 return;
5654 }
5655
5656 mHeavyWeightProcess = null;
5657 final Message m = PooledLambda.obtainMessage(
5658 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5659 proc.mUserId);
5660 mH.sendMessage(m);
5661 }
5662
5663 private void cancelHeavyWeightProcessNotification(int userId) {
5664 final INotificationManager inm = NotificationManager.getService();
5665 if (inm == null) {
5666 return;
5667 }
5668 try {
5669 inm.cancelNotificationWithTag("android", null,
5670 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5671 } catch (RuntimeException e) {
5672 Slog.w(TAG, "Error canceling notification for service", e);
5673 } catch (RemoteException e) {
5674 }
5675
5676 }
5677
5678 private void postHeavyWeightProcessNotification(
5679 WindowProcessController proc, Intent intent, int userId) {
5680 if (proc == null) {
5681 return;
5682 }
5683
5684 final INotificationManager inm = NotificationManager.getService();
5685 if (inm == null) {
5686 return;
5687 }
5688
5689 try {
5690 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5691 String text = mContext.getString(R.string.heavy_weight_notification,
5692 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5693 Notification notification =
5694 new Notification.Builder(context,
5695 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5696 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5697 .setWhen(0)
5698 .setOngoing(true)
5699 .setTicker(text)
5700 .setColor(mContext.getColor(
5701 com.android.internal.R.color.system_notification_accent_color))
5702 .setContentTitle(text)
5703 .setContentText(
5704 mContext.getText(R.string.heavy_weight_notification_detail))
5705 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5706 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5707 new UserHandle(userId)))
5708 .build();
5709 try {
5710 inm.enqueueNotificationWithTag("android", "android", null,
5711 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5712 } catch (RuntimeException e) {
5713 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5714 } catch (RemoteException e) {
5715 }
5716 } catch (PackageManager.NameNotFoundException e) {
5717 Slog.w(TAG, "Unable to create context for heavy notification", e);
5718 }
5719
5720 }
5721
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005722 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5723 IBinder token, String resultWho, int requestCode, Intent[] intents,
5724 String[] resolvedTypes, int flags, Bundle bOptions) {
5725
5726 ActivityRecord activity = null;
5727 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5728 activity = ActivityRecord.isInStackLocked(token);
5729 if (activity == null) {
5730 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5731 return null;
5732 }
5733 if (activity.finishing) {
5734 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5735 return null;
5736 }
5737 }
5738
5739 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5740 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5741 bOptions);
5742 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5743 if (noCreate) {
5744 return rec;
5745 }
5746 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5747 if (activity.pendingResults == null) {
5748 activity.pendingResults = new HashSet<>();
5749 }
5750 activity.pendingResults.add(rec.ref);
5751 }
5752 return rec;
5753 }
5754
Andrii Kulian52d255c2018-07-13 11:32:19 -07005755 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005756 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005757 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005758 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5759 mCurAppTimeTracker.start(resumedActivity.packageName);
5760 }
5761 }
5762
5763 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5764 if (mTracedResumedActivity != null) {
5765 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5766 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5767 }
5768 if (resumed != null) {
5769 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5770 constructResumedTraceName(resumed.packageName), 0);
5771 }
5772 mTracedResumedActivity = resumed;
5773 }
5774
5775 private String constructResumedTraceName(String packageName) {
5776 return "focused app: " + packageName;
5777 }
5778
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005779 /** Applies latest configuration and/or visibility updates if needed. */
5780 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5781 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005782 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005783 // mainStack is null during startup.
5784 if (mainStack != null) {
5785 if (changes != 0 && starting == null) {
5786 // If the configuration changed, and the caller is not already
5787 // in the process of starting an activity, then find the top
5788 // activity to check if its configuration needs to change.
5789 starting = mainStack.topRunningActivityLocked();
5790 }
5791
5792 if (starting != null) {
5793 kept = starting.ensureActivityConfiguration(changes,
5794 false /* preserveWindow */);
5795 // And we need to make sure at this point that all other activities
5796 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005797 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005798 !PRESERVE_WINDOWS);
5799 }
5800 }
5801
5802 return kept;
5803 }
5804
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005805 void scheduleAppGcsLocked() {
5806 mH.post(() -> mAmInternal.scheduleAppGcs());
5807 }
5808
Wale Ogunwale53783742018-09-16 10:21:51 -07005809 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5810 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5811 }
5812
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005813 /**
5814 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5815 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5816 * on demand.
5817 */
5818 IPackageManager getPackageManager() {
5819 return AppGlobals.getPackageManager();
5820 }
5821
5822 PackageManagerInternal getPackageManagerInternalLocked() {
5823 if (mPmInternal == null) {
5824 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5825 }
5826 return mPmInternal;
5827 }
5828
Hai Zhangf4da9be2019-05-01 13:46:06 +08005829 PermissionPolicyInternal getPermissionPolicyInternal() {
5830 if (mPermissionPolicyInternal == null) {
5831 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5832 }
5833 return mPermissionPolicyInternal;
5834 }
5835
Wale Ogunwale008163e2018-07-23 23:11:08 -07005836 AppWarnings getAppWarningsLocked() {
5837 return mAppWarnings;
5838 }
5839
Wale Ogunwale214f3482018-10-04 11:00:47 -07005840 Intent getHomeIntent() {
5841 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5842 intent.setComponent(mTopComponent);
5843 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5844 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5845 intent.addCategory(Intent.CATEGORY_HOME);
5846 }
5847 return intent;
5848 }
5849
Chilun2ef71f72018-11-16 17:57:15 +08005850 /**
5851 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5852 * activities.
5853 *
5854 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5855 * component defined in config_secondaryHomeComponent.
5856 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5857 */
5858 Intent getSecondaryHomeIntent(String preferredPackage) {
5859 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005860 if (preferredPackage == null) {
5861 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005862 final String secondaryHomeComponent = mContext.getResources().getString(
5863 com.android.internal.R.string.config_secondaryHomeComponent);
5864 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5865 } else {
5866 intent.setPackage(preferredPackage);
5867 }
5868 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5869 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5870 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5871 }
5872 return intent;
5873 }
5874
Wale Ogunwale214f3482018-10-04 11:00:47 -07005875 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5876 if (info == null) return null;
5877 ApplicationInfo newInfo = new ApplicationInfo(info);
5878 newInfo.initForUser(userId);
5879 return newInfo;
5880 }
5881
Wale Ogunwale9c103022018-10-18 07:44:54 -07005882 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005883 if (uid == SYSTEM_UID) {
5884 // The system gets to run in any process. If there are multiple processes with the same
5885 // uid, just pick the first (this should never happen).
5886 final SparseArray<WindowProcessController> procs =
5887 mProcessNames.getMap().get(processName);
5888 if (procs == null) return null;
5889 final int procCount = procs.size();
5890 for (int i = 0; i < procCount; i++) {
5891 final int procUid = procs.keyAt(i);
5892 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5893 // Don't use an app process or different user process for system component.
5894 continue;
5895 }
5896 return procs.valueAt(i);
5897 }
5898 }
5899
5900 return mProcessNames.get(processName, uid);
5901 }
5902
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005903 WindowProcessController getProcessController(IApplicationThread thread) {
5904 if (thread == null) {
5905 return null;
5906 }
5907
5908 final IBinder threadBinder = thread.asBinder();
5909 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5910 for (int i = pmap.size()-1; i >= 0; i--) {
5911 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5912 for (int j = procs.size() - 1; j >= 0; j--) {
5913 final WindowProcessController proc = procs.valueAt(j);
5914 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5915 return proc;
5916 }
5917 }
5918 }
5919
5920 return null;
5921 }
5922
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005923 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005924 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005925 if (proc == null) return null;
5926 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5927 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005928 }
5929 return null;
5930 }
5931
Riddle Hsua0536432019-02-16 00:38:59 +08005932 int getUidState(int uid) {
5933 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005934 }
5935
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005936 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005937 // A uid is considered to be foreground if it has a visible non-toast window.
5938 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005939 }
5940
Ricky Wai96f5c352019-04-10 18:40:17 +01005941 boolean isDeviceOwner(int uid) {
5942 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005943 }
5944
Ricky Wai96f5c352019-04-10 18:40:17 +01005945 void setDeviceOwnerUid(int uid) {
5946 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005947 }
5948
Wale Ogunwale9de19442018-10-18 19:05:03 -07005949 /**
5950 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5951 * the whitelist
5952 */
5953 String getPendingTempWhitelistTagForUidLocked(int uid) {
5954 return mPendingTempWhitelist.get(uid);
5955 }
5956
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005957 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5958 if (true || Build.IS_USER) {
5959 return;
5960 }
5961
5962 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5963 StrictMode.allowThreadDiskWrites();
5964 try {
5965 File tracesDir = new File("/data/anr");
5966 File tracesFile = null;
5967 try {
5968 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5969
5970 StringBuilder sb = new StringBuilder();
5971 Time tobj = new Time();
5972 tobj.set(System.currentTimeMillis());
5973 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5974 sb.append(": ");
5975 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5976 sb.append(" since ");
5977 sb.append(msg);
5978 FileOutputStream fos = new FileOutputStream(tracesFile);
5979 fos.write(sb.toString().getBytes());
5980 if (app == null) {
5981 fos.write("\n*** No application process!".getBytes());
5982 }
5983 fos.close();
5984 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5985 } catch (IOException e) {
5986 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5987 return;
5988 }
5989
5990 if (app != null && app.getPid() > 0) {
5991 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5992 firstPids.add(app.getPid());
5993 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5994 }
5995
5996 File lastTracesFile = null;
5997 File curTracesFile = null;
5998 for (int i=9; i>=0; i--) {
5999 String name = String.format(Locale.US, "slow%02d.txt", i);
6000 curTracesFile = new File(tracesDir, name);
6001 if (curTracesFile.exists()) {
6002 if (lastTracesFile != null) {
6003 curTracesFile.renameTo(lastTracesFile);
6004 } else {
6005 curTracesFile.delete();
6006 }
6007 }
6008 lastTracesFile = curTracesFile;
6009 }
6010 tracesFile.renameTo(curTracesFile);
6011 } finally {
6012 StrictMode.setThreadPolicy(oldPolicy);
6013 }
6014 }
6015
Michal Karpinskida34cd42019-04-02 19:46:52 +01006016 boolean isAssociatedCompanionApp(int userId, int uid) {
6017 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6018 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006019 return false;
6020 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006021 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006022 }
6023
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006024 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006025 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006026
6027
Wale Ogunwale98875612018-10-12 07:53:02 -07006028 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6029 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006030
Riddle Hsud93a6c42018-11-29 21:50:06 +08006031 H(Looper looper) {
6032 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006033 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006034
6035 @Override
6036 public void handleMessage(Message msg) {
6037 switch (msg.what) {
6038 case REPORT_TIME_TRACKER_MSG: {
6039 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6040 tracker.deliverResult(mContext);
6041 } break;
6042 }
6043 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006044 }
6045
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006046 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006047 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006048
6049 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006050 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006051 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006052
6053 @Override
6054 public void handleMessage(Message msg) {
6055 switch (msg.what) {
6056 case DISMISS_DIALOG_UI_MSG: {
6057 final Dialog d = (Dialog) msg.obj;
6058 d.dismiss();
6059 break;
6060 }
6061 }
6062 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006063 }
6064
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006065 final class LocalService extends ActivityTaskManagerInternal {
6066 @Override
6067 public SleepToken acquireSleepToken(String tag, int displayId) {
6068 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006069 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006070 }
6071
6072 @Override
6073 public ComponentName getHomeActivityForUser(int userId) {
6074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006075 final ActivityRecord homeActivity =
6076 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006077 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006078 }
6079 }
6080
6081 @Override
6082 public void onLocalVoiceInteractionStarted(IBinder activity,
6083 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6084 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006085 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006086 }
6087 }
6088
6089 @Override
6090 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6091 synchronized (mGlobalLock) {
6092 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6093 reasons, timestamp);
6094 }
6095 }
6096
6097 @Override
6098 public void notifyAppTransitionFinished() {
6099 synchronized (mGlobalLock) {
6100 mStackSupervisor.notifyAppTransitionDone();
6101 }
6102 }
6103
6104 @Override
6105 public void notifyAppTransitionCancelled() {
6106 synchronized (mGlobalLock) {
6107 mStackSupervisor.notifyAppTransitionDone();
6108 }
6109 }
6110
6111 @Override
6112 public List<IBinder> getTopVisibleActivities() {
6113 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006114 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006115 }
6116 }
6117
6118 @Override
6119 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6120 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006121 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006122 }
6123 }
6124
6125 @Override
6126 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6127 Bundle bOptions) {
6128 Preconditions.checkNotNull(intents, "intents");
6129 final String[] resolvedTypes = new String[intents.length];
6130
6131 // UID of the package on user userId.
6132 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6133 // packageUid may not be initialized.
6134 int packageUid = 0;
6135 final long ident = Binder.clearCallingIdentity();
6136
6137 try {
6138 for (int i = 0; i < intents.length; i++) {
6139 resolvedTypes[i] =
6140 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6141 }
6142
6143 packageUid = AppGlobals.getPackageManager().getPackageUid(
6144 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6145 } catch (RemoteException e) {
6146 // Shouldn't happen.
6147 } finally {
6148 Binder.restoreCallingIdentity(ident);
6149 }
6150
Riddle Hsu591bf612019-02-14 17:55:31 +08006151 return getActivityStartController().startActivitiesInPackage(
6152 packageUid, packageName,
6153 intents, resolvedTypes, null /* resultTo */,
6154 SafeActivityOptions.fromBundle(bOptions), userId,
6155 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6156 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 }
6158
6159 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006160 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6161 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6162 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6163 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006164 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006165 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006166 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6167 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6168 userId, validateIncomingUser, originatingPendingIntent,
6169 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006170 }
6171 }
6172
6173 @Override
6174 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6175 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6176 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6177 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006178 PendingIntentRecord originatingPendingIntent,
6179 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006180 synchronized (mGlobalLock) {
6181 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6182 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6183 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006184 validateIncomingUser, originatingPendingIntent,
6185 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006186 }
6187 }
6188
6189 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6191 Intent intent, Bundle options, int userId) {
6192 return ActivityTaskManagerService.this.startActivityAsUser(
6193 caller, callerPacakge, intent,
6194 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6195 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6196 false /*validateIncomingUser*/);
6197 }
6198
6199 @Override
lumark588a3e82018-07-20 18:53:54 +08006200 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 synchronized (mGlobalLock) {
6202
6203 // We might change the visibilities here, so prepare an empty app transition which
6204 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006205 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006206 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006207 if (activityDisplay == null) {
6208 return;
6209 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006210 final DisplayContent dc = activityDisplay.mDisplayContent;
6211 final boolean wasTransitionSet =
6212 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006213 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006214 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006215 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006216 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006217
6218 // If there was a transition set already we don't want to interfere with it as we
6219 // might be starting it too early.
6220 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006221 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 }
6223 }
6224 if (callback != null) {
6225 callback.run();
6226 }
6227 }
6228
6229 @Override
6230 public void notifyKeyguardTrustedChanged() {
6231 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006232 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006233 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006234 }
6235 }
6236 }
6237
6238 /**
6239 * Called after virtual display Id is updated by
6240 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6241 * {@param vrVr2dDisplayId}.
6242 */
6243 @Override
6244 public void setVr2dDisplayId(int vr2dDisplayId) {
6245 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6246 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006247 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 }
6249 }
6250
6251 @Override
6252 public void setFocusedActivity(IBinder token) {
6253 synchronized (mGlobalLock) {
6254 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6255 if (r == null) {
6256 throw new IllegalArgumentException(
6257 "setFocusedActivity: No activity record matching token=" + token);
6258 }
Louis Chang19443452018-10-09 12:10:21 +08006259 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006260 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006261 }
6262 }
6263 }
6264
6265 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006267 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006268 }
6269
6270 @Override
6271 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006272 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006273 }
6274
6275 @Override
6276 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006277 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006278 }
6279
6280 @Override
6281 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6282 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6283 }
6284
6285 @Override
6286 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006287 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006288 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006289
6290 @Override
6291 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6292 synchronized (mGlobalLock) {
6293 mActiveVoiceInteractionServiceComponent = component;
6294 }
6295 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006296
6297 @Override
6298 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6299 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6300 return;
6301 }
6302 synchronized (mGlobalLock) {
6303 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6304 if (types == null) {
6305 if (uid < 0) {
6306 return;
6307 }
6308 types = new ArrayMap<>();
6309 mAllowAppSwitchUids.put(userId, types);
6310 }
6311 if (uid < 0) {
6312 types.remove(type);
6313 } else {
6314 types.put(type, uid);
6315 }
6316 }
6317 }
6318
6319 @Override
6320 public void onUserStopped(int userId) {
6321 synchronized (mGlobalLock) {
6322 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6323 mAllowAppSwitchUids.remove(userId);
6324 }
6325 }
6326
6327 @Override
6328 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6329 synchronized (mGlobalLock) {
6330 return ActivityTaskManagerService.this.isGetTasksAllowed(
6331 caller, callingPid, callingUid);
6332 }
6333 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006334
Riddle Hsua0536432019-02-16 00:38:59 +08006335 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006336 @Override
6337 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006338 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006339 mProcessNames.put(proc.mName, proc.mUid, proc);
6340 }
6341 }
6342
Riddle Hsua0536432019-02-16 00:38:59 +08006343 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006344 @Override
6345 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006346 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006347 mProcessNames.remove(name, uid);
6348 }
6349 }
6350
Riddle Hsua0536432019-02-16 00:38:59 +08006351 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006352 @Override
6353 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006354 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006355 if (proc == mHomeProcess) {
6356 mHomeProcess = null;
6357 }
6358 if (proc == mPreviousProcess) {
6359 mPreviousProcess = null;
6360 }
6361 }
6362 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006363
Riddle Hsua0536432019-02-16 00:38:59 +08006364 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006365 @Override
6366 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006368 return mTopProcessState;
6369 }
6370 }
6371
Riddle Hsua0536432019-02-16 00:38:59 +08006372 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006373 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006374 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006375 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006376 return proc == mHeavyWeightProcess;
6377 }
6378 }
6379
Riddle Hsua0536432019-02-16 00:38:59 +08006380 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006381 @Override
6382 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006383 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006384 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6385 }
6386 }
6387
6388 @Override
6389 public void finishHeavyWeightApp() {
6390 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006391 if (mHeavyWeightProcess != null) {
6392 mHeavyWeightProcess.finishActivities();
6393 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006394 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6395 mHeavyWeightProcess);
6396 }
6397 }
6398
Riddle Hsua0536432019-02-16 00:38:59 +08006399 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006400 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006401 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006402 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006403 return isSleepingLocked();
6404 }
6405 }
6406
6407 @Override
6408 public boolean isShuttingDown() {
6409 synchronized (mGlobalLock) {
6410 return mShuttingDown;
6411 }
6412 }
6413
6414 @Override
6415 public boolean shuttingDown(boolean booted, int timeout) {
6416 synchronized (mGlobalLock) {
6417 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006418 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006419 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006420 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006421 return mStackSupervisor.shutdownLocked(timeout);
6422 }
6423 }
6424
6425 @Override
6426 public void enableScreenAfterBoot(boolean booted) {
6427 synchronized (mGlobalLock) {
6428 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6429 SystemClock.uptimeMillis());
6430 mWindowManager.enableScreenAfterBoot();
6431 updateEventDispatchingLocked(booted);
6432 }
6433 }
6434
6435 @Override
6436 public boolean showStrictModeViolationDialog() {
6437 synchronized (mGlobalLock) {
6438 return mShowDialogs && !mSleeping && !mShuttingDown;
6439 }
6440 }
6441
6442 @Override
6443 public void showSystemReadyErrorDialogsIfNeeded() {
6444 synchronized (mGlobalLock) {
6445 try {
6446 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6447 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6448 + " data partition or your device will be unstable.");
6449 mUiHandler.post(() -> {
6450 if (mShowDialogs) {
6451 AlertDialog d = new BaseErrorDialog(mUiContext);
6452 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6453 d.setCancelable(false);
6454 d.setTitle(mUiContext.getText(R.string.android_system_label));
6455 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6456 d.setButton(DialogInterface.BUTTON_POSITIVE,
6457 mUiContext.getText(R.string.ok),
6458 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6459 d.show();
6460 }
6461 });
6462 }
6463 } catch (RemoteException e) {
6464 }
6465
6466 if (!Build.isBuildConsistent()) {
6467 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6468 mUiHandler.post(() -> {
6469 if (mShowDialogs) {
6470 AlertDialog d = new BaseErrorDialog(mUiContext);
6471 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6472 d.setCancelable(false);
6473 d.setTitle(mUiContext.getText(R.string.android_system_label));
6474 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6475 d.setButton(DialogInterface.BUTTON_POSITIVE,
6476 mUiContext.getText(R.string.ok),
6477 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6478 d.show();
6479 }
6480 });
6481 }
6482 }
6483 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006484
6485 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006486 public void onProcessMapped(int pid, WindowProcessController proc) {
6487 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006488 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006489 }
6490 }
6491
6492 @Override
6493 public void onProcessUnMapped(int pid) {
6494 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006495 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006496 }
6497 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006498
6499 @Override
6500 public void onPackageDataCleared(String name) {
6501 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006502 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006503 mAppWarnings.onPackageDataCleared(name);
6504 }
6505 }
6506
6507 @Override
6508 public void onPackageUninstalled(String name) {
6509 synchronized (mGlobalLock) {
6510 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006511 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006512 }
6513 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006514
6515 @Override
6516 public void onPackageAdded(String name, boolean replacing) {
6517 synchronized (mGlobalLock) {
6518 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6519 }
6520 }
6521
6522 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006523 public void onPackageReplaced(ApplicationInfo aInfo) {
6524 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006525 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006526 }
6527 }
6528
6529 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006530 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6531 synchronized (mGlobalLock) {
6532 return compatibilityInfoForPackageLocked(ai);
6533 }
6534 }
6535
Yunfan Chen75157d72018-07-27 14:47:21 +09006536 /**
6537 * Set the corresponding display information for the process global configuration. To be
6538 * called when we need to show IME on a different display.
6539 *
6540 * @param pid The process id associated with the IME window.
6541 * @param displayId The ID of the display showing the IME.
6542 */
6543 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006544 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006545 // Don't update process-level configuration for Multi-Client IME process since other
6546 // IMEs on other displays will also receive this configuration change due to IME
6547 // services use the same application config/context.
6548 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006549
Yunfan Chen75157d72018-07-27 14:47:21 +09006550 if (pid == MY_PID || pid < 0) {
6551 if (DEBUG_CONFIGURATION) {
6552 Slog.w(TAG,
6553 "Trying to update display configuration for system/invalid process.");
6554 }
6555 return;
6556 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006557 synchronized (mGlobalLock) {
6558 final ActivityDisplay activityDisplay =
6559 mRootActivityContainer.getActivityDisplay(displayId);
6560 if (activityDisplay == null) {
6561 // Call might come when display is not yet added or has been removed.
6562 if (DEBUG_CONFIGURATION) {
6563 Slog.w(TAG, "Trying to update display configuration for non-existing "
6564 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006565 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006566 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006567 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006568 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006569 if (process == null) {
6570 if (DEBUG_CONFIGURATION) {
6571 Slog.w(TAG, "Trying to update display configuration for invalid "
6572 + "process, pid=" + pid);
6573 }
6574 return;
6575 }
6576 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6577 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006578 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006579
6580 @Override
6581 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6582 int requestCode, int resultCode, Intent data) {
6583 synchronized (mGlobalLock) {
6584 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006585 if (r != null && r.getActivityStack() != null) {
6586 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6587 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006588 }
6589 }
6590 }
6591
6592 @Override
6593 public void clearPendingResultForActivity(IBinder activityToken,
6594 WeakReference<PendingIntentRecord> pir) {
6595 synchronized (mGlobalLock) {
6596 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6597 if (r != null && r.pendingResults != null) {
6598 r.pendingResults.remove(pir);
6599 }
6600 }
6601 }
6602
6603 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006604 public ActivityTokens getTopActivityForTask(int taskId) {
6605 synchronized (mGlobalLock) {
6606 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6607 if (taskRecord == null) {
6608 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6609 + " Requested task not found");
6610 return null;
6611 }
6612 final ActivityRecord activity = taskRecord.getTopActivity();
6613 if (activity == null) {
6614 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6615 + " Requested activity not found");
6616 return null;
6617 }
6618 if (!activity.attachedToProcess()) {
6619 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6620 + activity);
6621 return null;
6622 }
6623 return new ActivityTokens(activity.appToken, activity.assistToken,
6624 activity.app.getThread());
6625 }
6626 }
6627
6628 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006629 public IIntentSender getIntentSender(int type, String packageName,
6630 int callingUid, int userId, IBinder token, String resultWho,
6631 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6632 Bundle bOptions) {
6633 synchronized (mGlobalLock) {
6634 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6635 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6636 }
6637 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006638
6639 @Override
6640 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6641 synchronized (mGlobalLock) {
6642 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6643 if (r == null) {
6644 return null;
6645 }
6646 if (r.mServiceConnectionsHolder == null) {
6647 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6648 ActivityTaskManagerService.this, r);
6649 }
6650
6651 return r.mServiceConnectionsHolder;
6652 }
6653 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006654
6655 @Override
6656 public Intent getHomeIntent() {
6657 synchronized (mGlobalLock) {
6658 return ActivityTaskManagerService.this.getHomeIntent();
6659 }
6660 }
6661
6662 @Override
6663 public boolean startHomeActivity(int userId, String reason) {
6664 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006665 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006666 }
6667 }
6668
6669 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006670 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006671 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006672 synchronized (mGlobalLock) {
6673 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006674 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006675 }
Chilun8b1f1be2019-03-13 17:14:36 +08006676 }
6677
6678 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006679 public boolean startHomeOnAllDisplays(int userId, String reason) {
6680 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006681 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006682 }
6683 }
6684
Riddle Hsua0536432019-02-16 00:38:59 +08006685 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006686 @Override
6687 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006688 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006689 if (mFactoryTest == FACTORY_TEST_OFF) {
6690 return false;
6691 }
6692 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6693 && wpc.mName.equals(mTopComponent.getPackageName())) {
6694 return true;
6695 }
6696 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6697 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6698 }
6699 }
6700
6701 @Override
6702 public void updateTopComponentForFactoryTest() {
6703 synchronized (mGlobalLock) {
6704 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6705 return;
6706 }
6707 final ResolveInfo ri = mContext.getPackageManager()
6708 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6709 final CharSequence errorMsg;
6710 if (ri != null) {
6711 final ActivityInfo ai = ri.activityInfo;
6712 final ApplicationInfo app = ai.applicationInfo;
6713 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6714 mTopAction = Intent.ACTION_FACTORY_TEST;
6715 mTopData = null;
6716 mTopComponent = new ComponentName(app.packageName, ai.name);
6717 errorMsg = null;
6718 } else {
6719 errorMsg = mContext.getResources().getText(
6720 com.android.internal.R.string.factorytest_not_system);
6721 }
6722 } else {
6723 errorMsg = mContext.getResources().getText(
6724 com.android.internal.R.string.factorytest_no_action);
6725 }
6726 if (errorMsg == null) {
6727 return;
6728 }
6729
6730 mTopAction = null;
6731 mTopData = null;
6732 mTopComponent = null;
6733 mUiHandler.post(() -> {
6734 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6735 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006736 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006737 });
6738 }
6739 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740
Riddle Hsua0536432019-02-16 00:38:59 +08006741 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742 @Override
6743 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6744 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006745 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006747 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748
6749 wpc.clearRecentTasks();
6750 wpc.clearActivities();
6751
6752 if (wpc.isInstrumenting()) {
6753 finishInstrumentationCallback.run();
6754 }
6755
Jorim Jaggid0752812018-10-16 16:07:20 +02006756 if (!restarting && hasVisibleActivities) {
6757 mWindowManager.deferSurfaceLayout();
6758 try {
6759 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6760 // If there was nothing to resume, and we are not already restarting
6761 // this process, but there is a visible activity that is hosted by the
6762 // process...then make sure all visible activities are running, taking
6763 // care of restarting this process.
6764 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6765 !PRESERVE_WINDOWS);
6766 }
6767 } finally {
6768 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006769 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 }
6771 }
6772 }
6773
6774 @Override
6775 public void closeSystemDialogs(String reason) {
6776 enforceNotIsolatedCaller("closeSystemDialogs");
6777
6778 final int pid = Binder.getCallingPid();
6779 final int uid = Binder.getCallingUid();
6780 final long origId = Binder.clearCallingIdentity();
6781 try {
6782 synchronized (mGlobalLock) {
6783 // Only allow this from foreground processes, so that background
6784 // applications can't abuse it to prevent system UI from being shown.
6785 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006786 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 if (!proc.isPerceptible()) {
6788 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6789 + " from background process " + proc);
6790 return;
6791 }
6792 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006793 mWindowManager.closeSystemDialogs(reason);
6794
Wale Ogunwaled32da472018-11-16 07:19:28 -08006795 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006797 // Call into AM outside the synchronized block.
6798 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 } finally {
6800 Binder.restoreCallingIdentity(origId);
6801 }
6802 }
6803
6804 @Override
6805 public void cleanupDisabledPackageComponents(
6806 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6807 synchronized (mGlobalLock) {
6808 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006809 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006811 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 mStackSupervisor.scheduleIdleLocked();
6813 }
6814
6815 // Clean-up disabled tasks
6816 getRecentTasks().cleanupDisabledPackageTasksLocked(
6817 packageName, disabledClasses, userId);
6818 }
6819 }
6820
6821 @Override
6822 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6823 int userId) {
6824 synchronized (mGlobalLock) {
6825
6826 boolean didSomething =
6827 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006828 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 null, doit, evenPersistent, userId);
6830 return didSomething;
6831 }
6832 }
6833
6834 @Override
6835 public void resumeTopActivities(boolean scheduleIdle) {
6836 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006837 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 if (scheduleIdle) {
6839 mStackSupervisor.scheduleIdleLocked();
6840 }
6841 }
6842 }
6843
Riddle Hsua0536432019-02-16 00:38:59 +08006844 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 @Override
6846 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006847 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6849 }
6850 }
6851
Riddle Hsua0536432019-02-16 00:38:59 +08006852 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 @Override
6854 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006855 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006856 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 }
6858 }
6859
6860 @Override
6861 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6862 try {
6863 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6864 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6865 }
6866 } catch (RemoteException ex) {
6867 throw new SecurityException("Fail to check is caller a privileged app", ex);
6868 }
6869
6870 synchronized (mGlobalLock) {
6871 final long ident = Binder.clearCallingIdentity();
6872 try {
6873 if (mAmInternal.shouldConfirmCredentials(userId)) {
6874 if (mKeyguardController.isKeyguardLocked()) {
6875 // Showing launcher to avoid user entering credential twice.
6876 startHomeActivity(currentUserId, "notifyLockedProfile");
6877 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006878 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 }
6880 } finally {
6881 Binder.restoreCallingIdentity(ident);
6882 }
6883 }
6884 }
6885
6886 @Override
6887 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6888 mAmInternal.enforceCallingPermission(
6889 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6890
6891 synchronized (mGlobalLock) {
6892 final long ident = Binder.clearCallingIdentity();
6893 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006894 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6895 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006896 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006897 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6898 UserHandle.CURRENT);
6899 } finally {
6900 Binder.restoreCallingIdentity(ident);
6901 }
6902 }
6903 }
6904
6905 @Override
6906 public void writeActivitiesToProto(ProtoOutputStream proto) {
6907 synchronized (mGlobalLock) {
6908 // The output proto of "activity --proto activities"
6909 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006910 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006911 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6912 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006913 }
6914 }
6915
6916 @Override
6917 public void saveANRState(String reason) {
6918 synchronized (mGlobalLock) {
6919 final StringWriter sw = new StringWriter();
6920 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6921 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6922 if (reason != null) {
6923 pw.println(" Reason: " + reason);
6924 }
6925 pw.println();
6926 getActivityStartController().dump(pw, " ", null);
6927 pw.println();
6928 pw.println("-------------------------------------------------------------------------------");
6929 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6930 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6931 "" /* header */);
6932 pw.println();
6933 pw.close();
6934
6935 mLastANRState = sw.toString();
6936 }
6937 }
6938
6939 @Override
6940 public void clearSavedANRState() {
6941 synchronized (mGlobalLock) {
6942 mLastANRState = null;
6943 }
6944 }
6945
6946 @Override
6947 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6948 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6949 synchronized (mGlobalLock) {
6950 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6951 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6952 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6953 dumpLastANRLocked(pw);
6954 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6955 dumpLastANRTracesLocked(pw);
6956 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6957 dumpActivityStarterLocked(pw, dumpPackage);
6958 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6959 dumpActivityContainersLocked(pw);
6960 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6961 if (getRecentTasks() != null) {
6962 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6963 }
6964 }
6965 }
6966 }
6967
6968 @Override
6969 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6970 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6971 int wakefulness) {
6972 synchronized (mGlobalLock) {
6973 if (mHomeProcess != null && (dumpPackage == null
6974 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6975 if (needSep) {
6976 pw.println();
6977 needSep = false;
6978 }
6979 pw.println(" mHomeProcess: " + mHomeProcess);
6980 }
6981 if (mPreviousProcess != null && (dumpPackage == null
6982 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6983 if (needSep) {
6984 pw.println();
6985 needSep = false;
6986 }
6987 pw.println(" mPreviousProcess: " + mPreviousProcess);
6988 }
6989 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6990 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6991 StringBuilder sb = new StringBuilder(128);
6992 sb.append(" mPreviousProcessVisibleTime: ");
6993 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6994 pw.println(sb);
6995 }
6996 if (mHeavyWeightProcess != null && (dumpPackage == null
6997 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6998 if (needSep) {
6999 pw.println();
7000 needSep = false;
7001 }
7002 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7003 }
7004 if (dumpPackage == null) {
7005 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007006 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007007 }
7008 if (dumpAll) {
7009 if (dumpPackage == null) {
7010 pw.println(" mConfigWillChange: "
7011 + getTopDisplayFocusedStack().mConfigWillChange);
7012 }
7013 if (mCompatModePackages.getPackages().size() > 0) {
7014 boolean printed = false;
7015 for (Map.Entry<String, Integer> entry
7016 : mCompatModePackages.getPackages().entrySet()) {
7017 String pkg = entry.getKey();
7018 int mode = entry.getValue();
7019 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7020 continue;
7021 }
7022 if (!printed) {
7023 pw.println(" mScreenCompatPackages:");
7024 printed = true;
7025 }
7026 pw.println(" " + pkg + ": " + mode);
7027 }
7028 }
7029 }
7030
7031 if (dumpPackage == null) {
7032 pw.println(" mWakefulness="
7033 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007034 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007035 if (mRunningVoice != null) {
7036 pw.println(" mRunningVoice=" + mRunningVoice);
7037 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7038 }
7039 pw.println(" mSleeping=" + mSleeping);
7040 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7041 pw.println(" mVrController=" + mVrController);
7042 }
7043 if (mCurAppTimeTracker != null) {
7044 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7045 }
7046 if (mAllowAppSwitchUids.size() > 0) {
7047 boolean printed = false;
7048 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7049 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7050 for (int j = 0; j < types.size(); j++) {
7051 if (dumpPackage == null ||
7052 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7053 if (needSep) {
7054 pw.println();
7055 needSep = false;
7056 }
7057 if (!printed) {
7058 pw.println(" mAllowAppSwitchUids:");
7059 printed = true;
7060 }
7061 pw.print(" User ");
7062 pw.print(mAllowAppSwitchUids.keyAt(i));
7063 pw.print(": Type ");
7064 pw.print(types.keyAt(j));
7065 pw.print(" = ");
7066 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7067 pw.println();
7068 }
7069 }
7070 }
7071 }
7072 if (dumpPackage == null) {
7073 if (mController != null) {
7074 pw.println(" mController=" + mController
7075 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7076 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007077 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7078 pw.println(" mLaunchingActivityWakeLock="
7079 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007080 }
7081
7082 return needSep;
7083 }
7084 }
7085
7086 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007087 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7088 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 synchronized (mGlobalLock) {
7090 if (dumpPackage == null) {
7091 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7092 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007093 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7094 if (mRunningVoice != null) {
7095 final long vrToken = proto.start(
7096 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7097 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7098 mRunningVoice.toString());
7099 mVoiceWakeLock.writeToProto(
7100 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7101 proto.end(vrToken);
7102 }
7103 mVrController.writeToProto(proto,
7104 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007105 if (mController != null) {
7106 final long token = proto.start(CONTROLLER);
7107 proto.write(CONTROLLER, mController.toString());
7108 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7109 proto.end(token);
7110 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007111 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7112 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7113 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007114 }
7115
7116 if (mHomeProcess != null && (dumpPackage == null
7117 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007118 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120
7121 if (mPreviousProcess != null && (dumpPackage == null
7122 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007123 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7125 }
7126
7127 if (mHeavyWeightProcess != null && (dumpPackage == null
7128 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007129 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007130 }
7131
7132 for (Map.Entry<String, Integer> entry
7133 : mCompatModePackages.getPackages().entrySet()) {
7134 String pkg = entry.getKey();
7135 int mode = entry.getValue();
7136 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7137 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7138 proto.write(PACKAGE, pkg);
7139 proto.write(MODE, mode);
7140 proto.end(compatToken);
7141 }
7142 }
7143
7144 if (mCurAppTimeTracker != null) {
7145 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7146 }
7147
7148 }
7149 }
7150
7151 @Override
7152 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7153 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7154 boolean dumpFocusedStackOnly) {
7155 synchronized (mGlobalLock) {
7156 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7157 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7158 }
7159 }
7160
7161 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007162 public void dumpForOom(PrintWriter pw) {
7163 synchronized (mGlobalLock) {
7164 pw.println(" mHomeProcess: " + mHomeProcess);
7165 pw.println(" mPreviousProcess: " + mPreviousProcess);
7166 if (mHeavyWeightProcess != null) {
7167 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7168 }
7169 }
7170 }
7171
7172 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007173 public boolean canGcNow() {
7174 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007175 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007176 }
7177 }
7178
Riddle Hsua0536432019-02-16 00:38:59 +08007179 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 @Override
7181 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007182 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007183 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007184 return top != null ? top.app : null;
7185 }
7186 }
7187
Riddle Hsua0536432019-02-16 00:38:59 +08007188 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 @Override
7190 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007191 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007192 if (mRootActivityContainer != null) {
7193 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 }
7195 }
7196 }
7197
7198 @Override
7199 public void scheduleDestroyAllActivities(String reason) {
7200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007201 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 }
7203 }
7204
7205 @Override
7206 public void removeUser(int userId) {
7207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007208 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007209 }
7210 }
7211
7212 @Override
7213 public boolean switchUser(int userId, UserState userState) {
7214 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007215 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217 }
7218
7219 @Override
7220 public void onHandleAppCrash(WindowProcessController wpc) {
7221 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007222 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 }
7224 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007225
7226 @Override
7227 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7228 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007229 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007230 }
7231 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007232
Riddle Hsua0536432019-02-16 00:38:59 +08007233 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007234 @Override
7235 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007236 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007237 }
7238
Riddle Hsua0536432019-02-16 00:38:59 +08007239 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007240 @Override
7241 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007242 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007243 }
7244
Riddle Hsua0536432019-02-16 00:38:59 +08007245 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007246 @Override
7247 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007248 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007249 }
7250
Riddle Hsua0536432019-02-16 00:38:59 +08007251 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007252 @Override
7253 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007254 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007255 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007256
7257 @Override
7258 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007259 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007260 mPendingTempWhitelist.put(uid, tag);
7261 }
7262 }
7263
7264 @Override
7265 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007266 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007267 mPendingTempWhitelist.remove(uid);
7268 }
7269 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007270
7271 @Override
7272 public boolean handleAppCrashInActivityController(String processName, int pid,
7273 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7274 Runnable killCrashingAppCallback) {
7275 synchronized (mGlobalLock) {
7276 if (mController == null) {
7277 return false;
7278 }
7279
7280 try {
7281 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7282 stackTrace)) {
7283 killCrashingAppCallback.run();
7284 return true;
7285 }
7286 } catch (RemoteException e) {
7287 mController = null;
7288 Watchdog.getInstance().setActivityController(null);
7289 }
7290 return false;
7291 }
7292 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007293
7294 @Override
7295 public void removeRecentTasksByPackageName(String packageName, int userId) {
7296 synchronized (mGlobalLock) {
7297 mRecentTasks.removeTasksByPackageName(packageName, userId);
7298 }
7299 }
7300
7301 @Override
7302 public void cleanupRecentTasksForUser(int userId) {
7303 synchronized (mGlobalLock) {
7304 mRecentTasks.cleanupLocked(userId);
7305 }
7306 }
7307
7308 @Override
7309 public void loadRecentTasksForUser(int userId) {
7310 synchronized (mGlobalLock) {
7311 mRecentTasks.loadUserRecentsLocked(userId);
7312 }
7313 }
7314
7315 @Override
7316 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7317 synchronized (mGlobalLock) {
7318 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7319 }
7320 }
7321
7322 @Override
7323 public void flushRecentTasks() {
7324 mRecentTasks.flush();
7325 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007326
7327 @Override
7328 public WindowProcessController getHomeProcess() {
7329 synchronized (mGlobalLock) {
7330 return mHomeProcess;
7331 }
7332 }
7333
7334 @Override
7335 public WindowProcessController getPreviousProcess() {
7336 synchronized (mGlobalLock) {
7337 return mPreviousProcess;
7338 }
7339 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007340
7341 @Override
7342 public void clearLockedTasks(String reason) {
7343 synchronized (mGlobalLock) {
7344 getLockTaskController().clearLockedTasks(reason);
7345 }
7346 }
7347
7348 @Override
7349 public void updateUserConfiguration() {
7350 synchronized (mGlobalLock) {
7351 final Configuration configuration = new Configuration(getGlobalConfiguration());
7352 final int currentUserId = mAmInternal.getCurrentUserId();
7353 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7354 configuration, currentUserId, Settings.System.canWrite(mContext));
7355 updateConfigurationLocked(configuration, null /* starting */,
7356 false /* initLocale */, false /* persistent */, currentUserId,
7357 false /* deferResume */);
7358 }
7359 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007360
7361 @Override
7362 public boolean canShowErrorDialogs() {
7363 synchronized (mGlobalLock) {
7364 return mShowDialogs && !mSleeping && !mShuttingDown
7365 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7366 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7367 mAmInternal.getCurrentUserId())
7368 && !(UserManager.isDeviceInDemoMode(mContext)
7369 && mAmInternal.getCurrentUser().isDemo());
7370 }
7371 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007372
7373 @Override
7374 public void setProfileApp(String profileApp) {
7375 synchronized (mGlobalLock) {
7376 mProfileApp = profileApp;
7377 }
7378 }
7379
7380 @Override
7381 public void setProfileProc(WindowProcessController wpc) {
7382 synchronized (mGlobalLock) {
7383 mProfileProc = wpc;
7384 }
7385 }
7386
7387 @Override
7388 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7389 synchronized (mGlobalLock) {
7390 mProfilerInfo = profilerInfo;
7391 }
7392 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007393
7394 @Override
7395 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7396 synchronized (mGlobalLock) {
7397 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7398 }
7399 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007400
7401 @Override
7402 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7403 synchronized (mGlobalLock) {
7404 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7405 }
7406 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007407
7408 @Override
7409 public boolean isUidForeground(int uid) {
7410 synchronized (mGlobalLock) {
7411 return ActivityTaskManagerService.this.isUidForeground(uid);
7412 }
7413 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007414
7415 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007416 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007417 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007418 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007419 }
7420 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007421
7422 @Override
7423 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007424 // Translate package names into UIDs
7425 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007426 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007427 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7428 if (uid >= 0) {
7429 result.add(uid);
7430 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007431 }
7432 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007433 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007434 }
7435 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007436 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007437}