blob: 682b1f8adb60665e3838fefacf0e70f081952b06 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100137import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400144import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.Notification;
147import android.app.NotificationManager;
148import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.PictureInPictureParams;
150import android.app.ProfilerInfo;
151import android.app.RemoteAction;
152import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700153import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.admin.DevicePolicyCache;
155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100196import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900212import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800229import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100250import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314
Wale Ogunwale98875612018-10-12 07:53:02 -0700315 /** Used to indicate that an app transition should be animated. */
316 static final boolean ANIMATE = true;
317
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700318 /** Hardware-reported OpenGLES version. */
319 final int GL_ES_VERSION;
320
Wale Ogunwale31913b52018-10-13 08:29:31 -0700321 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
322 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
323 public static final String DUMP_LASTANR_CMD = "lastanr" ;
324 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
325 public static final String DUMP_STARTER_CMD = "starter" ;
326 public static final String DUMP_CONTAINERS_CMD = "containers" ;
327 public static final String DUMP_RECENTS_CMD = "recents" ;
328 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
329
Wale Ogunwale64258362018-10-16 15:13:37 -0700330 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
331 public static final int RELAUNCH_REASON_NONE = 0;
332 /** This activity is being relaunched due to windowing mode change. */
333 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
334 /** This activity is being relaunched due to a free-resize operation. */
335 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
336
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700337 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700338
Wale Ogunwalef6733932018-06-27 05:14:34 -0700339 /**
340 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
341 * change at runtime. Use mContext for non-UI purposes.
342 */
343 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700345 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700346 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700348 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700349 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800350 @VisibleForTesting
351 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 PowerManagerInternal mPowerManagerInternal;
353 private UsageStatsManagerInternal mUsageStatsInternal;
354
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700355 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 IntentFirewall mIntentFirewall;
357
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700358 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800359 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800360 /**
361 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
362 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
363 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
364 *
365 * @see WindowManagerThreadPriorityBooster
366 */
367 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700368 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800369 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700370 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700371 private UserManagerService mUserManager;
372 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700373 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800374 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700375 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700376 /** All processes currently running that might have a window organized by name. */
377 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100378 /** All processes we currently have running mapped by pid and uid */
379 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** This is the process holding what we currently consider to be the "home" activity. */
381 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700382 /** The currently running heavy-weight process, if any. */
383 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700384 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /**
386 * This is the process holding the activity the user last visited that is in a different process
387 * from the one they are currently in.
388 */
389 WindowProcessController mPreviousProcess;
390 /** The time at which the previous process was last visible. */
391 long mPreviousProcessVisibleTime;
392
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700393 /** List of intents that were used to start the most recent tasks. */
394 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700395 /** State of external calls telling us if the device is awake or asleep. */
396 private boolean mKeyguardShown = false;
397
398 // Wrapper around VoiceInteractionServiceManager
399 private AssistUtils mAssistUtils;
400
401 // VoiceInteraction session ID that changes for each new request except when
402 // being called for multi-window assist in a single session.
403 private int mViSessionId = 1000;
404
405 // How long to wait in getAssistContextExtras for the activity and foreground services
406 // to respond with the result.
407 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
408
409 // How long top wait when going through the modern assist (which doesn't need to block
410 // on getting this result before starting to launch its UI).
411 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
412
413 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
414 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
415
Alison Cichowlas3e340502018-08-07 17:15:01 -0400416 // Permission tokens are used to temporarily granted a trusted app the ability to call
417 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
418 // showing any appropriate error messages to the user.
419 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
420 10 * MINUTE_IN_MILLIS;
421
422 // How long before the service actually expires a token. This is slightly longer than
423 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
424 // expiration exception.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
426 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
427
428 // How long the service will remember expired tokens, for the purpose of providing error
429 // messaging when a client uses an expired token.
430 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
431 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
432
Marvin Ramin830d4e32019-03-12 13:16:58 +0100433 // How long to whitelist the Services for when requested.
434 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
435
Alison Cichowlas3e340502018-08-07 17:15:01 -0400436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
462 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
507 IActivityController mController = null;
508 boolean mControllerIsAMonkey = false;
509
Wale Ogunwale214f3482018-10-04 11:00:47 -0700510 final int mFactoryTest;
511
512 /** Used to control how we initialize the service. */
513 ComponentName mTopComponent;
514 String mTopAction = Intent.ACTION_MAIN;
515 String mTopData;
516
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800517 /** Profiling app information. */
518 String mProfileApp = null;
519 WindowProcessController mProfileProc = null;
520 ProfilerInfo mProfilerInfo = null;
521
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700523 * Dump of the activity state at the time of the last ANR. Cleared after
524 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
525 */
526 String mLastANRState;
527
528 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700529 * Used to retain an update lock when the foreground activity is in
530 * immersive mode.
531 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700532 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533
534 /**
535 * Packages that are being allowed to perform unrestricted app switches. Mapping is
536 * User -> Type -> uid.
537 */
538 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
539
540 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private int mThumbnailWidth;
542 private int mThumbnailHeight;
543 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Flag that indicates if multi-window is enabled.
547 *
548 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
549 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
550 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
551 * At least one of the forms of multi-window must be enabled in order for this flag to be
552 * initialized to 'true'.
553 *
554 * @see #mSupportsSplitScreenMultiWindow
555 * @see #mSupportsFreeformWindowManagement
556 * @see #mSupportsPictureInPicture
557 * @see #mSupportsMultiDisplay
558 */
559 boolean mSupportsMultiWindow;
560 boolean mSupportsSplitScreenMultiWindow;
561 boolean mSupportsFreeformWindowManagement;
562 boolean mSupportsPictureInPicture;
563 boolean mSupportsMultiDisplay;
564 boolean mForceResizableActivities;
565
566 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
567
568 // VR Vr2d Display Id.
569 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700570
Wale Ogunwalef6733932018-06-27 05:14:34 -0700571 /**
572 * Set while we are wanting to sleep, to prevent any
573 * activities from being started/resumed.
574 *
575 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
576 *
577 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
578 * while in the sleep state until there is a pending transition out of sleep, in which case
579 * mSleeping is set to false, and remains false while awake.
580 *
581 * Whether mSleeping can quickly toggled between true/false without the device actually
582 * display changing states is undefined.
583 */
584 private boolean mSleeping = false;
585
586 /**
587 * The process state used for processes that are running the top activities.
588 * This changes between TOP and TOP_SLEEPING to following mSleeping.
589 */
590 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
591
592 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
593 // automatically. Important for devices without direct input devices.
594 private boolean mShowDialogs = true;
595
596 /** Set if we are shutting down the system, similar to sleeping. */
597 boolean mShuttingDown = false;
598
599 /**
600 * We want to hold a wake lock while running a voice interaction session, since
601 * this may happen with the screen off and we need to keep the CPU running to
602 * be able to continue to interact with the user.
603 */
604 PowerManager.WakeLock mVoiceWakeLock;
605
606 /**
607 * Set while we are running a voice interaction. This overrides sleeping while it is active.
608 */
609 IVoiceInteractionSession mRunningVoice;
610
611 /**
612 * The last resumed activity. This is identical to the current resumed activity most
613 * of the time but could be different when we're pausing one activity before we resume
614 * another activity.
615 */
616 ActivityRecord mLastResumedActivity;
617
618 /**
619 * The activity that is currently being traced as the active resumed activity.
620 *
621 * @see #updateResumedAppTrace
622 */
623 private @Nullable ActivityRecord mTracedResumedActivity;
624
625 /** If non-null, we are tracking the time the user spends in the currently focused app. */
626 AppTimeTracker mCurAppTimeTracker;
627
Wale Ogunwale008163e2018-07-23 23:11:08 -0700628 private AppWarnings mAppWarnings;
629
Wale Ogunwale53783742018-09-16 10:21:51 -0700630 /**
631 * Packages that the user has asked to have run in screen size
632 * compatibility mode instead of filling the screen.
633 */
634 CompatModePackages mCompatModePackages;
635
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 private FontScaleSettingObserver mFontScaleSettingObserver;
637
Ricky Wai96f5c352019-04-10 18:40:17 +0100638 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000639
Wale Ogunwalef6733932018-06-27 05:14:34 -0700640 private final class FontScaleSettingObserver extends ContentObserver {
641 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
642 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
643
644 public FontScaleSettingObserver() {
645 super(mH);
646 final ContentResolver resolver = mContext.getContentResolver();
647 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
648 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
649 UserHandle.USER_ALL);
650 }
651
652 @Override
653 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
654 if (mFontScaleUri.equals(uri)) {
655 updateFontScaleIfNeeded(userId);
656 } else if (mHideErrorDialogsUri.equals(uri)) {
657 synchronized (mGlobalLock) {
658 updateShouldShowDialogsLocked(getGlobalConfiguration());
659 }
660 }
661 }
662 }
663
Riddle Hsua0536432019-02-16 00:38:59 +0800664 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
665 @Target(ElementType.METHOD)
666 @Retention(RetentionPolicy.SOURCE)
667 @interface HotPath {
668 int NONE = 0;
669 int OOM_ADJUSTMENT = 1;
670 int LRU_UPDATE = 2;
671 int PROCESS_CHANGE = 3;
672 int caller() default NONE;
673 }
674
Charles Chen8d98dd22018-12-26 17:36:54 +0800675 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
676 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700677 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700678 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700679 mSystemThread = ActivityThread.currentActivityThread();
680 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700681 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800682 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700683 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 }
685
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700686 public void onSystemReady() {
687 synchronized (mGlobalLock) {
688 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
689 PackageManager.FEATURE_CANT_SAVE_STATE);
690 mAssistUtils = new AssistUtils(mContext);
691 mVrController.onSystemReady();
692 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700693 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700694 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700695 }
696
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700697 public void onInitPowerManagement() {
698 synchronized (mGlobalLock) {
699 mStackSupervisor.initPowerManagement();
700 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
701 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
702 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
703 mVoiceWakeLock.setReferenceCounted(false);
704 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700708 mFontScaleSettingObserver = new FontScaleSettingObserver();
709 }
710
Wale Ogunwale59507092018-10-29 09:00:30 -0700711 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700712 final boolean freeformWindowManagement =
713 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
714 || Settings.Global.getInt(
715 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
716
717 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
718 final boolean supportsPictureInPicture = supportsMultiWindow &&
719 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
720 final boolean supportsSplitScreenMultiWindow =
721 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
722 final boolean supportsMultiDisplay = mContext.getPackageManager()
723 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700724 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
725 final boolean forceResizable = Settings.Global.getInt(
726 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700727 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728
729 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900730 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700731
732 final Configuration configuration = new Configuration();
733 Settings.System.getConfiguration(resolver, configuration);
734 if (forceRtl) {
735 // This will take care of setting the correct layout direction flags
736 configuration.setLayoutDirection(configuration.locale);
737 }
738
739 synchronized (mGlobalLock) {
740 mForceResizableActivities = forceResizable;
741 final boolean multiWindowFormEnabled = freeformWindowManagement
742 || supportsSplitScreenMultiWindow
743 || supportsPictureInPicture
744 || supportsMultiDisplay;
745 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
746 mSupportsMultiWindow = true;
747 mSupportsFreeformWindowManagement = freeformWindowManagement;
748 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
749 mSupportsPictureInPicture = supportsPictureInPicture;
750 mSupportsMultiDisplay = supportsMultiDisplay;
751 } else {
752 mSupportsMultiWindow = false;
753 mSupportsFreeformWindowManagement = false;
754 mSupportsSplitScreenMultiWindow = false;
755 mSupportsPictureInPicture = false;
756 mSupportsMultiDisplay = false;
757 }
758 mWindowManager.setForceResizableTasks(mForceResizableActivities);
759 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700760 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
761 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700762 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763 // This happens before any activities are started, so we can change global configuration
764 // in-place.
765 updateConfigurationLocked(configuration, null, true);
766 final Configuration globalConfig = getGlobalConfiguration();
767 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
768
769 // Load resources only after the current configuration has been set.
770 final Resources res = mContext.getResources();
771 mThumbnailWidth = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_width);
773 mThumbnailHeight = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_height);
775
776 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
777 mFullscreenThumbnailScale = (float) res
778 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
779 (float) globalConfig.screenWidthDp;
780 } else {
781 mFullscreenThumbnailScale = res.getFraction(
782 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
783 }
784 }
785 }
786
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800787 public WindowManagerGlobalLock getGlobalLock() {
788 return mGlobalLock;
789 }
790
Yunfan Chen585f2932019-01-29 16:04:45 +0900791 /** For test purpose only. */
792 @VisibleForTesting
793 public ActivityTaskManagerInternal getAtmInternal() {
794 return mInternal;
795 }
796
Riddle Hsud93a6c42018-11-29 21:50:06 +0800797 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
798 Looper looper) {
799 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700800 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700801 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700802 final File systemDir = SystemServiceManager.ensureSystemDir();
803 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
804 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
807 mTempConfig.setToDefaults();
808 mTempConfig.setLocales(LocaleList.getDefault());
809 mConfigurationSeq = mTempConfig.seq = 1;
810 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800811 mRootActivityContainer = new RootActivityContainer(this);
812 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700818 mRecentTasks = createRecentTasks();
819 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mKeyguardController = mStackSupervisor.getKeyguardController();
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void onActivityManagerInternalAdded() {
825 synchronized (mGlobalLock) {
826 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
827 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
828 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700829 }
830
Yunfan Chen75157d72018-07-27 14:47:21 +0900831 int increaseConfigurationSeqLocked() {
832 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
833 return mConfigurationSeq;
834 }
835
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 protected ActivityStackSupervisor createStackSupervisor() {
837 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
838 supervisor.initialize();
839 return supervisor;
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void setWindowManager(WindowManagerService wm) {
843 synchronized (mGlobalLock) {
844 mWindowManager = wm;
845 mLockTaskController.setWindowManager(wm);
846 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800847 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700849 }
850
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
852 synchronized (mGlobalLock) {
853 mUsageStatsInternal = usageStatsManager;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 }
856
Wale Ogunwalef6733932018-06-27 05:14:34 -0700857 UserManagerService getUserManager() {
858 if (mUserManager == null) {
859 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
860 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
861 }
862 return mUserManager;
863 }
864
865 AppOpsService getAppOpsService() {
866 if (mAppOpsService == null) {
867 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
868 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
869 }
870 return mAppOpsService;
871 }
872
873 boolean hasUserRestriction(String restriction, int userId) {
874 return getUserManager().hasUserRestriction(restriction, userId);
875 }
876
Michal Karpinski15486842019-04-25 17:33:42 +0100877 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
878 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
879 callingUid, callingPackage);
880 if (mode == AppOpsManager.MODE_DEFAULT) {
881 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
882 == PERMISSION_GRANTED;
883 }
884 return mode == AppOpsManager.MODE_ALLOWED;
885 }
886
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700887 protected RecentTasks createRecentTasks() {
888 return new RecentTasks(this, mStackSupervisor);
889 }
890
891 RecentTasks getRecentTasks() {
892 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700893 }
894
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700895 ClientLifecycleManager getLifecycleManager() {
896 return mLifecycleManager;
897 }
898
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700899 ActivityStartController getActivityStartController() {
900 return mActivityStartController;
901 }
902
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700903 TaskChangeNotificationController getTaskChangeNotificationController() {
904 return mTaskChangeNotificationController;
905 }
906
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700907 LockTaskController getLockTaskController() {
908 return mLockTaskController;
909 }
910
Yunfan Chen75157d72018-07-27 14:47:21 +0900911 /**
912 * Return the global configuration used by the process corresponding to the input pid. This is
913 * usually the global configuration with some overrides specific to that process.
914 */
915 Configuration getGlobalConfigurationForCallingPid() {
916 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800917 return getGlobalConfigurationForPid(pid);
918 }
919
920 /**
921 * Return the global configuration used by the process corresponding to the given pid.
922 */
923 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900924 if (pid == MY_PID || pid < 0) {
925 return getGlobalConfiguration();
926 }
927 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100928 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 return app != null ? app.getConfiguration() : getGlobalConfiguration();
930 }
931 }
932
933 /**
934 * Return the device configuration info used by the process corresponding to the input pid.
935 * The value is consistent with the global configuration for the process.
936 */
937 @Override
938 public ConfigurationInfo getDeviceConfigurationInfo() {
939 ConfigurationInfo config = new ConfigurationInfo();
940 synchronized (mGlobalLock) {
941 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
942 config.reqTouchScreen = globalConfig.touchscreen;
943 config.reqKeyboardType = globalConfig.keyboard;
944 config.reqNavigation = globalConfig.navigation;
945 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
946 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
947 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
948 }
949 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
950 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
951 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
952 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700953 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900954 }
955 return config;
956 }
957
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700958 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700959 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 }
961
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 public static final class Lifecycle extends SystemService {
963 private final ActivityTaskManagerService mService;
964
965 public Lifecycle(Context context) {
966 super(context);
967 mService = new ActivityTaskManagerService(context);
968 }
969
970 @Override
971 public void onStart() {
972 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700973 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700974 }
975
Garfield Tan891146c2018-10-09 12:14:00 -0700976 @Override
977 public void onUnlockUser(int userId) {
978 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800979 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700980 }
981 }
982
983 @Override
984 public void onCleanupUser(int userId) {
985 synchronized (mService.getGlobalLock()) {
986 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
987 }
988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public ActivityTaskManagerService getService() {
991 return mService;
992 }
993 }
994
995 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 public final int startActivity(IApplicationThread caller, String callingPackage,
997 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
998 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
999 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1000 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1001 UserHandle.getCallingUserId());
1002 }
1003
1004 @Override
1005 public final int startActivities(IApplicationThread caller, String callingPackage,
1006 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1007 int userId) {
1008 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001009 enforceNotIsolatedCaller(reason);
1010 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001011 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001012 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1013 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1014 reason, null /* originatingPendingIntent */,
1015 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017
1018 @Override
1019 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1020 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1021 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1022 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1023 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1024 true /*validateIncomingUser*/);
1025 }
1026
1027 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1030 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001031 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001033 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1035
1036 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001037 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 .setCaller(caller)
1039 .setCallingPackage(callingPackage)
1040 .setResolvedType(resolvedType)
1041 .setResultTo(resultTo)
1042 .setResultWho(resultWho)
1043 .setRequestCode(requestCode)
1044 .setStartFlags(startFlags)
1045 .setProfilerInfo(profilerInfo)
1046 .setActivityOptions(bOptions)
1047 .setMayWait(userId)
1048 .execute();
1049
1050 }
1051
1052 @Override
1053 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1054 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001055 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1056 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 // Refuse possible leaked file descriptors
1058 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1059 throw new IllegalArgumentException("File descriptors passed in Intent");
1060 }
1061
1062 if (!(target instanceof PendingIntentRecord)) {
1063 throw new IllegalArgumentException("Bad PendingIntent object");
1064 }
1065
1066 PendingIntentRecord pir = (PendingIntentRecord)target;
1067
1068 synchronized (mGlobalLock) {
1069 // If this is coming from the currently resumed activity, it is
1070 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001071 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 if (stack.mResumedActivity != null &&
1073 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001074 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 }
1076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001077 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 }
1080
1081 @Override
1082 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1083 Bundle bOptions) {
1084 // Refuse possible leaked file descriptors
1085 if (intent != null && intent.hasFileDescriptors()) {
1086 throw new IllegalArgumentException("File descriptors passed in Intent");
1087 }
1088 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1089
1090 synchronized (mGlobalLock) {
1091 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1092 if (r == null) {
1093 SafeActivityOptions.abort(options);
1094 return false;
1095 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001096 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 // The caller is not running... d'oh!
1098 SafeActivityOptions.abort(options);
1099 return false;
1100 }
1101 intent = new Intent(intent);
1102 // The caller is not allowed to change the data.
1103 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1104 // And we are resetting to find the next component...
1105 intent.setComponent(null);
1106
1107 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1108
1109 ActivityInfo aInfo = null;
1110 try {
1111 List<ResolveInfo> resolves =
1112 AppGlobals.getPackageManager().queryIntentActivities(
1113 intent, r.resolvedType,
1114 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1115 UserHandle.getCallingUserId()).getList();
1116
1117 // Look for the original activity in the list...
1118 final int N = resolves != null ? resolves.size() : 0;
1119 for (int i=0; i<N; i++) {
1120 ResolveInfo rInfo = resolves.get(i);
1121 if (rInfo.activityInfo.packageName.equals(r.packageName)
1122 && rInfo.activityInfo.name.equals(r.info.name)) {
1123 // We found the current one... the next matching is
1124 // after it.
1125 i++;
1126 if (i<N) {
1127 aInfo = resolves.get(i).activityInfo;
1128 }
1129 if (debug) {
1130 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1131 + "/" + r.info.name);
1132 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1133 ? "null" : aInfo.packageName + "/" + aInfo.name));
1134 }
1135 break;
1136 }
1137 }
1138 } catch (RemoteException e) {
1139 }
1140
1141 if (aInfo == null) {
1142 // Nobody who is next!
1143 SafeActivityOptions.abort(options);
1144 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1145 return false;
1146 }
1147
1148 intent.setComponent(new ComponentName(
1149 aInfo.applicationInfo.packageName, aInfo.name));
1150 intent.setFlags(intent.getFlags()&~(
1151 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1152 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1153 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1154 FLAG_ACTIVITY_NEW_TASK));
1155
1156 // Okay now we need to start the new activity, replacing the currently running activity.
1157 // This is a little tricky because we want to start the new one as if the current one is
1158 // finished, but not finish the current one first so that there is no flicker.
1159 // And thus...
1160 final boolean wasFinishing = r.finishing;
1161 r.finishing = true;
1162
1163 // Propagate reply information over to the new activity.
1164 final ActivityRecord resultTo = r.resultTo;
1165 final String resultWho = r.resultWho;
1166 final int requestCode = r.requestCode;
1167 r.resultTo = null;
1168 if (resultTo != null) {
1169 resultTo.removeResultsLocked(r, resultWho, requestCode);
1170 }
1171
1172 final long origId = Binder.clearCallingIdentity();
1173 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001174 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001176 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .setResolvedType(r.resolvedType)
1178 .setActivityInfo(aInfo)
1179 .setResultTo(resultTo != null ? resultTo.appToken : null)
1180 .setResultWho(resultWho)
1181 .setRequestCode(requestCode)
1182 .setCallingPid(-1)
1183 .setCallingUid(r.launchedFromUid)
1184 .setCallingPackage(r.launchedFromPackage)
1185 .setRealCallingPid(-1)
1186 .setRealCallingUid(r.launchedFromUid)
1187 .setActivityOptions(options)
1188 .execute();
1189 Binder.restoreCallingIdentity(origId);
1190
1191 r.finishing = wasFinishing;
1192 if (res != ActivityManager.START_SUCCESS) {
1193 return false;
1194 }
1195 return true;
1196 }
1197 }
1198
1199 @Override
1200 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1201 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1202 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1203 final WaitResult res = new WaitResult();
1204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001205 enforceNotIsolatedCaller("startActivityAndWait");
1206 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1207 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001209 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .setCaller(caller)
1211 .setCallingPackage(callingPackage)
1212 .setResolvedType(resolvedType)
1213 .setResultTo(resultTo)
1214 .setResultWho(resultWho)
1215 .setRequestCode(requestCode)
1216 .setStartFlags(startFlags)
1217 .setActivityOptions(bOptions)
1218 .setMayWait(userId)
1219 .setProfilerInfo(profilerInfo)
1220 .setWaitResult(res)
1221 .execute();
1222 }
1223 return res;
1224 }
1225
1226 @Override
1227 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1228 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1229 int startFlags, Configuration config, Bundle bOptions, int userId) {
1230 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001231 enforceNotIsolatedCaller("startActivityWithConfig");
1232 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1233 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001234 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001235 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 .setCaller(caller)
1237 .setCallingPackage(callingPackage)
1238 .setResolvedType(resolvedType)
1239 .setResultTo(resultTo)
1240 .setResultWho(resultWho)
1241 .setRequestCode(requestCode)
1242 .setStartFlags(startFlags)
1243 .setGlobalConfiguration(config)
1244 .setActivityOptions(bOptions)
1245 .setMayWait(userId)
1246 .execute();
1247 }
1248 }
1249
Alison Cichowlas3e340502018-08-07 17:15:01 -04001250
1251 @Override
1252 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1253 int callingUid = Binder.getCallingUid();
1254 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1255 throw new SecurityException("Only the system process can request a permission token, "
1256 + "received request from uid: " + callingUid);
1257 }
1258 IBinder permissionToken = new Binder();
1259 synchronized (mGlobalLock) {
1260 mStartActivitySources.put(permissionToken, delegatorToken);
1261 }
1262
1263 Message expireMsg = PooledLambda.obtainMessage(
1264 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1265 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1266
1267 Message forgetMsg = PooledLambda.obtainMessage(
1268 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1269 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1270
1271 return permissionToken;
1272 }
1273
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 @Override
1275 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1276 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1278 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001280 // permission grants) as any app that may launch one of your own activities. So we only
1281 // allow this in two cases:
1282 // 1) The caller is an activity that is part of the core framework, and then only when it
1283 // is running as the system.
1284 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1285 // can only be requested by a system activity, which may then delegate this call to
1286 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 final ActivityRecord sourceRecord;
1288 final int targetUid;
1289 final String targetPackage;
1290 final boolean isResolver;
1291 synchronized (mGlobalLock) {
1292 if (resultTo == null) {
1293 throw new SecurityException("Must be called from an activity");
1294 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 final IBinder sourceToken;
1296 if (permissionToken != null) {
1297 // To even attempt to use a permissionToken, an app must also have this signature
1298 // permission.
1299 mAmInternal.enforceCallingPermission(
1300 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1301 "startActivityAsCaller");
1302 // If called with a permissionToken, we want the sourceRecord from the delegator
1303 // activity that requested this token.
1304 sourceToken = mStartActivitySources.remove(permissionToken);
1305 if (sourceToken == null) {
1306 // Invalid permissionToken, check if it recently expired.
1307 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1308 throw new SecurityException("Called with expired permission token: "
1309 + permissionToken);
1310 } else {
1311 throw new SecurityException("Called with invalid permission token: "
1312 + permissionToken);
1313 }
1314 }
1315 } else {
1316 // This method was called directly by the source.
1317 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001318 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319
Wale Ogunwaled32da472018-11-16 07:19:28 -08001320 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001321 if (sourceRecord == null) {
1322 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 }
1324 if (sourceRecord.app == null) {
1325 throw new SecurityException("Called without a process attached to activity");
1326 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327
1328 // Whether called directly or from a delegate, the source activity must be from the
1329 // android package.
1330 if (!sourceRecord.info.packageName.equals("android")) {
1331 throw new SecurityException("Must be called from an activity that is "
1332 + "declared in the android package");
1333 }
1334
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001335 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 // This is still okay, as long as this activity is running under the
1337 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001338 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 + " must be system uid or original calling uid "
1342 + sourceRecord.launchedFromUid);
1343 }
1344 }
1345 if (ignoreTargetSecurity) {
1346 if (intent.getComponent() == null) {
1347 throw new SecurityException(
1348 "Component must be specified with ignoreTargetSecurity");
1349 }
1350 if (intent.getSelector() != null) {
1351 throw new SecurityException(
1352 "Selector not allowed with ignoreTargetSecurity");
1353 }
1354 }
1355 targetUid = sourceRecord.launchedFromUid;
1356 targetPackage = sourceRecord.launchedFromPackage;
1357 isResolver = sourceRecord.isResolverOrChildActivity();
1358 }
1359
1360 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001361 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 }
1363
1364 // TODO: Switch to user app stacks here.
1365 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001366 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367 .setCallingUid(targetUid)
1368 .setCallingPackage(targetPackage)
1369 .setResolvedType(resolvedType)
1370 .setResultTo(resultTo)
1371 .setResultWho(resultWho)
1372 .setRequestCode(requestCode)
1373 .setStartFlags(startFlags)
1374 .setActivityOptions(bOptions)
1375 .setMayWait(userId)
1376 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1377 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1378 .execute();
1379 } catch (SecurityException e) {
1380 // XXX need to figure out how to propagate to original app.
1381 // A SecurityException here is generally actually a fault of the original
1382 // calling activity (such as a fairly granting permissions), so propagate it
1383 // back to them.
1384 /*
1385 StringBuilder msg = new StringBuilder();
1386 msg.append("While launching");
1387 msg.append(intent.toString());
1388 msg.append(": ");
1389 msg.append(e.getMessage());
1390 */
1391 throw e;
1392 }
1393 }
1394
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001395 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1396 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1397 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1398 }
1399
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 @Override
1401 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1402 Intent intent, String resolvedType, IVoiceInteractionSession session,
1403 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1404 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001405 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 if (session == null || interactor == null) {
1407 throw new NullPointerException("null session or interactor");
1408 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001411 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 .setCallingUid(callingUid)
1413 .setCallingPackage(callingPackage)
1414 .setResolvedType(resolvedType)
1415 .setVoiceSession(session)
1416 .setVoiceInteractor(interactor)
1417 .setStartFlags(startFlags)
1418 .setProfilerInfo(profilerInfo)
1419 .setActivityOptions(bOptions)
1420 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001421 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 .execute();
1423 }
1424
1425 @Override
1426 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1427 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1429 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001431 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 .setCallingUid(callingUid)
1433 .setCallingPackage(callingPackage)
1434 .setResolvedType(resolvedType)
1435 .setActivityOptions(bOptions)
1436 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001437 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 .execute();
1439 }
1440
1441 @Override
1442 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1443 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001444 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 final int callingPid = Binder.getCallingPid();
1446 final long origId = Binder.clearCallingIdentity();
1447 try {
1448 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001449 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1450 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451
1452 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1454 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1456 recentsUid, assistDataReceiver);
1457 }
1458 } finally {
1459 Binder.restoreCallingIdentity(origId);
1460 }
1461 }
1462
1463 @Override
1464 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 "startActivityFromRecents()");
1467
1468 final int callingPid = Binder.getCallingPid();
1469 final int callingUid = Binder.getCallingUid();
1470 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1471 final long origId = Binder.clearCallingIdentity();
1472 try {
1473 synchronized (mGlobalLock) {
1474 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1475 safeOptions);
1476 }
1477 } finally {
1478 Binder.restoreCallingIdentity(origId);
1479 }
1480 }
1481
1482 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001483 * Public API to check if the client is allowed to start an activity on specified display.
1484 *
1485 * If the target display is private or virtual, some restrictions will apply.
1486 *
1487 * @param displayId Target display id.
1488 * @param intent Intent used to launch the activity.
1489 * @param resolvedType The MIME type of the intent.
1490 * @param userId The id of the user for whom the call is made.
1491 * @return {@code true} if a call to start an activity on the target display should succeed and
1492 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1493 */
1494 @Override
1495 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1496 String resolvedType, int userId) {
1497 final int callingUid = Binder.getCallingUid();
1498 final int callingPid = Binder.getCallingPid();
1499 final long origId = Binder.clearCallingIdentity();
1500
1501 try {
1502 // Collect information about the target of the Intent.
1503 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1504 0 /* startFlags */, null /* profilerInfo */, userId,
1505 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1506 UserHandle.USER_NULL));
1507 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1508
1509 synchronized (mGlobalLock) {
1510 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1511 aInfo);
1512 }
1513 } finally {
1514 Binder.restoreCallingIdentity(origId);
1515 }
1516 }
1517
1518 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 * This is the internal entry point for handling Activity.finish().
1520 *
1521 * @param token The Binder token referencing the Activity we want to finish.
1522 * @param resultCode Result code, if any, from this Activity.
1523 * @param resultData Result data (Intent), if any, from this Activity.
1524 * @param finishTask Whether to finish the task associated with this Activity.
1525 *
1526 * @return Returns true if the activity successfully finished, or false if it is still running.
1527 */
1528 @Override
1529 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1530 int finishTask) {
1531 // Refuse possible leaked file descriptors
1532 if (resultData != null && resultData.hasFileDescriptors()) {
1533 throw new IllegalArgumentException("File descriptors passed in Intent");
1534 }
1535
1536 synchronized (mGlobalLock) {
1537 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1538 if (r == null) {
1539 return true;
1540 }
1541 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001542 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001543 ActivityRecord rootR = tr.getRootActivity();
1544 if (rootR == null) {
1545 Slog.w(TAG, "Finishing task with all activities already finished");
1546 }
1547 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1548 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001549 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 return false;
1551 }
1552
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001553 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1554 // We should consolidate.
1555 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001557 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 if (next != null) {
1559 // ask watcher if this is allowed
1560 boolean resumeOK = true;
1561 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001562 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001564 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 Watchdog.getInstance().setActivityController(null);
1566 }
1567
1568 if (!resumeOK) {
1569 Slog.i(TAG, "Not finishing activity because controller resumed");
1570 return false;
1571 }
1572 }
1573 }
1574 final long origId = Binder.clearCallingIdentity();
1575 try {
1576 boolean res;
1577 final boolean finishWithRootActivity =
1578 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1579 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1580 || (finishWithRootActivity && r == rootR)) {
1581 // If requested, remove the task that is associated to this activity only if it
1582 // was the root activity in the task. The result code and data is ignored
1583 // because we don't support returning them across task boundaries. Also, to
1584 // keep backwards compatibility we remove the task from recents when finishing
1585 // task with root activity.
1586 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1587 finishWithRootActivity, "finish-activity");
1588 if (!res) {
1589 Slog.i(TAG, "Removing task failed to finish activity");
1590 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001591 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001592 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 } else {
1594 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1595 resultData, "app-request", true);
1596 if (!res) {
1597 Slog.i(TAG, "Failed to finish by app-request");
1598 }
1599 }
1600 return res;
1601 } finally {
1602 Binder.restoreCallingIdentity(origId);
1603 }
1604 }
1605 }
1606
1607 @Override
1608 public boolean finishActivityAffinity(IBinder token) {
1609 synchronized (mGlobalLock) {
1610 final long origId = Binder.clearCallingIdentity();
1611 try {
1612 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1613 if (r == null) {
1614 return false;
1615 }
1616
1617 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1618 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001619 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001620 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 return false;
1622 }
1623 return task.getStack().finishActivityAffinityLocked(r);
1624 } finally {
1625 Binder.restoreCallingIdentity(origId);
1626 }
1627 }
1628 }
1629
1630 @Override
1631 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1632 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001633 try {
1634 WindowProcessController proc = null;
1635 synchronized (mGlobalLock) {
1636 ActivityStack stack = ActivityRecord.getStackLocked(token);
1637 if (stack == null) {
1638 return;
1639 }
1640 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1641 false /* fromTimeout */, false /* processPausingActivities */, config);
1642 if (r != null) {
1643 proc = r.app;
1644 }
1645 if (stopProfiling && proc != null) {
1646 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 }
1648 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001649 } finally {
1650 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001652 }
1653
1654 @Override
1655 public final void activityResumed(IBinder token) {
1656 final long origId = Binder.clearCallingIdentity();
1657 synchronized (mGlobalLock) {
1658 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001659 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 }
1661 Binder.restoreCallingIdentity(origId);
1662 }
1663
1664 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001665 public final void activityTopResumedStateLost() {
1666 final long origId = Binder.clearCallingIdentity();
1667 synchronized (mGlobalLock) {
1668 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1669 }
1670 Binder.restoreCallingIdentity(origId);
1671 }
1672
1673 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 public final void activityPaused(IBinder token) {
1675 final long origId = Binder.clearCallingIdentity();
1676 synchronized (mGlobalLock) {
1677 ActivityStack stack = ActivityRecord.getStackLocked(token);
1678 if (stack != null) {
1679 stack.activityPausedLocked(token, false);
1680 }
1681 }
1682 Binder.restoreCallingIdentity(origId);
1683 }
1684
1685 @Override
1686 public final void activityStopped(IBinder token, Bundle icicle,
1687 PersistableBundle persistentState, CharSequence description) {
1688 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1689
1690 // Refuse possible leaked file descriptors
1691 if (icicle != null && icicle.hasFileDescriptors()) {
1692 throw new IllegalArgumentException("File descriptors passed in Bundle");
1693 }
1694
1695 final long origId = Binder.clearCallingIdentity();
1696
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001697 String restartingName = null;
1698 int restartingUid = 0;
1699 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001701 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001703 if (r.attachedToProcess()
1704 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1705 // The activity was requested to restart from
1706 // {@link #restartActivityProcessIfVisible}.
1707 restartingName = r.app.mName;
1708 restartingUid = r.app.mUid;
1709 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 r.activityStoppedLocked(icicle, persistentState, description);
1711 }
1712 }
1713
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001714 if (restartingName != null) {
1715 // In order to let the foreground activity can be restarted with its saved state from
1716 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1717 // until the activity reports stopped with the state. And the activity record will be
1718 // kept because the record state is restarting, then the activity will be restarted
1719 // immediately if it is still the top one.
1720 mStackSupervisor.removeRestartTimeouts(r);
1721 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1722 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001723 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724
1725 Binder.restoreCallingIdentity(origId);
1726 }
1727
1728 @Override
1729 public final void activityDestroyed(IBinder token) {
1730 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1731 synchronized (mGlobalLock) {
1732 ActivityStack stack = ActivityRecord.getStackLocked(token);
1733 if (stack != null) {
1734 stack.activityDestroyedLocked(token, "activityDestroyed");
1735 }
1736 }
1737 }
1738
1739 @Override
1740 public final void activityRelaunched(IBinder token) {
1741 final long origId = Binder.clearCallingIdentity();
1742 synchronized (mGlobalLock) {
1743 mStackSupervisor.activityRelaunchedLocked(token);
1744 }
1745 Binder.restoreCallingIdentity(origId);
1746 }
1747
1748 public final void activitySlept(IBinder token) {
1749 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1750
1751 final long origId = Binder.clearCallingIdentity();
1752
1753 synchronized (mGlobalLock) {
1754 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1755 if (r != null) {
1756 mStackSupervisor.activitySleptLocked(r);
1757 }
1758 }
1759
1760 Binder.restoreCallingIdentity(origId);
1761 }
1762
1763 @Override
1764 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1765 synchronized (mGlobalLock) {
1766 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1767 if (r == null) {
1768 return;
1769 }
1770 final long origId = Binder.clearCallingIdentity();
1771 try {
1772 r.setRequestedOrientation(requestedOrientation);
1773 } finally {
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776 }
1777 }
1778
1779 @Override
1780 public int getRequestedOrientation(IBinder token) {
1781 synchronized (mGlobalLock) {
1782 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1783 if (r == null) {
1784 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1785 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001786 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
1788 }
1789
1790 @Override
1791 public void setImmersive(IBinder token, boolean immersive) {
1792 synchronized (mGlobalLock) {
1793 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1794 if (r == null) {
1795 throw new IllegalArgumentException();
1796 }
1797 r.immersive = immersive;
1798
1799 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001800 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 }
1804 }
1805 }
1806
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 void applyUpdateLockStateLocked(ActivityRecord r) {
1808 // Modifications to the UpdateLock state are done on our handler, outside
1809 // the activity manager's locks. The new state is determined based on the
1810 // state *now* of the relevant activity record. The object is passed to
1811 // the handler solely for logging detail, not to be consulted/modified.
1812 final boolean nextState = r != null && r.immersive;
1813 mH.post(() -> {
1814 if (mUpdateLock.isHeld() != nextState) {
1815 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1816 "Applying new update lock state '" + nextState + "' for " + r);
1817 if (nextState) {
1818 mUpdateLock.acquire();
1819 } else {
1820 mUpdateLock.release();
1821 }
1822 }
1823 });
1824 }
1825
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 @Override
1827 public boolean isImmersive(IBinder token) {
1828 synchronized (mGlobalLock) {
1829 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1830 if (r == null) {
1831 throw new IllegalArgumentException();
1832 }
1833 return r.immersive;
1834 }
1835 }
1836
1837 @Override
1838 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001841 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 return (r != null) ? r.immersive : false;
1843 }
1844 }
1845
1846 @Override
1847 public void overridePendingTransition(IBinder token, String packageName,
1848 int enterAnim, int exitAnim) {
1849 synchronized (mGlobalLock) {
1850 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1851 if (self == null) {
1852 return;
1853 }
1854
1855 final long origId = Binder.clearCallingIdentity();
1856
1857 if (self.isState(
1858 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001859 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001860 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
1862
1863 Binder.restoreCallingIdentity(origId);
1864 }
1865 }
1866
1867 @Override
1868 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001871 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001872 if (r == null) {
1873 return ActivityManager.COMPAT_MODE_UNKNOWN;
1874 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001875 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 }
1877 }
1878
1879 @Override
1880 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001881 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001882 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001883 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001885 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 if (r == null) {
1887 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1888 return;
1889 }
1890 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001891 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 }
1893 }
1894
1895 @Override
1896 public int getLaunchedFromUid(IBinder activityToken) {
1897 ActivityRecord srec;
1898 synchronized (mGlobalLock) {
1899 srec = ActivityRecord.forTokenLocked(activityToken);
1900 }
1901 if (srec == null) {
1902 return -1;
1903 }
1904 return srec.launchedFromUid;
1905 }
1906
1907 @Override
1908 public String getLaunchedFromPackage(IBinder activityToken) {
1909 ActivityRecord srec;
1910 synchronized (mGlobalLock) {
1911 srec = ActivityRecord.forTokenLocked(activityToken);
1912 }
1913 if (srec == null) {
1914 return null;
1915 }
1916 return srec.launchedFromPackage;
1917 }
1918
1919 @Override
1920 public boolean convertFromTranslucent(IBinder token) {
1921 final long origId = Binder.clearCallingIdentity();
1922 try {
1923 synchronized (mGlobalLock) {
1924 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1925 if (r == null) {
1926 return false;
1927 }
1928 final boolean translucentChanged = r.changeWindowTranslucency(true);
1929 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001930 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001933 return translucentChanged;
1934 }
1935 } finally {
1936 Binder.restoreCallingIdentity(origId);
1937 }
1938 }
1939
1940 @Override
1941 public boolean convertToTranslucent(IBinder token, Bundle options) {
1942 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1943 final long origId = Binder.clearCallingIdentity();
1944 try {
1945 synchronized (mGlobalLock) {
1946 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1947 if (r == null) {
1948 return false;
1949 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001950 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 int index = task.mActivities.lastIndexOf(r);
1952 if (index > 0) {
1953 ActivityRecord under = task.mActivities.get(index - 1);
1954 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1955 }
1956 final boolean translucentChanged = r.changeWindowTranslucency(false);
1957 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001958 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001960 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 return translucentChanged;
1963 }
1964 } finally {
1965 Binder.restoreCallingIdentity(origId);
1966 }
1967 }
1968
1969 @Override
1970 public void notifyActivityDrawn(IBinder token) {
1971 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1972 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001973 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001975 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 }
1977 }
1978 }
1979
1980 @Override
1981 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1982 synchronized (mGlobalLock) {
1983 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1984 if (r == null) {
1985 return;
1986 }
1987 r.reportFullyDrawnLocked(restoredFromBundle);
1988 }
1989 }
1990
1991 @Override
1992 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1993 synchronized (mGlobalLock) {
1994 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1995 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1996 return stack.mDisplayId;
1997 }
1998 return DEFAULT_DISPLAY;
1999 }
2000 }
2001
2002 @Override
2003 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002004 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 long ident = Binder.clearCallingIdentity();
2006 try {
2007 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002008 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002010 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 }
2012 return null;
2013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018
2019 @Override
2020 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002021 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2023 final long callingId = Binder.clearCallingIdentity();
2024 try {
2025 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002026 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 if (stack == null) {
2028 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2029 return;
2030 }
2031 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002032 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002033 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 }
2035 }
2036 } finally {
2037 Binder.restoreCallingIdentity(callingId);
2038 }
2039 }
2040
2041 @Override
2042 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002043 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2045 final long callingId = Binder.clearCallingIdentity();
2046 try {
2047 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002048 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002049 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (task == null) {
2051 return;
2052 }
2053 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002054 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002055 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 }
2057 }
2058 } finally {
2059 Binder.restoreCallingIdentity(callingId);
2060 }
2061 }
2062
2063 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002064 public void restartActivityProcessIfVisible(IBinder activityToken) {
2065 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2066 final long callingId = Binder.clearCallingIdentity();
2067 try {
2068 synchronized (mGlobalLock) {
2069 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2070 if (r == null) {
2071 return;
2072 }
2073 r.restartProcessIfVisible();
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(callingId);
2077 }
2078 }
2079
2080 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002082 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 synchronized (mGlobalLock) {
2084 final long ident = Binder.clearCallingIdentity();
2085 try {
2086 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2087 "remove-task");
2088 } finally {
2089 Binder.restoreCallingIdentity(ident);
2090 }
2091 }
2092 }
2093
2094 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002095 public void removeAllVisibleRecentTasks() {
2096 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2097 synchronized (mGlobalLock) {
2098 final long ident = Binder.clearCallingIdentity();
2099 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002100 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
2104 }
2105 }
2106
2107 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2111 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002112 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 }
2114 }
2115 return false;
2116 }
2117
2118 @Override
2119 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2120 Intent resultData) {
2121
2122 synchronized (mGlobalLock) {
2123 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2124 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002125 return r.getActivityStack().navigateUpToLocked(
2126 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 }
2128 return false;
2129 }
2130 }
2131
2132 /**
2133 * Attempts to move a task backwards in z-order (the order of activities within the task is
2134 * unchanged).
2135 *
2136 * There are several possible results of this call:
2137 * - if the task is locked, then we will show the lock toast
2138 * - if there is a task behind the provided task, then that task is made visible and resumed as
2139 * this task is moved to the back
2140 * - otherwise, if there are no other tasks in the stack:
2141 * - if this task is in the pinned stack, then we remove the stack completely, which will
2142 * have the effect of moving the task to the top or bottom of the fullscreen stack
2143 * (depending on whether it is visible)
2144 * - otherwise, we simply return home and hide this task
2145 *
2146 * @param token A reference to the activity we wish to move
2147 * @param nonRoot If false then this only works if the activity is the root
2148 * of a task; if true it will work for any activity in a task.
2149 * @return Returns true if the move completed, false if not.
2150 */
2151 @Override
2152 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002153 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 synchronized (mGlobalLock) {
2155 final long origId = Binder.clearCallingIdentity();
2156 try {
2157 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002158 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 if (task != null) {
2160 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2161 }
2162 } finally {
2163 Binder.restoreCallingIdentity(origId);
2164 }
2165 }
2166 return false;
2167 }
2168
2169 @Override
2170 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002171 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 long ident = Binder.clearCallingIdentity();
2173 Rect rect = new Rect();
2174 try {
2175 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002176 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2178 if (task == null) {
2179 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2180 return rect;
2181 }
2182 if (task.getStack() != null) {
2183 // Return the bounds from window manager since it will be adjusted for various
2184 // things like the presense of a docked stack for tasks that aren't resizeable.
2185 task.getWindowContainerBounds(rect);
2186 } else {
2187 // Task isn't in window manager yet since it isn't associated with a stack.
2188 // Return the persist value from activity manager
2189 if (!task.matchParentBounds()) {
2190 rect.set(task.getBounds());
2191 } else if (task.mLastNonFullscreenBounds != null) {
2192 rect.set(task.mLastNonFullscreenBounds);
2193 }
2194 }
2195 }
2196 } finally {
2197 Binder.restoreCallingIdentity(ident);
2198 }
2199 return rect;
2200 }
2201
2202 @Override
2203 public ActivityManager.TaskDescription getTaskDescription(int id) {
2204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002205 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002207 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2209 if (tr != null) {
2210 return tr.lastTaskDescription;
2211 }
2212 }
2213 return null;
2214 }
2215
2216 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002217 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2218 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2219 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2220 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2221 return;
2222 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002223 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002224 synchronized (mGlobalLock) {
2225 final long ident = Binder.clearCallingIdentity();
2226 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002227 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002228 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002229 if (task == null) {
2230 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2231 return;
2232 }
2233
2234 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2235 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2236
2237 if (!task.isActivityTypeStandardOrUndefined()) {
2238 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2239 + " non-standard task " + taskId + " to windowing mode="
2240 + windowingMode);
2241 }
2242
2243 final ActivityStack stack = task.getStack();
2244 if (toTop) {
2245 stack.moveToFront("setTaskWindowingMode", task);
2246 }
2247 stack.setWindowingMode(windowingMode);
2248 } finally {
2249 Binder.restoreCallingIdentity(ident);
2250 }
2251 }
2252 }
2253
2254 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002255 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 ActivityRecord r = getCallingRecordLocked(token);
2258 return r != null ? r.info.packageName : null;
2259 }
2260 }
2261
2262 @Override
2263 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002264 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265 ActivityRecord r = getCallingRecordLocked(token);
2266 return r != null ? r.intent.getComponent() : null;
2267 }
2268 }
2269
2270 private ActivityRecord getCallingRecordLocked(IBinder token) {
2271 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2272 if (r == null) {
2273 return null;
2274 }
2275 return r.resultTo;
2276 }
2277
2278 @Override
2279 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002280 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002281
2282 synchronized (mGlobalLock) {
2283 final long origId = Binder.clearCallingIdentity();
2284 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002285 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 } finally {
2287 Binder.restoreCallingIdentity(origId);
2288 }
2289 }
2290 }
2291
Mark Renouf446251d2019-04-26 10:22:41 -04002292 @Override
2293 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2294 synchronized (mGlobalLock) {
2295 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2296 if (r == null) {
2297 return;
2298 }
2299 ActivityStack stack = r.getActivityStack();
2300 if (stack != null && stack.isSingleTaskInstance()) {
2301 // Single-task stacks are used for activities which are presented in floating
2302 // windows above full screen activities. Instead of directly finishing the
2303 // task, a task change listener is used to notify SystemUI so the action can be
2304 // handled specially.
2305 final TaskRecord task = r.getTaskRecord();
2306 mTaskChangeNotificationController
2307 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2308 } else {
2309 try {
2310 callback.requestFinish();
2311 } catch (RemoteException e) {
2312 Slog.e(TAG, "Failed to invoke request finish callback", e);
2313 }
2314 }
2315 }
2316 }
2317
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 /**
2319 * TODO: Add mController hook
2320 */
2321 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002322 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2323 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002324 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002325
2326 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2327 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002328 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2329 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002330 }
2331 }
2332
Ricky Waiaca8a772019-04-04 16:01:06 +01002333 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2334 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335 boolean fromRecents) {
2336
Ricky Waiaca8a772019-04-04 16:01:06 +01002337 final int callingPid = Binder.getCallingPid();
2338 final int callingUid = Binder.getCallingUid();
2339 if (!isSameApp(callingUid, callingPackage)) {
2340 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2341 + Binder.getCallingPid() + " as package " + callingPackage;
2342 Slog.w(TAG, msg);
2343 throw new SecurityException(msg);
2344 }
2345 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002346 SafeActivityOptions.abort(options);
2347 return;
2348 }
2349 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002350 WindowProcessController callerApp = null;
2351 if (appThread != null) {
2352 callerApp = getProcessController(appThread);
2353 }
2354 final ActivityStarter starter = getActivityStartController().obtainStarter(
2355 null /* intent */, "moveTaskToFront");
2356 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2357 -1, callerApp, null, false, null)) {
2358 boolean abort = !isBackgroundActivityStartsEnabled();
2359 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2360 if (abort) {
2361 return;
2362 }
2363 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002365 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 if (task == null) {
2367 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002368 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 return;
2370 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002371 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002373 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 return;
2375 }
2376 ActivityOptions realOptions = options != null
2377 ? options.getOptions(mStackSupervisor)
2378 : null;
2379 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2380 false /* forceNonResizable */);
2381
2382 final ActivityRecord topActivity = task.getTopActivity();
2383 if (topActivity != null) {
2384
2385 // We are reshowing a task, use a starting window to hide the initial draw delay
2386 // so the transition can start earlier.
2387 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2388 true /* taskSwitch */, fromRecents);
2389 }
2390 } finally {
2391 Binder.restoreCallingIdentity(origId);
2392 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 }
2394
Ricky Waiaca8a772019-04-04 16:01:06 +01002395 /**
2396 * Return true if callingUid is system, or packageName belongs to that callingUid.
2397 */
2398 boolean isSameApp(int callingUid, @Nullable String packageName) {
2399 try {
2400 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2401 if (packageName == null) {
2402 return false;
2403 }
2404 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2405 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2406 UserHandle.getUserId(callingUid));
2407 return UserHandle.isSameApp(callingUid, uid);
2408 }
2409 } catch (RemoteException e) {
2410 // Should not happen
2411 }
2412 return true;
2413 }
2414
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2416 int callingPid, int callingUid, String name) {
2417 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2418 return true;
2419 }
2420
2421 if (getRecentTasks().isCallerRecents(sourceUid)) {
2422 return true;
2423 }
2424
2425 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2426 if (perm == PackageManager.PERMISSION_GRANTED) {
2427 return true;
2428 }
2429 if (checkAllowAppSwitchUid(sourceUid)) {
2430 return true;
2431 }
2432
2433 // If the actual IPC caller is different from the logical source, then
2434 // also see if they are allowed to control app switches.
2435 if (callingUid != -1 && callingUid != sourceUid) {
2436 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2437 if (perm == PackageManager.PERMISSION_GRANTED) {
2438 return true;
2439 }
2440 if (checkAllowAppSwitchUid(callingUid)) {
2441 return true;
2442 }
2443 }
2444
2445 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2446 return false;
2447 }
2448
2449 private boolean checkAllowAppSwitchUid(int uid) {
2450 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2451 if (types != null) {
2452 for (int i = types.size() - 1; i >= 0; i--) {
2453 if (types.valueAt(i).intValue() == uid) {
2454 return true;
2455 }
2456 }
2457 }
2458 return false;
2459 }
2460
2461 @Override
2462 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2463 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2464 "setActivityController()");
2465 synchronized (mGlobalLock) {
2466 mController = controller;
2467 mControllerIsAMonkey = imAMonkey;
2468 Watchdog.getInstance().setActivityController(controller);
2469 }
2470 }
2471
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002472 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002473 synchronized (mGlobalLock) {
2474 return mController != null && mControllerIsAMonkey;
2475 }
2476 }
2477
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002478 @Override
2479 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2480 synchronized (mGlobalLock) {
2481 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2482 }
2483 }
2484
2485 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002486 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2487 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2488 }
2489
2490 @Override
2491 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2492 @WindowConfiguration.ActivityType int ignoreActivityType,
2493 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2494 final int callingUid = Binder.getCallingUid();
2495 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2496
2497 synchronized (mGlobalLock) {
2498 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2499
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002500 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002501 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002502 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002503 ignoreWindowingMode, callingUid, allowed);
2504 }
2505
2506 return list;
2507 }
2508
2509 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2511 synchronized (mGlobalLock) {
2512 final long origId = Binder.clearCallingIdentity();
2513 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2514 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002515 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002516 }
2517 Binder.restoreCallingIdentity(origId);
2518 }
2519 }
2520
2521 @Override
2522 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 ActivityStack stack = ActivityRecord.getStackLocked(token);
2525 if (stack != null) {
2526 return stack.willActivityBeVisibleLocked(token);
2527 }
2528 return false;
2529 }
2530 }
2531
2532 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002533 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002534 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 synchronized (mGlobalLock) {
2536 final long ident = Binder.clearCallingIdentity();
2537 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002538 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 if (task == null) {
2540 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2541 return;
2542 }
2543
2544 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2545 + " to stackId=" + stackId + " toTop=" + toTop);
2546
Wale Ogunwaled32da472018-11-16 07:19:28 -08002547 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002548 if (stack == null) {
2549 throw new IllegalStateException(
2550 "moveTaskToStack: No stack for stackId=" + stackId);
2551 }
2552 if (!stack.isActivityTypeStandardOrUndefined()) {
2553 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2554 + taskId + " to stack " + stackId);
2555 }
2556 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2559 }
2560 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2561 "moveTaskToStack");
2562 } finally {
2563 Binder.restoreCallingIdentity(ident);
2564 }
2565 }
2566 }
2567
2568 @Override
2569 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2570 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572
2573 final long ident = Binder.clearCallingIdentity();
2574 try {
2575 synchronized (mGlobalLock) {
2576 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002577 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 if (stack == null) {
2579 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2580 return;
2581 }
2582 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2583 throw new IllegalArgumentException("Stack: " + stackId
2584 + " doesn't support animated resize.");
2585 }
2586 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2587 animationDuration, false /* fromFullscreen */);
2588 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002589 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590 if (stack == null) {
2591 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2592 return;
2593 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2596 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2597 }
2598 }
2599 } finally {
2600 Binder.restoreCallingIdentity(ident);
2601 }
2602 }
2603
wilsonshih5c4cf522019-01-25 09:03:47 +08002604 @Override
2605 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2606 int animationDuration) {
2607 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2608
2609 final long ident = Binder.clearCallingIdentity();
2610 try {
2611 synchronized (mGlobalLock) {
2612 if (xOffset == 0 && yOffset == 0) {
2613 return;
2614 }
2615 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2616 if (stack == null) {
2617 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2618 return;
2619 }
2620 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2621 throw new IllegalArgumentException("Stack: " + stackId
2622 + " doesn't support animated resize.");
2623 }
2624 final Rect destBounds = new Rect();
2625 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002626 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002627 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2628 return;
2629 }
2630 destBounds.offset(xOffset, yOffset);
2631 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2632 animationDuration, false /* fromFullscreen */);
2633 }
2634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 /**
2639 * Moves the specified task to the primary-split-screen stack.
2640 *
2641 * @param taskId Id of task to move.
2642 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2643 * exist already. See
2644 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2645 * and
2646 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2647 * @param toTop If the task and stack should be moved to the top.
2648 * @param animate Whether we should play an animation for the moving the task.
2649 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2650 * stack. Pass {@code null} to use default bounds.
2651 * @param showRecents If the recents activity should be shown on the other side of the task
2652 * going into split-screen mode.
2653 */
2654 @Override
2655 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2656 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002657 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002658 "setTaskWindowingModeSplitScreenPrimary()");
2659 synchronized (mGlobalLock) {
2660 final long ident = Binder.clearCallingIdentity();
2661 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002662 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002663 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 if (task == null) {
2665 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2666 return false;
2667 }
2668 if (DEBUG_STACK) Slog.d(TAG_STACK,
2669 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2670 + " to createMode=" + createMode + " toTop=" + toTop);
2671 if (!task.isActivityTypeStandardOrUndefined()) {
2672 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2673 + " non-standard task " + taskId + " to split-screen windowing mode");
2674 }
2675
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002676 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002677 final int windowingMode = task.getWindowingMode();
2678 final ActivityStack stack = task.getStack();
2679 if (toTop) {
2680 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2681 }
2682 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002683 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2684 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 return windowingMode != task.getWindowingMode();
2686 } finally {
2687 Binder.restoreCallingIdentity(ident);
2688 }
2689 }
2690 }
2691
2692 /**
2693 * Removes stacks in the input windowing modes from the system if they are of activity type
2694 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2695 */
2696 @Override
2697 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002698 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 "removeStacksInWindowingModes()");
2700
2701 synchronized (mGlobalLock) {
2702 final long ident = Binder.clearCallingIdentity();
2703 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002704 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 } finally {
2706 Binder.restoreCallingIdentity(ident);
2707 }
2708 }
2709 }
2710
2711 @Override
2712 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002713 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002714 "removeStacksWithActivityTypes()");
2715
2716 synchronized (mGlobalLock) {
2717 final long ident = Binder.clearCallingIdentity();
2718 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002719 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 } finally {
2721 Binder.restoreCallingIdentity(ident);
2722 }
2723 }
2724 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002725
2726 @Override
2727 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2728 int userId) {
2729 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002730 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2731 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002732 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 final boolean detailed = checkGetTasksPermission(
2734 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2735 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 == PackageManager.PERMISSION_GRANTED;
2737
2738 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002739 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 callingUid);
2741 }
2742 }
2743
2744 @Override
2745 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002746 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 long ident = Binder.clearCallingIdentity();
2748 try {
2749 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002750 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 }
2752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756
2757 @Override
2758 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 long ident = Binder.clearCallingIdentity();
2761 try {
2762 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002763 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 }
2765 } finally {
2766 Binder.restoreCallingIdentity(ident);
2767 }
2768 }
2769
2770 @Override
2771 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 final long callingUid = Binder.getCallingUid();
2774 final long origId = Binder.clearCallingIdentity();
2775 try {
2776 synchronized (mGlobalLock) {
2777 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002778 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2780 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2781 }
2782 } finally {
2783 Binder.restoreCallingIdentity(origId);
2784 }
2785 }
2786
2787 @Override
2788 public void startLockTaskModeByToken(IBinder token) {
2789 synchronized (mGlobalLock) {
2790 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2791 if (r == null) {
2792 return;
2793 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002794 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 }
2797
2798 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002799 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 // This makes inner call to look as if it was initiated by system.
2802 long ident = Binder.clearCallingIdentity();
2803 try {
2804 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002805 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002806 MATCH_TASK_IN_STACKS_ONLY);
2807 if (task == null) {
2808 return;
2809 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810
2811 // When starting lock task mode the stack must be in front and focused
2812 task.getStack().moveToFront("startSystemLockTaskMode");
2813 startLockTaskModeLocked(task, true /* isSystemCaller */);
2814 }
2815 } finally {
2816 Binder.restoreCallingIdentity(ident);
2817 }
2818 }
2819
2820 @Override
2821 public void stopLockTaskModeByToken(IBinder token) {
2822 synchronized (mGlobalLock) {
2823 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2824 if (r == null) {
2825 return;
2826 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002827 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 }
2829 }
2830
2831 /**
2832 * This API should be called by SystemUI only when user perform certain action to dismiss
2833 * lock task mode. We should only dismiss pinned lock task mode in this case.
2834 */
2835 @Override
2836 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002837 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2839 }
2840
2841 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2842 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2843 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2844 return;
2845 }
2846
Wale Ogunwaled32da472018-11-16 07:19:28 -08002847 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 if (stack == null || task != stack.topTask()) {
2849 throw new IllegalArgumentException("Invalid task, not in foreground");
2850 }
2851
2852 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2853 // system or a specific app.
2854 // * System-initiated requests will only start the pinned mode (screen pinning)
2855 // * App-initiated requests
2856 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2857 // - will start the pinned mode, otherwise
2858 final int callingUid = Binder.getCallingUid();
2859 long ident = Binder.clearCallingIdentity();
2860 try {
2861 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002862 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002864 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865 } finally {
2866 Binder.restoreCallingIdentity(ident);
2867 }
2868 }
2869
2870 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2871 final int callingUid = Binder.getCallingUid();
2872 long ident = Binder.clearCallingIdentity();
2873 try {
2874 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002875 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 }
2877 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2878 // task and jumping straight into a call in the case of emergency call back.
2879 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2880 if (tm != null) {
2881 tm.showInCallScreen(false);
2882 }
2883 } finally {
2884 Binder.restoreCallingIdentity(ident);
2885 }
2886 }
2887
2888 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002889 public void updateLockTaskPackages(int userId, String[] packages) {
2890 final int callingUid = Binder.getCallingUid();
2891 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2892 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2893 "updateLockTaskPackages()");
2894 }
2895 synchronized (this) {
2896 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2897 + Arrays.toString(packages));
2898 getLockTaskController().updateLockTaskPackages(userId, packages);
2899 }
2900 }
2901
2902 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 public boolean isInLockTaskMode() {
2904 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2905 }
2906
2907 @Override
2908 public int getLockTaskModeState() {
2909 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002910 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 }
2912 }
2913
2914 @Override
2915 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2916 synchronized (mGlobalLock) {
2917 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2918 if (r != null) {
2919 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002920 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002922 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 }
2924 }
2925 }
2926
2927 @Override
2928 public Bundle getActivityOptions(IBinder token) {
2929 final long origId = Binder.clearCallingIdentity();
2930 try {
2931 synchronized (mGlobalLock) {
2932 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2933 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002934 final ActivityOptions activityOptions = r.takeOptionsLocked(
2935 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936 return activityOptions == null ? null : activityOptions.toBundle();
2937 }
2938 return null;
2939 }
2940 } finally {
2941 Binder.restoreCallingIdentity(origId);
2942 }
2943 }
2944
2945 @Override
2946 public List<IBinder> getAppTasks(String callingPackage) {
2947 int callingUid = Binder.getCallingUid();
2948 long ident = Binder.clearCallingIdentity();
2949 try {
2950 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002951 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 }
2953 } finally {
2954 Binder.restoreCallingIdentity(ident);
2955 }
2956 }
2957
2958 @Override
2959 public void finishVoiceTask(IVoiceInteractionSession session) {
2960 synchronized (mGlobalLock) {
2961 final long origId = Binder.clearCallingIdentity();
2962 try {
2963 // TODO: VI Consider treating local voice interactions and voice tasks
2964 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002965 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 } finally {
2967 Binder.restoreCallingIdentity(origId);
2968 }
2969 }
2970
2971 }
2972
2973 @Override
2974 public boolean isTopOfTask(IBinder token) {
2975 synchronized (mGlobalLock) {
2976 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002977 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 }
2979 }
2980
2981 @Override
2982 public void notifyLaunchTaskBehindComplete(IBinder token) {
2983 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2984 }
2985
2986 @Override
2987 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002988 mH.post(() -> {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002991 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002992 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002993 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002994 } catch (RemoteException e) {
2995 }
2996 }
2997 }
2998
2999 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 }
3001
3002 /** Called from an app when assist data is ready. */
3003 @Override
3004 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3005 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003006 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003007 synchronized (pae) {
3008 pae.result = extras;
3009 pae.structure = structure;
3010 pae.content = content;
3011 if (referrer != null) {
3012 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3013 }
3014 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003015 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003016 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3017 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 structure.setHomeActivity(pae.isHome);
3019 }
3020 pae.haveResult = true;
3021 pae.notifyAll();
3022 if (pae.intent == null && pae.receiver == null) {
3023 // Caller is just waiting for the result.
3024 return;
3025 }
3026 }
3027 // We are now ready to launch the assist activity.
3028 IAssistDataReceiver sendReceiver = null;
3029 Bundle sendBundle = null;
3030 synchronized (mGlobalLock) {
3031 buildAssistBundleLocked(pae, extras);
3032 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003033 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 if (!exists) {
3035 // Timed out.
3036 return;
3037 }
3038
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003039 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003040 // Caller wants result sent back to them.
3041 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003042 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3043 pae.activity.getTaskRecord().taskId);
3044 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3045 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3047 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3048 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3049 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3050 }
3051 }
3052 if (sendReceiver != null) {
3053 try {
3054 sendReceiver.onHandleAssistData(sendBundle);
3055 } catch (RemoteException e) {
3056 }
3057 return;
3058 }
3059
3060 final long ident = Binder.clearCallingIdentity();
3061 try {
3062 if (TextUtils.equals(pae.intent.getAction(),
3063 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3064 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003065
3066 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 } else {
3068 pae.intent.replaceExtras(pae.extras);
3069 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3070 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3071 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003072 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073
3074 try {
3075 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3076 } catch (ActivityNotFoundException e) {
3077 Slog.w(TAG, "No activity to handle assist action.", e);
3078 }
3079 }
3080 } finally {
3081 Binder.restoreCallingIdentity(ident);
3082 }
3083 }
3084
Marvin Ramin830d4e32019-03-12 13:16:58 +01003085 /**
3086 * Workaround for historical API which starts the Assist service with a non-foreground
3087 * {@code startService()} call.
3088 */
3089 private void startVoiceInteractionServiceAsUser(
3090 Intent intent, int userHandle, String reason) {
3091 // Resolve the intent to find out which package we need to whitelist.
3092 ResolveInfo resolveInfo =
3093 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3094 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3095 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3096 return;
3097 }
3098 intent.setPackage(resolveInfo.serviceInfo.packageName);
3099
3100 // Whitelist background services temporarily.
3101 LocalServices.getService(DeviceIdleController.LocalService.class)
3102 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3103 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3104
3105 // Finally, try to start the service.
3106 try {
3107 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3108 } catch (RuntimeException e) {
3109 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3110 }
3111 }
3112
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 @Override
3114 public int addAppTask(IBinder activityToken, Intent intent,
3115 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3116 final int callingUid = Binder.getCallingUid();
3117 final long callingIdent = Binder.clearCallingIdentity();
3118
3119 try {
3120 synchronized (mGlobalLock) {
3121 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3122 if (r == null) {
3123 throw new IllegalArgumentException("Activity does not exist; token="
3124 + activityToken);
3125 }
3126 ComponentName comp = intent.getComponent();
3127 if (comp == null) {
3128 throw new IllegalArgumentException("Intent " + intent
3129 + " must specify explicit component");
3130 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003131 if (thumbnail.getWidth() != mThumbnailWidth
3132 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 throw new IllegalArgumentException("Bad thumbnail size: got "
3134 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003135 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003136 }
3137 if (intent.getSelector() != null) {
3138 intent.setSelector(null);
3139 }
3140 if (intent.getSourceBounds() != null) {
3141 intent.setSourceBounds(null);
3142 }
3143 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3144 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3145 // The caller has added this as an auto-remove task... that makes no
3146 // sense, so turn off auto-remove.
3147 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3148 }
3149 }
3150 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3151 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3152 if (ainfo.applicationInfo.uid != callingUid) {
3153 throw new SecurityException(
3154 "Can't add task for another application: target uid="
3155 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3156 }
3157
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003158 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003160 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003162 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 // The app has too many tasks already and we can't add any more
3164 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3165 return INVALID_TASK_ID;
3166 }
3167 task.lastTaskDescription.copyFrom(description);
3168
3169 // TODO: Send the thumbnail to WM to store it.
3170
3171 return task.taskId;
3172 }
3173 } finally {
3174 Binder.restoreCallingIdentity(callingIdent);
3175 }
3176 }
3177
3178 @Override
3179 public Point getAppTaskThumbnailSize() {
3180 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003181 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 }
3183 }
3184
3185 @Override
3186 public void setTaskResizeable(int taskId, int resizeableMode) {
3187 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003188 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3190 if (task == null) {
3191 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3192 return;
3193 }
3194 task.setResizeMode(resizeableMode);
3195 }
3196 }
3197
3198 @Override
3199 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 long ident = Binder.clearCallingIdentity();
3202 try {
3203 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003204 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003205 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 if (task == null) {
3207 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3208 return;
3209 }
3210 // Place the task in the right stack if it isn't there already based on
3211 // the requested bounds.
3212 // The stack transition logic is:
3213 // - a null bounds on a freeform task moves that task to fullscreen
3214 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3215 // that task to freeform
3216 // - otherwise the task is not moved
3217 ActivityStack stack = task.getStack();
3218 if (!task.getWindowConfiguration().canResizeTask()) {
3219 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3220 }
3221 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3222 stack = stack.getDisplay().getOrCreateStack(
3223 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3224 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3225 stack = stack.getDisplay().getOrCreateStack(
3226 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3227 }
3228
3229 // Reparent the task to the right stack if necessary
3230 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3231 if (stack != task.getStack()) {
3232 // Defer resume until the task is resized below
3233 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3234 DEFER_RESUME, "resizeTask");
3235 preserveWindow = false;
3236 }
3237
3238 // After reparenting (which only resizes the task to the stack bounds), resize the
3239 // task to the actual bounds provided
3240 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3241 }
3242 } finally {
3243 Binder.restoreCallingIdentity(ident);
3244 }
3245 }
3246
3247 @Override
3248 public boolean releaseActivityInstance(IBinder token) {
3249 synchronized (mGlobalLock) {
3250 final long origId = Binder.clearCallingIdentity();
3251 try {
3252 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3253 if (r == null) {
3254 return false;
3255 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003256 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003257 } finally {
3258 Binder.restoreCallingIdentity(origId);
3259 }
3260 }
3261 }
3262
3263 @Override
3264 public void releaseSomeActivities(IApplicationThread appInt) {
3265 synchronized (mGlobalLock) {
3266 final long origId = Binder.clearCallingIdentity();
3267 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003268 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003269 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003270 } finally {
3271 Binder.restoreCallingIdentity(origId);
3272 }
3273 }
3274 }
3275
3276 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003277 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003278 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003279 != PackageManager.PERMISSION_GRANTED) {
3280 throw new SecurityException("Requires permission "
3281 + android.Manifest.permission.DEVICE_POWER);
3282 }
3283
3284 synchronized (mGlobalLock) {
3285 long ident = Binder.clearCallingIdentity();
3286 if (mKeyguardShown != keyguardShowing) {
3287 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003288 final Message msg = PooledLambda.obtainMessage(
3289 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3290 keyguardShowing);
3291 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003292 }
3293 try {
wilsonshih177261f2019-02-22 12:02:18 +08003294 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 } finally {
3296 Binder.restoreCallingIdentity(ident);
3297 }
3298 }
3299
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003300 mH.post(() -> {
3301 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3302 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3303 }
3304 });
3305 }
3306
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003307 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003308 mH.post(() -> {
3309 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3310 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3311 }
3312 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 }
3314
3315 @Override
3316 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003317 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3318 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319
3320 final File passedIconFile = new File(filePath);
3321 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3322 passedIconFile.getName());
3323 if (!legitIconFile.getPath().equals(filePath)
3324 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3325 throw new IllegalArgumentException("Bad file path: " + filePath
3326 + " passed for userId " + userId);
3327 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003328 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 }
3330
3331 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003332 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3334 final ActivityOptions activityOptions = safeOptions != null
3335 ? safeOptions.getOptions(mStackSupervisor)
3336 : null;
3337 if (activityOptions == null
3338 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3339 || activityOptions.getCustomInPlaceResId() == 0) {
3340 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3341 "with valid animation");
3342 }
lumark588a3e82018-07-20 18:53:54 +08003343 // Get top display of front most application.
3344 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3345 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003346 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3347 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3348 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003349 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003350 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003351 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 }
3353
3354 @Override
3355 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003356 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 synchronized (mGlobalLock) {
3358 final long ident = Binder.clearCallingIdentity();
3359 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003360 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 if (stack == null) {
3362 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3363 return;
3364 }
3365 if (!stack.isActivityTypeStandardOrUndefined()) {
3366 throw new IllegalArgumentException(
3367 "Removing non-standard stack is not allowed.");
3368 }
3369 mStackSupervisor.removeStack(stack);
3370 } finally {
3371 Binder.restoreCallingIdentity(ident);
3372 }
3373 }
3374 }
3375
3376 @Override
3377 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003378 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379
3380 synchronized (mGlobalLock) {
3381 final long ident = Binder.clearCallingIdentity();
3382 try {
3383 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3384 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003385 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 } finally {
3387 Binder.restoreCallingIdentity(ident);
3388 }
3389 }
3390 }
3391
3392 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003393 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 synchronized (mGlobalLock) {
3395 long ident = Binder.clearCallingIdentity();
3396 try {
3397 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3398 if (r == null) {
3399 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003400 "toggleFreeformWindowingMode: No activity record matching token="
3401 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 }
3403
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003404 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003405 if (stack == null) {
3406 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3407 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 }
3409
Yunfan Chend967af82019-01-17 18:30:18 +09003410 if (!stack.inFreeformWindowingMode()
3411 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3412 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3413 + "toggle between fullscreen and freeform.");
3414 }
3415
3416 if (stack.inFreeformWindowingMode()) {
3417 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003418 } else if (stack.getParent().inFreeformWindowingMode()) {
3419 // If the window is on a freeform display, set it to undefined. It will be
3420 // resolved to freeform and it can adjust windowing mode when the display mode
3421 // changes in runtime.
3422 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003423 } else {
3424 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3425 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 } finally {
3427 Binder.restoreCallingIdentity(ident);
3428 }
3429 }
3430 }
3431
3432 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3433 @Override
3434 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003437 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 }
3439
3440 /** Unregister a task stack listener so that it stops receiving callbacks. */
3441 @Override
3442 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003443 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003444 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003445 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 }
3447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003448 @Override
3449 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3450 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3451 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3452 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3453 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3454 }
3455
3456 @Override
3457 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3458 IBinder activityToken, int flags) {
3459 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3460 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3461 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3462 }
3463
3464 @Override
3465 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3466 Bundle args) {
3467 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3468 true /* focused */, true /* newSessionId */, userHandle, args,
3469 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3470 }
3471
3472 @Override
3473 public Bundle getAssistContextExtras(int requestType) {
3474 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3475 null, null, true /* focused */, true /* newSessionId */,
3476 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3477 if (pae == null) {
3478 return null;
3479 }
3480 synchronized (pae) {
3481 while (!pae.haveResult) {
3482 try {
3483 pae.wait();
3484 } catch (InterruptedException e) {
3485 }
3486 }
3487 }
3488 synchronized (mGlobalLock) {
3489 buildAssistBundleLocked(pae, pae.result);
3490 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003491 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492 }
3493 return pae.extras;
3494 }
3495
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003496 /**
3497 * Binder IPC calls go through the public entry point.
3498 * This can be called with or without the global lock held.
3499 */
3500 private static int checkCallingPermission(String permission) {
3501 return checkPermission(
3502 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3503 }
3504
3505 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003506 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003507 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3508 mAmInternal.enforceCallingPermission(permission, func);
3509 }
3510 }
3511
3512 @VisibleForTesting
3513 int checkGetTasksPermission(String permission, int pid, int uid) {
3514 return checkPermission(permission, pid, uid);
3515 }
3516
3517 static int checkPermission(String permission, int pid, int uid) {
3518 if (permission == null) {
3519 return PackageManager.PERMISSION_DENIED;
3520 }
3521 return checkComponentPermission(permission, pid, uid, -1, true);
3522 }
3523
Wale Ogunwale214f3482018-10-04 11:00:47 -07003524 public static int checkComponentPermission(String permission, int pid, int uid,
3525 int owningUid, boolean exported) {
3526 return ActivityManagerService.checkComponentPermission(
3527 permission, pid, uid, owningUid, exported);
3528 }
3529
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003530 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3531 if (getRecentTasks().isCallerRecents(callingUid)) {
3532 // Always allow the recents component to get tasks
3533 return true;
3534 }
3535
3536 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3537 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3538 if (!allowed) {
3539 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3540 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3541 // Temporary compatibility: some existing apps on the system image may
3542 // still be requesting the old permission and not switched to the new
3543 // one; if so, we'll still allow them full access. This means we need
3544 // to see if they are holding the old permission and are a system app.
3545 try {
3546 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3547 allowed = true;
3548 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3549 + " is using old GET_TASKS but privileged; allowing");
3550 }
3551 } catch (RemoteException e) {
3552 }
3553 }
3554 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3555 + " does not hold REAL_GET_TASKS; limiting output");
3556 }
3557 return allowed;
3558 }
3559
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3561 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3562 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3563 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003564 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003565 "enqueueAssistContext()");
3566
3567 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003568 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003569 if (activity == null) {
3570 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3571 return null;
3572 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003573 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3575 return null;
3576 }
3577 if (focused) {
3578 if (activityToken != null) {
3579 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3580 if (activity != caller) {
3581 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3582 + " is not current top " + activity);
3583 return null;
3584 }
3585 }
3586 } else {
3587 activity = ActivityRecord.forTokenLocked(activityToken);
3588 if (activity == null) {
3589 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3590 + " couldn't be found");
3591 return null;
3592 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003593 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3595 return null;
3596 }
3597 }
3598
3599 PendingAssistExtras pae;
3600 Bundle extras = new Bundle();
3601 if (args != null) {
3602 extras.putAll(args);
3603 }
3604 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003605 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606
3607 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3608 userHandle);
3609 pae.isHome = activity.isActivityTypeHome();
3610
3611 // Increment the sessionId if necessary
3612 if (newSessionId) {
3613 mViSessionId++;
3614 }
3615 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003616 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3617 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003618 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003619 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 } catch (RemoteException e) {
3621 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3622 return null;
3623 }
3624 return pae;
3625 }
3626 }
3627
3628 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3629 if (result != null) {
3630 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3631 }
3632 if (pae.hint != null) {
3633 pae.extras.putBoolean(pae.hint, true);
3634 }
3635 }
3636
3637 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3638 IAssistDataReceiver receiver;
3639 synchronized (mGlobalLock) {
3640 mPendingAssistExtras.remove(pae);
3641 receiver = pae.receiver;
3642 }
3643 if (receiver != null) {
3644 // Caller wants result sent back to them.
3645 Bundle sendBundle = new Bundle();
3646 // At least return the receiver extras
3647 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3648 try {
3649 pae.receiver.onHandleAssistData(sendBundle);
3650 } catch (RemoteException e) {
3651 }
3652 }
3653 }
3654
3655 public class PendingAssistExtras extends Binder implements Runnable {
3656 public final ActivityRecord activity;
3657 public boolean isHome;
3658 public final Bundle extras;
3659 public final Intent intent;
3660 public final String hint;
3661 public final IAssistDataReceiver receiver;
3662 public final int userHandle;
3663 public boolean haveResult = false;
3664 public Bundle result = null;
3665 public AssistStructure structure = null;
3666 public AssistContent content = null;
3667 public Bundle receiverExtras;
3668
3669 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3670 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3671 int _userHandle) {
3672 activity = _activity;
3673 extras = _extras;
3674 intent = _intent;
3675 hint = _hint;
3676 receiver = _receiver;
3677 receiverExtras = _receiverExtras;
3678 userHandle = _userHandle;
3679 }
3680
3681 @Override
3682 public void run() {
3683 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3684 synchronized (this) {
3685 haveResult = true;
3686 notifyAll();
3687 }
3688 pendingAssistExtrasTimedOut(this);
3689 }
3690 }
3691
3692 @Override
3693 public boolean isAssistDataAllowedOnCurrentActivity() {
3694 int userId;
3695 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003696 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3698 return false;
3699 }
3700
3701 final ActivityRecord activity = focusedStack.getTopActivity();
3702 if (activity == null) {
3703 return false;
3704 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003705 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003706 }
3707 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3708 }
3709
3710 @Override
3711 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3712 long ident = Binder.clearCallingIdentity();
3713 try {
3714 synchronized (mGlobalLock) {
3715 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003716 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003717 if (top != caller) {
3718 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3719 + " is not current top " + top);
3720 return false;
3721 }
3722 if (!top.nowVisible) {
3723 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3724 + " is not visible");
3725 return false;
3726 }
3727 }
3728 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3729 token);
3730 } finally {
3731 Binder.restoreCallingIdentity(ident);
3732 }
3733 }
3734
3735 @Override
3736 public boolean isRootVoiceInteraction(IBinder token) {
3737 synchronized (mGlobalLock) {
3738 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3739 if (r == null) {
3740 return false;
3741 }
3742 return r.rootVoiceInteraction;
3743 }
3744 }
3745
Wale Ogunwalef6733932018-06-27 05:14:34 -07003746 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3747 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3748 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3749 if (activityToCallback == null) return;
3750 activityToCallback.setVoiceSessionLocked(voiceSession);
3751
3752 // Inform the activity
3753 try {
3754 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3755 voiceInteractor);
3756 long token = Binder.clearCallingIdentity();
3757 try {
3758 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3759 } finally {
3760 Binder.restoreCallingIdentity(token);
3761 }
3762 // TODO: VI Should we cache the activity so that it's easier to find later
3763 // rather than scan through all the stacks and activities?
3764 } catch (RemoteException re) {
3765 activityToCallback.clearVoiceSessionLocked();
3766 // TODO: VI Should this terminate the voice session?
3767 }
3768 }
3769
3770 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3771 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3772 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3773 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3774 boolean wasRunningVoice = mRunningVoice != null;
3775 mRunningVoice = session;
3776 if (!wasRunningVoice) {
3777 mVoiceWakeLock.acquire();
3778 updateSleepIfNeededLocked();
3779 }
3780 }
3781 }
3782
3783 void finishRunningVoiceLocked() {
3784 if (mRunningVoice != null) {
3785 mRunningVoice = null;
3786 mVoiceWakeLock.release();
3787 updateSleepIfNeededLocked();
3788 }
3789 }
3790
3791 @Override
3792 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3793 synchronized (mGlobalLock) {
3794 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3795 if (keepAwake) {
3796 mVoiceWakeLock.acquire();
3797 } else {
3798 mVoiceWakeLock.release();
3799 }
3800 }
3801 }
3802 }
3803
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 @Override
3805 public ComponentName getActivityClassForToken(IBinder token) {
3806 synchronized (mGlobalLock) {
3807 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3808 if (r == null) {
3809 return null;
3810 }
3811 return r.intent.getComponent();
3812 }
3813 }
3814
3815 @Override
3816 public String getPackageForToken(IBinder token) {
3817 synchronized (mGlobalLock) {
3818 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3819 if (r == null) {
3820 return null;
3821 }
3822 return r.packageName;
3823 }
3824 }
3825
3826 @Override
3827 public void showLockTaskEscapeMessage(IBinder token) {
3828 synchronized (mGlobalLock) {
3829 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3830 if (r == null) {
3831 return;
3832 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003833 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 }
3835 }
3836
3837 @Override
3838 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003839 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 final long token = Binder.clearCallingIdentity();
3841 try {
3842 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003843 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 }
3845 } finally {
3846 Binder.restoreCallingIdentity(token);
3847 }
3848 }
3849
3850 /**
3851 * Try to place task to provided position. The final position might be different depending on
3852 * current user and stacks state. The task will be moved to target stack if it's currently in
3853 * different stack.
3854 */
3855 @Override
3856 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003857 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 synchronized (mGlobalLock) {
3859 long ident = Binder.clearCallingIdentity();
3860 try {
3861 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3862 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003863 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 if (task == null) {
3865 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3866 + taskId);
3867 }
3868
Wale Ogunwaled32da472018-11-16 07:19:28 -08003869 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870
3871 if (stack == null) {
3872 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3873 + stackId);
3874 }
3875 if (!stack.isActivityTypeStandardOrUndefined()) {
3876 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3877 + " the position of task " + taskId + " in/to non-standard stack");
3878 }
3879
3880 // TODO: Have the callers of this API call a separate reparent method if that is
3881 // what they intended to do vs. having this method also do reparenting.
3882 if (task.getStack() == stack) {
3883 // Change position in current stack.
3884 stack.positionChildAt(task, position);
3885 } else {
3886 // Reparent to new stack.
3887 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3888 !DEFER_RESUME, "positionTaskInStack");
3889 }
3890 } finally {
3891 Binder.restoreCallingIdentity(ident);
3892 }
3893 }
3894 }
3895
3896 @Override
3897 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3898 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3899 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3900 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3901 synchronized (mGlobalLock) {
3902 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3903 if (record == null) {
3904 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3905 + "found for: " + token);
3906 }
3907 record.setSizeConfigurations(horizontalSizeConfiguration,
3908 verticalSizeConfigurations, smallestSizeConfigurations);
3909 }
3910 }
3911
3912 /**
3913 * Dismisses split-screen multi-window mode.
3914 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3915 */
3916 @Override
3917 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003918 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3920 final long ident = Binder.clearCallingIdentity();
3921 try {
3922 synchronized (mGlobalLock) {
3923 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003924 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 if (stack == null) {
3926 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3927 return;
3928 }
3929
3930 if (toTop) {
3931 // Caller wants the current split-screen primary stack to be the top stack after
3932 // it goes fullscreen, so move it to the front.
3933 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003934 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 // In this case the current split-screen primary stack shouldn't be the top
3936 // stack after it goes fullscreen, but it current has focus, so we move the
3937 // focus to the top-most split-screen secondary stack next to it.
3938 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3939 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3940 if (otherStack != null) {
3941 otherStack.moveToFront("dismissSplitScreenMode_other");
3942 }
3943 }
3944
Evan Rosky10475742018-09-05 19:02:48 -07003945 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 }
3947 } finally {
3948 Binder.restoreCallingIdentity(ident);
3949 }
3950 }
3951
3952 /**
3953 * Dismisses Pip
3954 * @param animate True if the dismissal should be animated.
3955 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3956 * default animation duration should be used.
3957 */
3958 @Override
3959 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003960 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 final long ident = Binder.clearCallingIdentity();
3962 try {
3963 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003964 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003965 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 if (stack == null) {
3967 Slog.w(TAG, "dismissPip: pinned stack not found.");
3968 return;
3969 }
3970 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3971 throw new IllegalArgumentException("Stack: " + stack
3972 + " doesn't support animated resize.");
3973 }
3974 if (animate) {
3975 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3976 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3977 } else {
3978 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3979 }
3980 }
3981 } finally {
3982 Binder.restoreCallingIdentity(ident);
3983 }
3984 }
3985
3986 @Override
3987 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 synchronized (mGlobalLock) {
3990 mSuppressResizeConfigChanges = suppress;
3991 }
3992 }
3993
3994 /**
3995 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3996 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3997 * activity and clearing the task at the same time.
3998 */
3999 @Override
4000 // TODO: API should just be about changing windowing modes...
4001 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004002 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 "moveTasksToFullscreenStack()");
4004 synchronized (mGlobalLock) {
4005 final long origId = Binder.clearCallingIdentity();
4006 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004007 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 if (stack != null){
4009 if (!stack.isActivityTypeStandardOrUndefined()) {
4010 throw new IllegalArgumentException(
4011 "You can't move tasks from non-standard stacks.");
4012 }
4013 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4014 }
4015 } finally {
4016 Binder.restoreCallingIdentity(origId);
4017 }
4018 }
4019 }
4020
4021 /**
4022 * Moves the top activity in the input stackId to the pinned stack.
4023 *
4024 * @param stackId Id of stack to move the top activity to pinned stack.
4025 * @param bounds Bounds to use for pinned stack.
4026 *
4027 * @return True if the top activity of the input stack was successfully moved to the pinned
4028 * stack.
4029 */
4030 @Override
4031 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 "moveTopActivityToPinnedStack()");
4034 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004035 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4037 + "Device doesn't support picture-in-picture mode");
4038 }
4039
4040 long ident = Binder.clearCallingIdentity();
4041 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004042 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 } finally {
4044 Binder.restoreCallingIdentity(ident);
4045 }
4046 }
4047 }
4048
4049 @Override
4050 public boolean isInMultiWindowMode(IBinder token) {
4051 final long origId = Binder.clearCallingIdentity();
4052 try {
4053 synchronized (mGlobalLock) {
4054 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4055 if (r == null) {
4056 return false;
4057 }
4058 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4059 return r.inMultiWindowMode();
4060 }
4061 } finally {
4062 Binder.restoreCallingIdentity(origId);
4063 }
4064 }
4065
4066 @Override
4067 public boolean isInPictureInPictureMode(IBinder token) {
4068 final long origId = Binder.clearCallingIdentity();
4069 try {
4070 synchronized (mGlobalLock) {
4071 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4072 }
4073 } finally {
4074 Binder.restoreCallingIdentity(origId);
4075 }
4076 }
4077
4078 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004079 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4080 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 return false;
4082 }
4083
4084 // If we are animating to fullscreen then we have already dispatched the PIP mode
4085 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004086 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4087 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 }
4089
4090 @Override
4091 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4092 final long origId = Binder.clearCallingIdentity();
4093 try {
4094 synchronized (mGlobalLock) {
4095 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4096 "enterPictureInPictureMode", token, params);
4097
4098 // If the activity is already in picture in picture mode, then just return early
4099 if (isInPictureInPictureMode(r)) {
4100 return true;
4101 }
4102
4103 // Activity supports picture-in-picture, now check that we can enter PiP at this
4104 // point, if it is
4105 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4106 false /* beforeStopping */)) {
4107 return false;
4108 }
4109
4110 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004111 synchronized (mGlobalLock) {
4112 // Only update the saved args from the args that are set
4113 r.pictureInPictureArgs.copyOnlySet(params);
4114 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4115 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4116 // Adjust the source bounds by the insets for the transition down
4117 final Rect sourceBounds = new Rect(
4118 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004119 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004120 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004121 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004122 stack.setPictureInPictureAspectRatio(aspectRatio);
4123 stack.setPictureInPictureActions(actions);
4124 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4125 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4126 logPictureInPictureArgs(params);
4127 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004128 };
4129
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004130 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004131 // If the keyguard is showing or occluded, then try and dismiss it before
4132 // entering picture-in-picture (this will prompt the user to authenticate if the
4133 // device is currently locked).
4134 dismissKeyguard(token, new KeyguardDismissCallback() {
4135 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004136 public void onDismissSucceeded() {
4137 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138 }
4139 }, null /* message */);
4140 } else {
4141 // Enter picture in picture immediately otherwise
4142 enterPipRunnable.run();
4143 }
4144 return true;
4145 }
4146 } finally {
4147 Binder.restoreCallingIdentity(origId);
4148 }
4149 }
4150
4151 @Override
4152 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4153 final long origId = Binder.clearCallingIdentity();
4154 try {
4155 synchronized (mGlobalLock) {
4156 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4157 "setPictureInPictureParams", token, params);
4158
4159 // Only update the saved args from the args that are set
4160 r.pictureInPictureArgs.copyOnlySet(params);
4161 if (r.inPinnedWindowingMode()) {
4162 // If the activity is already in picture-in-picture, update the pinned stack now
4163 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4164 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004165 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 if (!stack.isAnimatingBoundsToFullscreen()) {
4167 stack.setPictureInPictureAspectRatio(
4168 r.pictureInPictureArgs.getAspectRatio());
4169 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4170 }
4171 }
4172 logPictureInPictureArgs(params);
4173 }
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177 }
4178
4179 @Override
4180 public int getMaxNumPictureInPictureActions(IBinder token) {
4181 // Currently, this is a static constant, but later, we may change this to be dependent on
4182 // the context of the activity
4183 return 3;
4184 }
4185
4186 private void logPictureInPictureArgs(PictureInPictureParams params) {
4187 if (params.hasSetActions()) {
4188 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4189 params.getActions().size());
4190 }
4191 if (params.hasSetAspectRatio()) {
4192 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4193 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4194 MetricsLogger.action(lm);
4195 }
4196 }
4197
4198 /**
4199 * Checks the state of the system and the activity associated with the given {@param token} to
4200 * verify that picture-in-picture is supported for that activity.
4201 *
4202 * @return the activity record for the given {@param token} if all the checks pass.
4203 */
4204 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4205 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 throw new IllegalStateException(caller
4208 + ": Device doesn't support picture-in-picture mode.");
4209 }
4210
4211 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4212 if (r == null) {
4213 throw new IllegalStateException(caller
4214 + ": Can't find activity for token=" + token);
4215 }
4216
4217 if (!r.supportsPictureInPicture()) {
4218 throw new IllegalStateException(caller
4219 + ": Current activity does not support picture-in-picture.");
4220 }
4221
4222 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004223 && !mWindowManager.isValidPictureInPictureAspectRatio(
4224 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 final float minAspectRatio = mContext.getResources().getFloat(
4226 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4227 final float maxAspectRatio = mContext.getResources().getFloat(
4228 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4229 throw new IllegalArgumentException(String.format(caller
4230 + ": Aspect ratio is too extreme (must be between %f and %f).",
4231 minAspectRatio, maxAspectRatio));
4232 }
4233
4234 // Truncate the number of actions if necessary
4235 params.truncateActions(getMaxNumPictureInPictureActions(token));
4236
4237 return r;
4238 }
4239
4240 @Override
4241 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 synchronized (mGlobalLock) {
4244 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4245 if (r == null) {
4246 throw new IllegalArgumentException("Activity does not exist; token="
4247 + activityToken);
4248 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004249 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 }
4251 }
4252
4253 @Override
4254 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4255 Rect tempDockedTaskInsetBounds,
4256 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004257 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 long ident = Binder.clearCallingIdentity();
4259 try {
4260 synchronized (mGlobalLock) {
4261 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4262 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4263 PRESERVE_WINDOWS);
4264 }
4265 } finally {
4266 Binder.restoreCallingIdentity(ident);
4267 }
4268 }
4269
4270 @Override
4271 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004272 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004273 final long ident = Binder.clearCallingIdentity();
4274 try {
4275 synchronized (mGlobalLock) {
4276 mStackSupervisor.setSplitScreenResizing(resizing);
4277 }
4278 } finally {
4279 Binder.restoreCallingIdentity(ident);
4280 }
4281 }
4282
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004283 /**
4284 * Check that we have the features required for VR-related API calls, and throw an exception if
4285 * not.
4286 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004287 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004288 if (!mContext.getPackageManager().hasSystemFeature(
4289 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4290 throw new UnsupportedOperationException("VR mode not supported on this device!");
4291 }
4292 }
4293
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 @Override
4295 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004296 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004297
4298 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4299
4300 ActivityRecord r;
4301 synchronized (mGlobalLock) {
4302 r = ActivityRecord.isInStackLocked(token);
4303 }
4304
4305 if (r == null) {
4306 throw new IllegalArgumentException();
4307 }
4308
4309 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004310 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 VrManagerInternal.NO_ERROR) {
4312 return err;
4313 }
4314
4315 // Clear the binder calling uid since this path may call moveToTask().
4316 final long callingId = Binder.clearCallingIdentity();
4317 try {
4318 synchronized (mGlobalLock) {
4319 r.requestedVrComponent = (enabled) ? packageName : null;
4320
4321 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004322 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004323 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324 }
4325 return 0;
4326 }
4327 } finally {
4328 Binder.restoreCallingIdentity(callingId);
4329 }
4330 }
4331
4332 @Override
4333 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4334 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4335 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004336 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4338 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4339 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004340 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 || activity.voiceSession != null) {
4342 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4343 return;
4344 }
4345 if (activity.pendingVoiceInteractionStart) {
4346 Slog.w(TAG, "Pending start of voice interaction already.");
4347 return;
4348 }
4349 activity.pendingVoiceInteractionStart = true;
4350 }
4351 LocalServices.getService(VoiceInteractionManagerInternal.class)
4352 .startLocalVoiceInteraction(callingActivity, options);
4353 }
4354
4355 @Override
4356 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4357 LocalServices.getService(VoiceInteractionManagerInternal.class)
4358 .stopLocalVoiceInteraction(callingActivity);
4359 }
4360
4361 @Override
4362 public boolean supportsLocalVoiceInteraction() {
4363 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4364 .supportsLocalVoiceInteraction();
4365 }
4366
4367 /** Notifies all listeners when the pinned stack animation starts. */
4368 @Override
4369 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004370 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 }
4372
4373 /** Notifies all listeners when the pinned stack animation ends. */
4374 @Override
4375 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004376 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 }
4378
4379 @Override
4380 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004381 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382 final long ident = Binder.clearCallingIdentity();
4383 try {
4384 synchronized (mGlobalLock) {
4385 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4386 }
4387 } finally {
4388 Binder.restoreCallingIdentity(ident);
4389 }
4390 }
4391
4392 @Override
4393 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004394 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395
4396 synchronized (mGlobalLock) {
4397 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004398 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 // Call might come when display is not yet added or has already been removed.
4400 if (DEBUG_CONFIGURATION) {
4401 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4402 + displayId);
4403 }
4404 return false;
4405 }
4406
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004407 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004409 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 }
4411
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004413 final Message msg = PooledLambda.obtainMessage(
4414 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4415 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 }
4417
4418 final long origId = Binder.clearCallingIdentity();
4419 try {
4420 if (values != null) {
4421 Settings.System.clearConfiguration(values);
4422 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004423 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4425 return mTmpUpdateConfigurationResult.changes != 0;
4426 } finally {
4427 Binder.restoreCallingIdentity(origId);
4428 }
4429 }
4430 }
4431
4432 @Override
4433 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435
4436 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004437 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 }
4441
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004443 final Message msg = PooledLambda.obtainMessage(
4444 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4445 DEFAULT_DISPLAY);
4446 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 }
4448
4449 final long origId = Binder.clearCallingIdentity();
4450 try {
4451 if (values != null) {
4452 Settings.System.clearConfiguration(values);
4453 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 UserHandle.USER_NULL, false /* deferResume */,
4456 mTmpUpdateConfigurationResult);
4457 return mTmpUpdateConfigurationResult.changes != 0;
4458 } finally {
4459 Binder.restoreCallingIdentity(origId);
4460 }
4461 }
4462 }
4463
4464 @Override
4465 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4466 CharSequence message) {
4467 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4470 }
4471 final long callingId = Binder.clearCallingIdentity();
4472 try {
4473 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004474 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 }
4476 } finally {
4477 Binder.restoreCallingIdentity(callingId);
4478 }
4479 }
4480
4481 @Override
4482 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004483 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 "cancelTaskWindowTransition()");
4485 final long ident = Binder.clearCallingIdentity();
4486 try {
4487 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004488 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 MATCH_TASK_IN_STACKS_ONLY);
4490 if (task == null) {
4491 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4492 return;
4493 }
4494 task.cancelWindowTransition();
4495 }
4496 } finally {
4497 Binder.restoreCallingIdentity(ident);
4498 }
4499 }
4500
4501 @Override
4502 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 final long ident = Binder.clearCallingIdentity();
4505 try {
4506 final TaskRecord task;
4507 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004508 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4510 if (task == null) {
4511 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4512 return null;
4513 }
4514 }
4515 // Don't call this while holding the lock as this operation might hit the disk.
4516 return task.getSnapshot(reducedResolution);
4517 } finally {
4518 Binder.restoreCallingIdentity(ident);
4519 }
4520 }
4521
4522 @Override
4523 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4524 synchronized (mGlobalLock) {
4525 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4526 if (r == null) {
4527 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4528 + token);
4529 return;
4530 }
4531 final long origId = Binder.clearCallingIdentity();
4532 try {
4533 r.setDisablePreviewScreenshots(disable);
4534 } finally {
4535 Binder.restoreCallingIdentity(origId);
4536 }
4537 }
4538 }
4539
4540 /** Return the user id of the last resumed activity. */
4541 @Override
4542 public @UserIdInt
4543 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004544 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004545 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4546 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004547 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004548 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004550 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004551 }
4552 }
4553
4554 @Override
4555 public void updateLockTaskFeatures(int userId, int flags) {
4556 final int callingUid = Binder.getCallingUid();
4557 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004558 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 "updateLockTaskFeatures()");
4560 }
4561 synchronized (mGlobalLock) {
4562 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4563 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004564 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 }
4566 }
4567
4568 @Override
4569 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4570 synchronized (mGlobalLock) {
4571 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4572 if (r == null) {
4573 return;
4574 }
4575 final long origId = Binder.clearCallingIdentity();
4576 try {
4577 r.setShowWhenLocked(showWhenLocked);
4578 } finally {
4579 Binder.restoreCallingIdentity(origId);
4580 }
4581 }
4582 }
4583
4584 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004585 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4586 synchronized (mGlobalLock) {
4587 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4588 if (r == null) {
4589 return;
4590 }
4591 final long origId = Binder.clearCallingIdentity();
4592 try {
4593 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4594 } finally {
4595 Binder.restoreCallingIdentity(origId);
4596 }
4597 }
4598 }
4599
4600 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4602 synchronized (mGlobalLock) {
4603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4604 if (r == null) {
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 r.setTurnScreenOn(turnScreenOn);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
4617 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004618 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004619 "registerRemoteAnimations");
4620 definition.setCallingPid(Binder.getCallingPid());
4621 synchronized (mGlobalLock) {
4622 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4623 if (r == null) {
4624 return;
4625 }
4626 final long origId = Binder.clearCallingIdentity();
4627 try {
4628 r.registerRemoteAnimations(definition);
4629 } finally {
4630 Binder.restoreCallingIdentity(origId);
4631 }
4632 }
4633 }
4634
4635 @Override
4636 public void registerRemoteAnimationForNextActivityStart(String packageName,
4637 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004638 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 "registerRemoteAnimationForNextActivityStart");
4640 adapter.setCallingPid(Binder.getCallingPid());
4641 synchronized (mGlobalLock) {
4642 final long origId = Binder.clearCallingIdentity();
4643 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004644 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004645 packageName, adapter);
4646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650 }
4651
Evan Rosky966759f2019-01-15 10:33:58 -08004652 @Override
4653 public void registerRemoteAnimationsForDisplay(int displayId,
4654 RemoteAnimationDefinition definition) {
4655 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4656 "registerRemoteAnimations");
4657 definition.setCallingPid(Binder.getCallingPid());
4658 synchronized (mGlobalLock) {
4659 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4660 if (display == null) {
4661 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4662 return;
4663 }
4664 final long origId = Binder.clearCallingIdentity();
4665 try {
4666 display.mDisplayContent.registerRemoteAnimations(definition);
4667 } finally {
4668 Binder.restoreCallingIdentity(origId);
4669 }
4670 }
4671 }
4672
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004673 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4674 @Override
4675 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4676 synchronized (mGlobalLock) {
4677 final long origId = Binder.clearCallingIdentity();
4678 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004679 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004680 } finally {
4681 Binder.restoreCallingIdentity(origId);
4682 }
4683 }
4684 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004685
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004686 @Override
4687 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004688 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004689 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004690 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004691 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004692 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004693 }
4694 }
4695
4696 @Override
4697 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004698 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004699 != PERMISSION_GRANTED) {
4700 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4701 + Binder.getCallingPid()
4702 + ", uid=" + Binder.getCallingUid()
4703 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4704 Slog.w(TAG, msg);
4705 throw new SecurityException(msg);
4706 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004707 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004708 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004709 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004710 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004711 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 }
4713 }
4714
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004715 @Override
4716 public void stopAppSwitches() {
4717 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4718 synchronized (mGlobalLock) {
4719 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4720 mDidAppSwitch = false;
4721 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4722 }
4723 }
4724
4725 @Override
4726 public void resumeAppSwitches() {
4727 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4728 synchronized (mGlobalLock) {
4729 // Note that we don't execute any pending app switches... we will
4730 // let those wait until either the timeout, or the next start
4731 // activity request.
4732 mAppSwitchesAllowedTime = 0;
4733 }
4734 }
4735
4736 void onStartActivitySetDidAppSwitch() {
4737 if (mDidAppSwitch) {
4738 // This is the second allowed switch since we stopped switches, so now just generally
4739 // allow switches. Use case:
4740 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4741 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4742 // anyone to switch again).
4743 mAppSwitchesAllowedTime = 0;
4744 } else {
4745 mDidAppSwitch = true;
4746 }
4747 }
4748
4749 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004750 boolean shouldDisableNonVrUiLocked() {
4751 return mVrController.shouldDisableNonVrUiLocked();
4752 }
4753
Wale Ogunwale53783742018-09-16 10:21:51 -07004754 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004755 // VR apps are expected to run in a main display. If an app is turning on VR for
4756 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4757 // fullscreen stack before enabling VR Mode.
4758 // TODO: The goal of this code is to keep the VR app on the main display. When the
4759 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4760 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4761 // option would be a better choice here.
4762 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4763 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4764 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004765 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004766 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004767 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004768 }
4769 mH.post(() -> {
4770 if (!mVrController.onVrModeChanged(r)) {
4771 return;
4772 }
4773 synchronized (mGlobalLock) {
4774 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4775 mWindowManager.disableNonVrUi(disableNonVrUi);
4776 if (disableNonVrUi) {
4777 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4778 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004779 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 }
4781 }
4782 });
4783 }
4784
Wale Ogunwale53783742018-09-16 10:21:51 -07004785 @Override
4786 public int getPackageScreenCompatMode(String packageName) {
4787 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4788 synchronized (mGlobalLock) {
4789 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4790 }
4791 }
4792
4793 @Override
4794 public void setPackageScreenCompatMode(String packageName, int mode) {
4795 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4796 "setPackageScreenCompatMode");
4797 synchronized (mGlobalLock) {
4798 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4799 }
4800 }
4801
4802 @Override
4803 public boolean getPackageAskScreenCompat(String packageName) {
4804 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4805 synchronized (mGlobalLock) {
4806 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4807 }
4808 }
4809
4810 @Override
4811 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4812 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4813 "setPackageAskScreenCompat");
4814 synchronized (mGlobalLock) {
4815 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4816 }
4817 }
4818
Wale Ogunwale64258362018-10-16 15:13:37 -07004819 public static String relaunchReasonToString(int relaunchReason) {
4820 switch (relaunchReason) {
4821 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4822 return "window_resize";
4823 case RELAUNCH_REASON_FREE_RESIZE:
4824 return "free_resize";
4825 default:
4826 return null;
4827 }
4828 }
4829
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004830 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004831 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004832 }
4833
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004834 /** Pokes the task persister. */
4835 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4836 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4837 }
4838
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004839 boolean isKeyguardLocked() {
4840 return mKeyguardController.isKeyguardLocked();
4841 }
4842
Garfield Tan01548632018-11-27 10:15:48 -08004843 /**
4844 * Clears launch params for the given package.
4845 * @param packageNames the names of the packages of which the launch params are to be cleared
4846 */
4847 @Override
4848 public void clearLaunchParamsForPackages(List<String> packageNames) {
4849 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4850 "clearLaunchParamsForPackages");
4851 synchronized (mGlobalLock) {
4852 for (int i = 0; i < packageNames.size(); ++i) {
4853 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4854 }
4855 }
4856 }
4857
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004858 /**
4859 * Makes the display with the given id a single task instance display. I.e the display can only
4860 * contain one task.
4861 */
4862 @Override
4863 public void setDisplayToSingleTaskInstance(int displayId) {
4864 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4865 "setDisplayToSingleTaskInstance");
4866 final long origId = Binder.clearCallingIdentity();
4867 try {
4868 final ActivityDisplay display =
4869 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4870 if (display != null) {
4871 display.setDisplayToSingleTaskInstance();
4872 }
4873 } finally {
4874 Binder.restoreCallingIdentity(origId);
4875 }
4876 }
4877
Wale Ogunwale31913b52018-10-13 08:29:31 -07004878 void dumpLastANRLocked(PrintWriter pw) {
4879 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4880 if (mLastANRState == null) {
4881 pw.println(" <no ANR has occurred since boot>");
4882 } else {
4883 pw.println(mLastANRState);
4884 }
4885 }
4886
4887 void dumpLastANRTracesLocked(PrintWriter pw) {
4888 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4889
4890 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4891 if (ArrayUtils.isEmpty(files)) {
4892 pw.println(" <no ANR has occurred since boot>");
4893 return;
4894 }
4895 // Find the latest file.
4896 File latest = null;
4897 for (File f : files) {
4898 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4899 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004900 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004901 }
4902 pw.print("File: ");
4903 pw.print(latest.getName());
4904 pw.println();
4905 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4906 String line;
4907 while ((line = in.readLine()) != null) {
4908 pw.println(line);
4909 }
4910 } catch (IOException e) {
4911 pw.print("Unable to read: ");
4912 pw.print(e);
4913 pw.println();
4914 }
4915 }
4916
4917 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4918 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4919 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4920 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4921 }
4922
4923 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4924 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4925 pw.println(header);
4926
Wale Ogunwaled32da472018-11-16 07:19:28 -08004927 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004928 dumpPackage);
4929 boolean needSep = printedAnything;
4930
4931 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004932 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004933 " ResumedActivity: ");
4934 if (printed) {
4935 printedAnything = true;
4936 needSep = false;
4937 }
4938
4939 if (dumpPackage == null) {
4940 if (needSep) {
4941 pw.println();
4942 }
4943 printedAnything = true;
4944 mStackSupervisor.dump(pw, " ");
4945 }
4946
4947 if (!printedAnything) {
4948 pw.println(" (nothing)");
4949 }
4950 }
4951
4952 void dumpActivityContainersLocked(PrintWriter pw) {
4953 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004954 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004955 pw.println(" ");
4956 }
4957
4958 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4959 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4960 getActivityStartController().dump(pw, "", dumpPackage);
4961 }
4962
4963 /**
4964 * There are three things that cmd can be:
4965 * - a flattened component name that matches an existing activity
4966 * - the cmd arg isn't the flattened component name of an existing activity:
4967 * dump all activity whose component contains the cmd as a substring
4968 * - A hex number of the ActivityRecord object instance.
4969 *
4970 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4971 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4972 */
4973 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4974 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4975 ArrayList<ActivityRecord> activities;
4976
4977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004978 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004979 dumpFocusedStackOnly);
4980 }
4981
4982 if (activities.size() <= 0) {
4983 return false;
4984 }
4985
4986 String[] newArgs = new String[args.length - opti];
4987 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4988
4989 TaskRecord lastTask = null;
4990 boolean needSep = false;
4991 for (int i = activities.size() - 1; i >= 0; i--) {
4992 ActivityRecord r = activities.get(i);
4993 if (needSep) {
4994 pw.println();
4995 }
4996 needSep = true;
4997 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004998 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004999 if (lastTask != task) {
5000 lastTask = task;
5001 pw.print("TASK "); pw.print(lastTask.affinity);
5002 pw.print(" id="); pw.print(lastTask.taskId);
5003 pw.print(" userId="); pw.println(lastTask.userId);
5004 if (dumpAll) {
5005 lastTask.dump(pw, " ");
5006 }
5007 }
5008 }
5009 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5010 }
5011 return true;
5012 }
5013
5014 /**
5015 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5016 * there is a thread associated with the activity.
5017 */
5018 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5019 final ActivityRecord r, String[] args, boolean dumpAll) {
5020 String innerPrefix = prefix + " ";
5021 synchronized (mGlobalLock) {
5022 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5023 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5024 pw.print(" pid=");
5025 if (r.hasProcess()) pw.println(r.app.getPid());
5026 else pw.println("(not running)");
5027 if (dumpAll) {
5028 r.dump(pw, innerPrefix);
5029 }
5030 }
5031 if (r.attachedToProcess()) {
5032 // flush anything that is already in the PrintWriter since the thread is going
5033 // to write to the file descriptor directly
5034 pw.flush();
5035 try {
5036 TransferPipe tp = new TransferPipe();
5037 try {
5038 r.app.getThread().dumpActivity(tp.getWriteFd(),
5039 r.appToken, innerPrefix, args);
5040 tp.go(fd);
5041 } finally {
5042 tp.kill();
5043 }
5044 } catch (IOException e) {
5045 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5046 } catch (RemoteException e) {
5047 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5048 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005049 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005050 }
5051
sanryhuang498e77e2018-12-06 14:57:01 +08005052 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5053 boolean testPssMode) {
5054 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5055 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5056 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005057 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005058 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5059 st.toString());
5060 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005061 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5062 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5063 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005064 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5065 testPssMode);
5066 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005067 }
5068
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005069 int getCurrentUserId() {
5070 return mAmInternal.getCurrentUserId();
5071 }
5072
5073 private void enforceNotIsolatedCaller(String caller) {
5074 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5075 throw new SecurityException("Isolated process not allowed to call " + caller);
5076 }
5077 }
5078
Wale Ogunwalef6733932018-06-27 05:14:34 -07005079 public Configuration getConfiguration() {
5080 Configuration ci;
5081 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005082 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005083 ci.userSetLocale = false;
5084 }
5085 return ci;
5086 }
5087
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005088 /**
5089 * Current global configuration information. Contains general settings for the entire system,
5090 * also corresponds to the merged configuration of the default display.
5091 */
5092 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005093 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005094 }
5095
5096 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5097 boolean initLocale) {
5098 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5099 }
5100
5101 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5102 boolean initLocale, boolean deferResume) {
5103 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5104 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5105 UserHandle.USER_NULL, deferResume);
5106 }
5107
Wale Ogunwale59507092018-10-29 09:00:30 -07005108 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005109 final long origId = Binder.clearCallingIdentity();
5110 try {
5111 synchronized (mGlobalLock) {
5112 updateConfigurationLocked(values, null, false, true, userId,
5113 false /* deferResume */);
5114 }
5115 } finally {
5116 Binder.restoreCallingIdentity(origId);
5117 }
5118 }
5119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005120 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5121 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5122 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5123 deferResume, null /* result */);
5124 }
5125
5126 /**
5127 * Do either or both things: (1) change the current configuration, and (2)
5128 * make sure the given activity is running with the (now) current
5129 * configuration. Returns true if the activity has been left running, or
5130 * false if <var>starting</var> is being destroyed to match the new
5131 * configuration.
5132 *
5133 * @param userId is only used when persistent parameter is set to true to persist configuration
5134 * for that particular user
5135 */
5136 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5137 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5138 ActivityTaskManagerService.UpdateConfigurationResult result) {
5139 int changes = 0;
5140 boolean kept = true;
5141
5142 if (mWindowManager != null) {
5143 mWindowManager.deferSurfaceLayout();
5144 }
5145 try {
5146 if (values != null) {
5147 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5148 deferResume);
5149 }
5150
5151 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5152 } finally {
5153 if (mWindowManager != null) {
5154 mWindowManager.continueSurfaceLayout();
5155 }
5156 }
5157
5158 if (result != null) {
5159 result.changes = changes;
5160 result.activityRelaunched = !kept;
5161 }
5162 return kept;
5163 }
5164
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005165 /** Update default (global) configuration and notify listeners about changes. */
5166 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5167 boolean persistent, int userId, boolean deferResume) {
5168 mTempConfig.setTo(getGlobalConfiguration());
5169 final int changes = mTempConfig.updateFrom(values);
5170 if (changes == 0) {
5171 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5172 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5173 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5174 // (even if there are no actual changes) to unfreeze the window.
5175 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5176 return 0;
5177 }
5178
5179 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5180 "Updating global configuration to: " + values);
5181
5182 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5183 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5184 values.colorMode,
5185 values.densityDpi,
5186 values.fontScale,
5187 values.hardKeyboardHidden,
5188 values.keyboard,
5189 values.keyboardHidden,
5190 values.mcc,
5191 values.mnc,
5192 values.navigation,
5193 values.navigationHidden,
5194 values.orientation,
5195 values.screenHeightDp,
5196 values.screenLayout,
5197 values.screenWidthDp,
5198 values.smallestScreenWidthDp,
5199 values.touchscreen,
5200 values.uiMode);
5201
5202
5203 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5204 final LocaleList locales = values.getLocales();
5205 int bestLocaleIndex = 0;
5206 if (locales.size() > 1) {
5207 if (mSupportedSystemLocales == null) {
5208 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5209 }
5210 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5211 }
5212 SystemProperties.set("persist.sys.locale",
5213 locales.get(bestLocaleIndex).toLanguageTag());
5214 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005215
5216 final Message m = PooledLambda.obtainMessage(
5217 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5218 locales.get(bestLocaleIndex));
5219 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
Yunfan Chen75157d72018-07-27 14:47:21 +09005222 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223
5224 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005225 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226
5227 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5228 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005229 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230
5231 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005232 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233
5234 AttributeCache ac = AttributeCache.instance();
5235 if (ac != null) {
5236 ac.updateConfiguration(mTempConfig);
5237 }
5238
5239 // Make sure all resources in our process are updated right now, so that anyone who is going
5240 // to retrieve resource values after we return will be sure to get the new ones. This is
5241 // especially important during boot, where the first config change needs to guarantee all
5242 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005243 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005244
5245 // We need another copy of global config because we're scheduling some calls instead of
5246 // running them in place. We need to be sure that object we send will be handled unchanged.
5247 final Configuration configCopy = new Configuration(mTempConfig);
5248 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005249 final Message msg = PooledLambda.obtainMessage(
5250 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5251 this, userId, configCopy);
5252 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 }
5254
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005255 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5256 for (int i = pidMap.size() - 1; i >= 0; i--) {
5257 final int pid = pidMap.keyAt(i);
5258 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005259 if (DEBUG_CONFIGURATION) {
5260 Slog.v(TAG_CONFIGURATION, "Update process config of "
5261 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005263 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005264 }
5265
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005266 final Message msg = PooledLambda.obtainMessage(
5267 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5268 mAmInternal, changes, initLocale);
5269 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005270
5271 // Override configuration of the default display duplicates global config, so we need to
5272 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005273 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274 DEFAULT_DISPLAY);
5275
5276 return changes;
5277 }
5278
5279 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5280 boolean deferResume, int displayId) {
5281 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5282 displayId, null /* result */);
5283 }
5284
5285 /**
5286 * Updates override configuration specific for the selected display. If no config is provided,
5287 * new one will be computed in WM based on current display info.
5288 */
5289 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5290 ActivityRecord starting, boolean deferResume, int displayId,
5291 ActivityTaskManagerService.UpdateConfigurationResult result) {
5292 int changes = 0;
5293 boolean kept = true;
5294
5295 if (mWindowManager != null) {
5296 mWindowManager.deferSurfaceLayout();
5297 }
5298 try {
5299 if (values != null) {
5300 if (displayId == DEFAULT_DISPLAY) {
5301 // Override configuration of the default display duplicates global config, so
5302 // we're calling global config update instead for default display. It will also
5303 // apply the correct override config.
5304 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5305 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5306 } else {
5307 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5308 }
5309 }
5310
5311 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5312 } finally {
5313 if (mWindowManager != null) {
5314 mWindowManager.continueSurfaceLayout();
5315 }
5316 }
5317
5318 if (result != null) {
5319 result.changes = changes;
5320 result.activityRelaunched = !kept;
5321 }
5322 return kept;
5323 }
5324
5325 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5326 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005327 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005328 final int changes = mTempConfig.updateFrom(values);
5329 if (changes != 0) {
5330 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5331 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005332 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333
5334 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5335 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005336 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005337
Wale Ogunwale5c918702018-10-18 11:06:33 -07005338 // Post message to start process to avoid possible deadlock of calling into AMS with
5339 // the ATMS lock held.
5340 final Message msg = PooledLambda.obtainMessage(
5341 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005342 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005343 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344 }
5345 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005346 return changes;
5347 }
5348
Wale Ogunwalef6733932018-06-27 05:14:34 -07005349 private void updateEventDispatchingLocked(boolean booted) {
5350 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5351 }
5352
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005353 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5354 final ContentResolver resolver = mContext.getContentResolver();
5355 Settings.System.putConfigurationForUser(resolver, config, userId);
5356 }
5357
5358 private void sendLocaleToMountDaemonMsg(Locale l) {
5359 try {
5360 IBinder service = ServiceManager.getService("mount");
5361 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5362 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5363 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5364 } catch (RemoteException e) {
5365 Log.e(TAG, "Error storing locale for decryption UI", e);
5366 }
5367 }
5368
Alison Cichowlas3e340502018-08-07 17:15:01 -04005369 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5370 mStartActivitySources.remove(permissionToken);
5371 mExpiredStartAsCallerTokens.add(permissionToken);
5372 }
5373
5374 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5375 mExpiredStartAsCallerTokens.remove(permissionToken);
5376 }
5377
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005378 boolean isActivityStartsLoggingEnabled() {
5379 return mAmInternal.isActivityStartsLoggingEnabled();
5380 }
5381
Michal Karpinski8596ded2018-11-14 14:43:48 +00005382 boolean isBackgroundActivityStartsEnabled() {
5383 return mAmInternal.isBackgroundActivityStartsEnabled();
5384 }
5385
Ricky Waiaca8a772019-04-04 16:01:06 +01005386 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5387 if (packageName == null) {
5388 return false;
5389 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005390 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5391 }
5392
Wale Ogunwalef6733932018-06-27 05:14:34 -07005393 void enableScreenAfterBoot(boolean booted) {
5394 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5395 SystemClock.uptimeMillis());
5396 mWindowManager.enableScreenAfterBoot();
5397
5398 synchronized (mGlobalLock) {
5399 updateEventDispatchingLocked(booted);
5400 }
5401 }
5402
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005403 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5404 if (r == null || !r.hasProcess()) {
5405 return KEY_DISPATCHING_TIMEOUT_MS;
5406 }
5407 return getInputDispatchingTimeoutLocked(r.app);
5408 }
5409
5410 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005411 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005412 }
5413
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 /**
5415 * Decide based on the configuration whether we should show the ANR,
5416 * crash, etc dialogs. The idea is that if there is no affordance to
5417 * press the on-screen buttons, or the user experience would be more
5418 * greatly impacted than the crash itself, we shouldn't show the dialog.
5419 *
5420 * A thought: SystemUI might also want to get told about this, the Power
5421 * dialog / global actions also might want different behaviors.
5422 */
5423 private void updateShouldShowDialogsLocked(Configuration config) {
5424 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5425 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5426 && config.navigation == Configuration.NAVIGATION_NONAV);
5427 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5428 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5429 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5430 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5431 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5432 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5433 HIDE_ERROR_DIALOGS, 0) != 0;
5434 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5435 }
5436
5437 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5438 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5439 FONT_SCALE, 1.0f, userId);
5440
5441 synchronized (this) {
5442 if (getGlobalConfiguration().fontScale == scaleFactor) {
5443 return;
5444 }
5445
5446 final Configuration configuration
5447 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5448 configuration.fontScale = scaleFactor;
5449 updatePersistentConfiguration(configuration, userId);
5450 }
5451 }
5452
5453 // Actually is sleeping or shutting down or whatever else in the future
5454 // is an inactive state.
5455 boolean isSleepingOrShuttingDownLocked() {
5456 return isSleepingLocked() || mShuttingDown;
5457 }
5458
5459 boolean isSleepingLocked() {
5460 return mSleeping;
5461 }
5462
Riddle Hsu16567132018-08-16 21:37:47 +08005463 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005464 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005465 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 if (task.isActivityTypeStandard()) {
5467 if (mCurAppTimeTracker != r.appTimeTracker) {
5468 // We are switching app tracking. Complete the current one.
5469 if (mCurAppTimeTracker != null) {
5470 mCurAppTimeTracker.stop();
5471 mH.obtainMessage(
5472 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005473 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005474 mCurAppTimeTracker = null;
5475 }
5476 if (r.appTimeTracker != null) {
5477 mCurAppTimeTracker = r.appTimeTracker;
5478 startTimeTrackingFocusedActivityLocked();
5479 }
5480 } else {
5481 startTimeTrackingFocusedActivityLocked();
5482 }
5483 } else {
5484 r.appTimeTracker = null;
5485 }
5486 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5487 // TODO: Probably not, because we don't want to resume voice on switching
5488 // back to this activity
5489 if (task.voiceInteractor != null) {
5490 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5491 } else {
5492 finishRunningVoiceLocked();
5493
5494 if (mLastResumedActivity != null) {
5495 final IVoiceInteractionSession session;
5496
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005497 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005498 if (lastResumedActivityTask != null
5499 && lastResumedActivityTask.voiceSession != null) {
5500 session = lastResumedActivityTask.voiceSession;
5501 } else {
5502 session = mLastResumedActivity.voiceSession;
5503 }
5504
5505 if (session != null) {
5506 // We had been in a voice interaction session, but now focused has
5507 // move to something different. Just finish the session, we can't
5508 // return to it and retain the proper state and synchronization with
5509 // the voice interaction service.
5510 finishVoiceTask(session);
5511 }
5512 }
5513 }
5514
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005515 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5516 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 }
5518 updateResumedAppTrace(r);
5519 mLastResumedActivity = r;
5520
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005521 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522
5523 applyUpdateLockStateLocked(r);
5524 applyUpdateVrModeLocked(r);
5525
5526 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005527 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528 r == null ? "NULL" : r.shortComponentName,
5529 reason);
5530 }
5531
5532 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5533 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005534 final ActivityTaskManagerInternal.SleepToken token =
5535 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536 updateSleepIfNeededLocked();
5537 return token;
5538 }
5539 }
5540
5541 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005542 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543 final boolean wasSleeping = mSleeping;
5544 boolean updateOomAdj = false;
5545
5546 if (!shouldSleep) {
5547 // If wasSleeping is true, we need to wake up activity manager state from when
5548 // we started sleeping. In either case, we need to apply the sleep tokens, which
5549 // will wake up stacks or put them to sleep as appropriate.
5550 if (wasSleeping) {
5551 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005552 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5553 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554 startTimeTrackingFocusedActivityLocked();
5555 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005556 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5558 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005559 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005560 if (wasSleeping) {
5561 updateOomAdj = true;
5562 }
5563 } else if (!mSleeping && shouldSleep) {
5564 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005565 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5566 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005567 if (mCurAppTimeTracker != null) {
5568 mCurAppTimeTracker.stop();
5569 }
5570 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005571 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 mStackSupervisor.goingToSleepLocked();
5573 updateResumedAppTrace(null /* resumed */);
5574 updateOomAdj = true;
5575 }
5576 if (updateOomAdj) {
5577 mH.post(mAmInternal::updateOomAdj);
5578 }
5579 }
5580
5581 void updateOomAdj() {
5582 mH.post(mAmInternal::updateOomAdj);
5583 }
5584
Wale Ogunwale53783742018-09-16 10:21:51 -07005585 void updateCpuStats() {
5586 mH.post(mAmInternal::updateCpuStats);
5587 }
5588
Hui Yu03d12402018-12-06 18:00:37 -08005589 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5590 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005591 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5592 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005593 mH.sendMessage(m);
5594 }
5595
Hui Yu03d12402018-12-06 18:00:37 -08005596 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005597 ComponentName taskRoot = null;
5598 final TaskRecord task = activity.getTaskRecord();
5599 if (task != null) {
5600 final ActivityRecord rootActivity = task.getRootActivity();
5601 if (rootActivity != null) {
5602 taskRoot = rootActivity.mActivityComponent;
5603 }
5604 }
5605
Hui Yu03d12402018-12-06 18:00:37 -08005606 final Message m = PooledLambda.obtainMessage(
5607 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005608 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005609 mH.sendMessage(m);
5610 }
5611
Wale Ogunwale53783742018-09-16 10:21:51 -07005612 void setBooting(boolean booting) {
5613 mAmInternal.setBooting(booting);
5614 }
5615
5616 boolean isBooting() {
5617 return mAmInternal.isBooting();
5618 }
5619
5620 void setBooted(boolean booted) {
5621 mAmInternal.setBooted(booted);
5622 }
5623
5624 boolean isBooted() {
5625 return mAmInternal.isBooted();
5626 }
5627
5628 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5629 mH.post(() -> {
5630 if (finishBooting) {
5631 mAmInternal.finishBooting();
5632 }
5633 if (enableScreen) {
5634 mInternal.enableScreenAfterBoot(isBooted());
5635 }
5636 });
5637 }
5638
5639 void setHeavyWeightProcess(ActivityRecord root) {
5640 mHeavyWeightProcess = root.app;
5641 final Message m = PooledLambda.obtainMessage(
5642 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005643 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005644 mH.sendMessage(m);
5645 }
5646
5647 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5648 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5649 return;
5650 }
5651
5652 mHeavyWeightProcess = null;
5653 final Message m = PooledLambda.obtainMessage(
5654 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5655 proc.mUserId);
5656 mH.sendMessage(m);
5657 }
5658
5659 private void cancelHeavyWeightProcessNotification(int userId) {
5660 final INotificationManager inm = NotificationManager.getService();
5661 if (inm == null) {
5662 return;
5663 }
5664 try {
5665 inm.cancelNotificationWithTag("android", null,
5666 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5667 } catch (RuntimeException e) {
5668 Slog.w(TAG, "Error canceling notification for service", e);
5669 } catch (RemoteException e) {
5670 }
5671
5672 }
5673
5674 private void postHeavyWeightProcessNotification(
5675 WindowProcessController proc, Intent intent, int userId) {
5676 if (proc == null) {
5677 return;
5678 }
5679
5680 final INotificationManager inm = NotificationManager.getService();
5681 if (inm == null) {
5682 return;
5683 }
5684
5685 try {
5686 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5687 String text = mContext.getString(R.string.heavy_weight_notification,
5688 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5689 Notification notification =
5690 new Notification.Builder(context,
5691 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5692 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5693 .setWhen(0)
5694 .setOngoing(true)
5695 .setTicker(text)
5696 .setColor(mContext.getColor(
5697 com.android.internal.R.color.system_notification_accent_color))
5698 .setContentTitle(text)
5699 .setContentText(
5700 mContext.getText(R.string.heavy_weight_notification_detail))
5701 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5702 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5703 new UserHandle(userId)))
5704 .build();
5705 try {
5706 inm.enqueueNotificationWithTag("android", "android", null,
5707 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5708 } catch (RuntimeException e) {
5709 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5710 } catch (RemoteException e) {
5711 }
5712 } catch (PackageManager.NameNotFoundException e) {
5713 Slog.w(TAG, "Unable to create context for heavy notification", e);
5714 }
5715
5716 }
5717
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005718 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5719 IBinder token, String resultWho, int requestCode, Intent[] intents,
5720 String[] resolvedTypes, int flags, Bundle bOptions) {
5721
5722 ActivityRecord activity = null;
5723 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5724 activity = ActivityRecord.isInStackLocked(token);
5725 if (activity == null) {
5726 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5727 return null;
5728 }
5729 if (activity.finishing) {
5730 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5731 return null;
5732 }
5733 }
5734
5735 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5736 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5737 bOptions);
5738 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5739 if (noCreate) {
5740 return rec;
5741 }
5742 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5743 if (activity.pendingResults == null) {
5744 activity.pendingResults = new HashSet<>();
5745 }
5746 activity.pendingResults.add(rec.ref);
5747 }
5748 return rec;
5749 }
5750
Andrii Kulian52d255c2018-07-13 11:32:19 -07005751 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005752 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005753 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005754 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5755 mCurAppTimeTracker.start(resumedActivity.packageName);
5756 }
5757 }
5758
5759 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5760 if (mTracedResumedActivity != null) {
5761 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5762 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5763 }
5764 if (resumed != null) {
5765 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5766 constructResumedTraceName(resumed.packageName), 0);
5767 }
5768 mTracedResumedActivity = resumed;
5769 }
5770
5771 private String constructResumedTraceName(String packageName) {
5772 return "focused app: " + packageName;
5773 }
5774
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005775 /** Applies latest configuration and/or visibility updates if needed. */
5776 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5777 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005778 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005779 // mainStack is null during startup.
5780 if (mainStack != null) {
5781 if (changes != 0 && starting == null) {
5782 // If the configuration changed, and the caller is not already
5783 // in the process of starting an activity, then find the top
5784 // activity to check if its configuration needs to change.
5785 starting = mainStack.topRunningActivityLocked();
5786 }
5787
5788 if (starting != null) {
5789 kept = starting.ensureActivityConfiguration(changes,
5790 false /* preserveWindow */);
5791 // And we need to make sure at this point that all other activities
5792 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005793 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005794 !PRESERVE_WINDOWS);
5795 }
5796 }
5797
5798 return kept;
5799 }
5800
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005801 void scheduleAppGcsLocked() {
5802 mH.post(() -> mAmInternal.scheduleAppGcs());
5803 }
5804
Wale Ogunwale53783742018-09-16 10:21:51 -07005805 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5806 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5807 }
5808
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005809 /**
5810 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5811 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5812 * on demand.
5813 */
5814 IPackageManager getPackageManager() {
5815 return AppGlobals.getPackageManager();
5816 }
5817
5818 PackageManagerInternal getPackageManagerInternalLocked() {
5819 if (mPmInternal == null) {
5820 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5821 }
5822 return mPmInternal;
5823 }
5824
Wale Ogunwale008163e2018-07-23 23:11:08 -07005825 AppWarnings getAppWarningsLocked() {
5826 return mAppWarnings;
5827 }
5828
Wale Ogunwale214f3482018-10-04 11:00:47 -07005829 Intent getHomeIntent() {
5830 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5831 intent.setComponent(mTopComponent);
5832 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5833 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5834 intent.addCategory(Intent.CATEGORY_HOME);
5835 }
5836 return intent;
5837 }
5838
Chilun2ef71f72018-11-16 17:57:15 +08005839 /**
5840 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5841 * activities.
5842 *
5843 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5844 * component defined in config_secondaryHomeComponent.
5845 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5846 */
5847 Intent getSecondaryHomeIntent(String preferredPackage) {
5848 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005849 if (preferredPackage == null) {
5850 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005851 final String secondaryHomeComponent = mContext.getResources().getString(
5852 com.android.internal.R.string.config_secondaryHomeComponent);
5853 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5854 } else {
5855 intent.setPackage(preferredPackage);
5856 }
5857 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5858 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5859 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5860 }
5861 return intent;
5862 }
5863
Wale Ogunwale214f3482018-10-04 11:00:47 -07005864 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5865 if (info == null) return null;
5866 ApplicationInfo newInfo = new ApplicationInfo(info);
5867 newInfo.initForUser(userId);
5868 return newInfo;
5869 }
5870
Wale Ogunwale9c103022018-10-18 07:44:54 -07005871 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005872 if (uid == SYSTEM_UID) {
5873 // The system gets to run in any process. If there are multiple processes with the same
5874 // uid, just pick the first (this should never happen).
5875 final SparseArray<WindowProcessController> procs =
5876 mProcessNames.getMap().get(processName);
5877 if (procs == null) return null;
5878 final int procCount = procs.size();
5879 for (int i = 0; i < procCount; i++) {
5880 final int procUid = procs.keyAt(i);
5881 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5882 // Don't use an app process or different user process for system component.
5883 continue;
5884 }
5885 return procs.valueAt(i);
5886 }
5887 }
5888
5889 return mProcessNames.get(processName, uid);
5890 }
5891
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005892 WindowProcessController getProcessController(IApplicationThread thread) {
5893 if (thread == null) {
5894 return null;
5895 }
5896
5897 final IBinder threadBinder = thread.asBinder();
5898 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5899 for (int i = pmap.size()-1; i >= 0; i--) {
5900 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5901 for (int j = procs.size() - 1; j >= 0; j--) {
5902 final WindowProcessController proc = procs.valueAt(j);
5903 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5904 return proc;
5905 }
5906 }
5907 }
5908
5909 return null;
5910 }
5911
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005912 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005913 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005914 if (proc == null) return null;
5915 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5916 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005917 }
5918 return null;
5919 }
5920
Riddle Hsua0536432019-02-16 00:38:59 +08005921 int getUidState(int uid) {
5922 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005923 }
5924
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005925 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005926 // A uid is considered to be foreground if it has a visible non-toast window.
5927 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005928 }
5929
Ricky Wai96f5c352019-04-10 18:40:17 +01005930 boolean isDeviceOwner(int uid) {
5931 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005932 }
5933
Ricky Wai96f5c352019-04-10 18:40:17 +01005934 void setDeviceOwnerUid(int uid) {
5935 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005936 }
5937
Wale Ogunwale9de19442018-10-18 19:05:03 -07005938 /**
5939 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5940 * the whitelist
5941 */
5942 String getPendingTempWhitelistTagForUidLocked(int uid) {
5943 return mPendingTempWhitelist.get(uid);
5944 }
5945
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005946 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5947 if (true || Build.IS_USER) {
5948 return;
5949 }
5950
5951 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5952 StrictMode.allowThreadDiskWrites();
5953 try {
5954 File tracesDir = new File("/data/anr");
5955 File tracesFile = null;
5956 try {
5957 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5958
5959 StringBuilder sb = new StringBuilder();
5960 Time tobj = new Time();
5961 tobj.set(System.currentTimeMillis());
5962 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5963 sb.append(": ");
5964 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5965 sb.append(" since ");
5966 sb.append(msg);
5967 FileOutputStream fos = new FileOutputStream(tracesFile);
5968 fos.write(sb.toString().getBytes());
5969 if (app == null) {
5970 fos.write("\n*** No application process!".getBytes());
5971 }
5972 fos.close();
5973 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5974 } catch (IOException e) {
5975 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5976 return;
5977 }
5978
5979 if (app != null && app.getPid() > 0) {
5980 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5981 firstPids.add(app.getPid());
5982 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5983 }
5984
5985 File lastTracesFile = null;
5986 File curTracesFile = null;
5987 for (int i=9; i>=0; i--) {
5988 String name = String.format(Locale.US, "slow%02d.txt", i);
5989 curTracesFile = new File(tracesDir, name);
5990 if (curTracesFile.exists()) {
5991 if (lastTracesFile != null) {
5992 curTracesFile.renameTo(lastTracesFile);
5993 } else {
5994 curTracesFile.delete();
5995 }
5996 }
5997 lastTracesFile = curTracesFile;
5998 }
5999 tracesFile.renameTo(curTracesFile);
6000 } finally {
6001 StrictMode.setThreadPolicy(oldPolicy);
6002 }
6003 }
6004
Michal Karpinskida34cd42019-04-02 19:46:52 +01006005 boolean isAssociatedCompanionApp(int userId, int uid) {
6006 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6007 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006008 return false;
6009 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006010 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006011 }
6012
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006013 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006014 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006015
6016
Wale Ogunwale98875612018-10-12 07:53:02 -07006017 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6018 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006019
Riddle Hsud93a6c42018-11-29 21:50:06 +08006020 H(Looper looper) {
6021 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006022 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006023
6024 @Override
6025 public void handleMessage(Message msg) {
6026 switch (msg.what) {
6027 case REPORT_TIME_TRACKER_MSG: {
6028 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6029 tracker.deliverResult(mContext);
6030 } break;
6031 }
6032 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006033 }
6034
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006035 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006036 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006037
6038 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006039 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006040 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006041
6042 @Override
6043 public void handleMessage(Message msg) {
6044 switch (msg.what) {
6045 case DISMISS_DIALOG_UI_MSG: {
6046 final Dialog d = (Dialog) msg.obj;
6047 d.dismiss();
6048 break;
6049 }
6050 }
6051 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006052 }
6053
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006054 final class LocalService extends ActivityTaskManagerInternal {
6055 @Override
6056 public SleepToken acquireSleepToken(String tag, int displayId) {
6057 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006058 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060
6061 @Override
6062 public ComponentName getHomeActivityForUser(int userId) {
6063 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006064 final ActivityRecord homeActivity =
6065 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006066 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006067 }
6068 }
6069
6070 @Override
6071 public void onLocalVoiceInteractionStarted(IBinder activity,
6072 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6073 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006074 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006075 }
6076 }
6077
6078 @Override
6079 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6080 synchronized (mGlobalLock) {
6081 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6082 reasons, timestamp);
6083 }
6084 }
6085
6086 @Override
6087 public void notifyAppTransitionFinished() {
6088 synchronized (mGlobalLock) {
6089 mStackSupervisor.notifyAppTransitionDone();
6090 }
6091 }
6092
6093 @Override
6094 public void notifyAppTransitionCancelled() {
6095 synchronized (mGlobalLock) {
6096 mStackSupervisor.notifyAppTransitionDone();
6097 }
6098 }
6099
6100 @Override
6101 public List<IBinder> getTopVisibleActivities() {
6102 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006103 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104 }
6105 }
6106
6107 @Override
6108 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6109 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006110 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006111 }
6112 }
6113
6114 @Override
6115 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6116 Bundle bOptions) {
6117 Preconditions.checkNotNull(intents, "intents");
6118 final String[] resolvedTypes = new String[intents.length];
6119
6120 // UID of the package on user userId.
6121 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6122 // packageUid may not be initialized.
6123 int packageUid = 0;
6124 final long ident = Binder.clearCallingIdentity();
6125
6126 try {
6127 for (int i = 0; i < intents.length; i++) {
6128 resolvedTypes[i] =
6129 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6130 }
6131
6132 packageUid = AppGlobals.getPackageManager().getPackageUid(
6133 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6134 } catch (RemoteException e) {
6135 // Shouldn't happen.
6136 } finally {
6137 Binder.restoreCallingIdentity(ident);
6138 }
6139
Riddle Hsu591bf612019-02-14 17:55:31 +08006140 return getActivityStartController().startActivitiesInPackage(
6141 packageUid, packageName,
6142 intents, resolvedTypes, null /* resultTo */,
6143 SafeActivityOptions.fromBundle(bOptions), userId,
6144 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6145 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 }
6147
6148 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006149 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6150 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6151 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6152 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006153 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006154 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006155 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6156 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6157 userId, validateIncomingUser, originatingPendingIntent,
6158 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006159 }
6160 }
6161
6162 @Override
6163 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6164 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6165 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6166 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006167 PendingIntentRecord originatingPendingIntent,
6168 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006169 synchronized (mGlobalLock) {
6170 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6171 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6172 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006173 validateIncomingUser, originatingPendingIntent,
6174 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006175 }
6176 }
6177
6178 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6180 Intent intent, Bundle options, int userId) {
6181 return ActivityTaskManagerService.this.startActivityAsUser(
6182 caller, callerPacakge, intent,
6183 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6184 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6185 false /*validateIncomingUser*/);
6186 }
6187
6188 @Override
lumark588a3e82018-07-20 18:53:54 +08006189 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 synchronized (mGlobalLock) {
6191
6192 // We might change the visibilities here, so prepare an empty app transition which
6193 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006194 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006195 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006196 if (activityDisplay == null) {
6197 return;
6198 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006199 final DisplayContent dc = activityDisplay.mDisplayContent;
6200 final boolean wasTransitionSet =
6201 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006202 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006203 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006205 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206
6207 // If there was a transition set already we don't want to interfere with it as we
6208 // might be starting it too early.
6209 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006210 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 }
6212 }
6213 if (callback != null) {
6214 callback.run();
6215 }
6216 }
6217
6218 @Override
6219 public void notifyKeyguardTrustedChanged() {
6220 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006221 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006222 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 }
6224 }
6225 }
6226
6227 /**
6228 * Called after virtual display Id is updated by
6229 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6230 * {@param vrVr2dDisplayId}.
6231 */
6232 @Override
6233 public void setVr2dDisplayId(int vr2dDisplayId) {
6234 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6235 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006236 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006237 }
6238 }
6239
6240 @Override
6241 public void setFocusedActivity(IBinder token) {
6242 synchronized (mGlobalLock) {
6243 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6244 if (r == null) {
6245 throw new IllegalArgumentException(
6246 "setFocusedActivity: No activity record matching token=" + token);
6247 }
Louis Chang19443452018-10-09 12:10:21 +08006248 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006249 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 }
6251 }
6252 }
6253
6254 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006256 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006257 }
6258
6259 @Override
6260 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006261 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 }
6263
6264 @Override
6265 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006266 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 }
6268
6269 @Override
6270 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6271 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6272 }
6273
6274 @Override
6275 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006276 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006277 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006278
6279 @Override
6280 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6281 synchronized (mGlobalLock) {
6282 mActiveVoiceInteractionServiceComponent = component;
6283 }
6284 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006285
6286 @Override
6287 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6288 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6289 return;
6290 }
6291 synchronized (mGlobalLock) {
6292 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6293 if (types == null) {
6294 if (uid < 0) {
6295 return;
6296 }
6297 types = new ArrayMap<>();
6298 mAllowAppSwitchUids.put(userId, types);
6299 }
6300 if (uid < 0) {
6301 types.remove(type);
6302 } else {
6303 types.put(type, uid);
6304 }
6305 }
6306 }
6307
6308 @Override
6309 public void onUserStopped(int userId) {
6310 synchronized (mGlobalLock) {
6311 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6312 mAllowAppSwitchUids.remove(userId);
6313 }
6314 }
6315
6316 @Override
6317 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6318 synchronized (mGlobalLock) {
6319 return ActivityTaskManagerService.this.isGetTasksAllowed(
6320 caller, callingPid, callingUid);
6321 }
6322 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006323
Riddle Hsua0536432019-02-16 00:38:59 +08006324 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006325 @Override
6326 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006327 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006328 mProcessNames.put(proc.mName, proc.mUid, proc);
6329 }
6330 }
6331
Riddle Hsua0536432019-02-16 00:38:59 +08006332 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006333 @Override
6334 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006335 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006336 mProcessNames.remove(name, uid);
6337 }
6338 }
6339
Riddle Hsua0536432019-02-16 00:38:59 +08006340 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006341 @Override
6342 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006343 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006344 if (proc == mHomeProcess) {
6345 mHomeProcess = null;
6346 }
6347 if (proc == mPreviousProcess) {
6348 mPreviousProcess = null;
6349 }
6350 }
6351 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006352
Riddle Hsua0536432019-02-16 00:38:59 +08006353 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006354 @Override
6355 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006356 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006357 return mTopProcessState;
6358 }
6359 }
6360
Riddle Hsua0536432019-02-16 00:38:59 +08006361 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006362 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006363 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006364 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006365 return proc == mHeavyWeightProcess;
6366 }
6367 }
6368
Riddle Hsua0536432019-02-16 00:38:59 +08006369 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006370 @Override
6371 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006372 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006373 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6374 }
6375 }
6376
6377 @Override
6378 public void finishHeavyWeightApp() {
6379 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006380 if (mHeavyWeightProcess != null) {
6381 mHeavyWeightProcess.finishActivities();
6382 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006383 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6384 mHeavyWeightProcess);
6385 }
6386 }
6387
Riddle Hsua0536432019-02-16 00:38:59 +08006388 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006389 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006390 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006391 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006392 return isSleepingLocked();
6393 }
6394 }
6395
6396 @Override
6397 public boolean isShuttingDown() {
6398 synchronized (mGlobalLock) {
6399 return mShuttingDown;
6400 }
6401 }
6402
6403 @Override
6404 public boolean shuttingDown(boolean booted, int timeout) {
6405 synchronized (mGlobalLock) {
6406 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006407 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006408 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006409 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006410 return mStackSupervisor.shutdownLocked(timeout);
6411 }
6412 }
6413
6414 @Override
6415 public void enableScreenAfterBoot(boolean booted) {
6416 synchronized (mGlobalLock) {
6417 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6418 SystemClock.uptimeMillis());
6419 mWindowManager.enableScreenAfterBoot();
6420 updateEventDispatchingLocked(booted);
6421 }
6422 }
6423
6424 @Override
6425 public boolean showStrictModeViolationDialog() {
6426 synchronized (mGlobalLock) {
6427 return mShowDialogs && !mSleeping && !mShuttingDown;
6428 }
6429 }
6430
6431 @Override
6432 public void showSystemReadyErrorDialogsIfNeeded() {
6433 synchronized (mGlobalLock) {
6434 try {
6435 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6436 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6437 + " data partition or your device will be unstable.");
6438 mUiHandler.post(() -> {
6439 if (mShowDialogs) {
6440 AlertDialog d = new BaseErrorDialog(mUiContext);
6441 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6442 d.setCancelable(false);
6443 d.setTitle(mUiContext.getText(R.string.android_system_label));
6444 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6445 d.setButton(DialogInterface.BUTTON_POSITIVE,
6446 mUiContext.getText(R.string.ok),
6447 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6448 d.show();
6449 }
6450 });
6451 }
6452 } catch (RemoteException e) {
6453 }
6454
6455 if (!Build.isBuildConsistent()) {
6456 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6457 mUiHandler.post(() -> {
6458 if (mShowDialogs) {
6459 AlertDialog d = new BaseErrorDialog(mUiContext);
6460 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6461 d.setCancelable(false);
6462 d.setTitle(mUiContext.getText(R.string.android_system_label));
6463 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6464 d.setButton(DialogInterface.BUTTON_POSITIVE,
6465 mUiContext.getText(R.string.ok),
6466 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6467 d.show();
6468 }
6469 });
6470 }
6471 }
6472 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006473
6474 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006475 public void onProcessMapped(int pid, WindowProcessController proc) {
6476 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006477 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006478 }
6479 }
6480
6481 @Override
6482 public void onProcessUnMapped(int pid) {
6483 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006484 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006485 }
6486 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006487
6488 @Override
6489 public void onPackageDataCleared(String name) {
6490 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006491 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006492 mAppWarnings.onPackageDataCleared(name);
6493 }
6494 }
6495
6496 @Override
6497 public void onPackageUninstalled(String name) {
6498 synchronized (mGlobalLock) {
6499 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006500 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006501 }
6502 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006503
6504 @Override
6505 public void onPackageAdded(String name, boolean replacing) {
6506 synchronized (mGlobalLock) {
6507 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6508 }
6509 }
6510
6511 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006512 public void onPackageReplaced(ApplicationInfo aInfo) {
6513 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006514 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006515 }
6516 }
6517
6518 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006519 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6520 synchronized (mGlobalLock) {
6521 return compatibilityInfoForPackageLocked(ai);
6522 }
6523 }
6524
Yunfan Chen75157d72018-07-27 14:47:21 +09006525 /**
6526 * Set the corresponding display information for the process global configuration. To be
6527 * called when we need to show IME on a different display.
6528 *
6529 * @param pid The process id associated with the IME window.
6530 * @param displayId The ID of the display showing the IME.
6531 */
6532 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006533 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006534 // Don't update process-level configuration for Multi-Client IME process since other
6535 // IMEs on other displays will also receive this configuration change due to IME
6536 // services use the same application config/context.
6537 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006538
Yunfan Chen75157d72018-07-27 14:47:21 +09006539 if (pid == MY_PID || pid < 0) {
6540 if (DEBUG_CONFIGURATION) {
6541 Slog.w(TAG,
6542 "Trying to update display configuration for system/invalid process.");
6543 }
6544 return;
6545 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006546 synchronized (mGlobalLock) {
6547 final ActivityDisplay activityDisplay =
6548 mRootActivityContainer.getActivityDisplay(displayId);
6549 if (activityDisplay == null) {
6550 // Call might come when display is not yet added or has been removed.
6551 if (DEBUG_CONFIGURATION) {
6552 Slog.w(TAG, "Trying to update display configuration for non-existing "
6553 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006554 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006555 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006556 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006557 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006558 if (process == null) {
6559 if (DEBUG_CONFIGURATION) {
6560 Slog.w(TAG, "Trying to update display configuration for invalid "
6561 + "process, pid=" + pid);
6562 }
6563 return;
6564 }
6565 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6566 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006567 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006568
6569 @Override
6570 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6571 int requestCode, int resultCode, Intent data) {
6572 synchronized (mGlobalLock) {
6573 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006574 if (r != null && r.getActivityStack() != null) {
6575 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6576 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006577 }
6578 }
6579 }
6580
6581 @Override
6582 public void clearPendingResultForActivity(IBinder activityToken,
6583 WeakReference<PendingIntentRecord> pir) {
6584 synchronized (mGlobalLock) {
6585 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6586 if (r != null && r.pendingResults != null) {
6587 r.pendingResults.remove(pir);
6588 }
6589 }
6590 }
6591
6592 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006593 public ActivityTokens getTopActivityForTask(int taskId) {
6594 synchronized (mGlobalLock) {
6595 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6596 if (taskRecord == null) {
6597 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6598 + " Requested task not found");
6599 return null;
6600 }
6601 final ActivityRecord activity = taskRecord.getTopActivity();
6602 if (activity == null) {
6603 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6604 + " Requested activity not found");
6605 return null;
6606 }
6607 if (!activity.attachedToProcess()) {
6608 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6609 + activity);
6610 return null;
6611 }
6612 return new ActivityTokens(activity.appToken, activity.assistToken,
6613 activity.app.getThread());
6614 }
6615 }
6616
6617 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006618 public IIntentSender getIntentSender(int type, String packageName,
6619 int callingUid, int userId, IBinder token, String resultWho,
6620 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6621 Bundle bOptions) {
6622 synchronized (mGlobalLock) {
6623 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6624 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6625 }
6626 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006627
6628 @Override
6629 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6630 synchronized (mGlobalLock) {
6631 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6632 if (r == null) {
6633 return null;
6634 }
6635 if (r.mServiceConnectionsHolder == null) {
6636 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6637 ActivityTaskManagerService.this, r);
6638 }
6639
6640 return r.mServiceConnectionsHolder;
6641 }
6642 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006643
6644 @Override
6645 public Intent getHomeIntent() {
6646 synchronized (mGlobalLock) {
6647 return ActivityTaskManagerService.this.getHomeIntent();
6648 }
6649 }
6650
6651 @Override
6652 public boolean startHomeActivity(int userId, String reason) {
6653 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006654 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006655 }
6656 }
6657
6658 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006659 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006660 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006661 synchronized (mGlobalLock) {
6662 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006663 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006664 }
Chilun8b1f1be2019-03-13 17:14:36 +08006665 }
6666
6667 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006668 public boolean startHomeOnAllDisplays(int userId, String reason) {
6669 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006670 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006671 }
6672 }
6673
Riddle Hsua0536432019-02-16 00:38:59 +08006674 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006675 @Override
6676 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006677 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006678 if (mFactoryTest == FACTORY_TEST_OFF) {
6679 return false;
6680 }
6681 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6682 && wpc.mName.equals(mTopComponent.getPackageName())) {
6683 return true;
6684 }
6685 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6686 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6687 }
6688 }
6689
6690 @Override
6691 public void updateTopComponentForFactoryTest() {
6692 synchronized (mGlobalLock) {
6693 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6694 return;
6695 }
6696 final ResolveInfo ri = mContext.getPackageManager()
6697 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6698 final CharSequence errorMsg;
6699 if (ri != null) {
6700 final ActivityInfo ai = ri.activityInfo;
6701 final ApplicationInfo app = ai.applicationInfo;
6702 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6703 mTopAction = Intent.ACTION_FACTORY_TEST;
6704 mTopData = null;
6705 mTopComponent = new ComponentName(app.packageName, ai.name);
6706 errorMsg = null;
6707 } else {
6708 errorMsg = mContext.getResources().getText(
6709 com.android.internal.R.string.factorytest_not_system);
6710 }
6711 } else {
6712 errorMsg = mContext.getResources().getText(
6713 com.android.internal.R.string.factorytest_no_action);
6714 }
6715 if (errorMsg == null) {
6716 return;
6717 }
6718
6719 mTopAction = null;
6720 mTopData = null;
6721 mTopComponent = null;
6722 mUiHandler.post(() -> {
6723 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6724 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006725 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006726 });
6727 }
6728 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729
Riddle Hsua0536432019-02-16 00:38:59 +08006730 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 @Override
6732 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6733 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006734 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006735 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006736 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737
6738 wpc.clearRecentTasks();
6739 wpc.clearActivities();
6740
6741 if (wpc.isInstrumenting()) {
6742 finishInstrumentationCallback.run();
6743 }
6744
Jorim Jaggid0752812018-10-16 16:07:20 +02006745 if (!restarting && hasVisibleActivities) {
6746 mWindowManager.deferSurfaceLayout();
6747 try {
6748 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6749 // If there was nothing to resume, and we are not already restarting
6750 // this process, but there is a visible activity that is hosted by the
6751 // process...then make sure all visible activities are running, taking
6752 // care of restarting this process.
6753 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6754 !PRESERVE_WINDOWS);
6755 }
6756 } finally {
6757 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 }
6760 }
6761 }
6762
6763 @Override
6764 public void closeSystemDialogs(String reason) {
6765 enforceNotIsolatedCaller("closeSystemDialogs");
6766
6767 final int pid = Binder.getCallingPid();
6768 final int uid = Binder.getCallingUid();
6769 final long origId = Binder.clearCallingIdentity();
6770 try {
6771 synchronized (mGlobalLock) {
6772 // Only allow this from foreground processes, so that background
6773 // applications can't abuse it to prevent system UI from being shown.
6774 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006775 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776 if (!proc.isPerceptible()) {
6777 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6778 + " from background process " + proc);
6779 return;
6780 }
6781 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 mWindowManager.closeSystemDialogs(reason);
6783
Wale Ogunwaled32da472018-11-16 07:19:28 -08006784 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006785 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006786 // Call into AM outside the synchronized block.
6787 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006788 } finally {
6789 Binder.restoreCallingIdentity(origId);
6790 }
6791 }
6792
6793 @Override
6794 public void cleanupDisabledPackageComponents(
6795 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6796 synchronized (mGlobalLock) {
6797 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006798 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006800 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 mStackSupervisor.scheduleIdleLocked();
6802 }
6803
6804 // Clean-up disabled tasks
6805 getRecentTasks().cleanupDisabledPackageTasksLocked(
6806 packageName, disabledClasses, userId);
6807 }
6808 }
6809
6810 @Override
6811 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6812 int userId) {
6813 synchronized (mGlobalLock) {
6814
6815 boolean didSomething =
6816 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006817 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006818 null, doit, evenPersistent, userId);
6819 return didSomething;
6820 }
6821 }
6822
6823 @Override
6824 public void resumeTopActivities(boolean scheduleIdle) {
6825 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006826 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 if (scheduleIdle) {
6828 mStackSupervisor.scheduleIdleLocked();
6829 }
6830 }
6831 }
6832
Riddle Hsua0536432019-02-16 00:38:59 +08006833 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 @Override
6835 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006836 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6838 }
6839 }
6840
Riddle Hsua0536432019-02-16 00:38:59 +08006841 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 @Override
6843 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006844 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006845 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
6847 }
6848
6849 @Override
6850 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6851 try {
6852 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6853 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6854 }
6855 } catch (RemoteException ex) {
6856 throw new SecurityException("Fail to check is caller a privileged app", ex);
6857 }
6858
6859 synchronized (mGlobalLock) {
6860 final long ident = Binder.clearCallingIdentity();
6861 try {
6862 if (mAmInternal.shouldConfirmCredentials(userId)) {
6863 if (mKeyguardController.isKeyguardLocked()) {
6864 // Showing launcher to avoid user entering credential twice.
6865 startHomeActivity(currentUserId, "notifyLockedProfile");
6866 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006867 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006868 }
6869 } finally {
6870 Binder.restoreCallingIdentity(ident);
6871 }
6872 }
6873 }
6874
6875 @Override
6876 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6877 mAmInternal.enforceCallingPermission(
6878 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6879
6880 synchronized (mGlobalLock) {
6881 final long ident = Binder.clearCallingIdentity();
6882 try {
6883 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6884 FLAG_ACTIVITY_TASK_ON_HOME);
6885 ActivityOptions activityOptions = options != null
6886 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006887 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006888 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006889 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006890 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006891 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6893 UserHandle.CURRENT);
6894 } finally {
6895 Binder.restoreCallingIdentity(ident);
6896 }
6897 }
6898 }
6899
6900 @Override
6901 public void writeActivitiesToProto(ProtoOutputStream proto) {
6902 synchronized (mGlobalLock) {
6903 // The output proto of "activity --proto activities"
6904 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006905 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006906 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6907 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 }
6909 }
6910
6911 @Override
6912 public void saveANRState(String reason) {
6913 synchronized (mGlobalLock) {
6914 final StringWriter sw = new StringWriter();
6915 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6916 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6917 if (reason != null) {
6918 pw.println(" Reason: " + reason);
6919 }
6920 pw.println();
6921 getActivityStartController().dump(pw, " ", null);
6922 pw.println();
6923 pw.println("-------------------------------------------------------------------------------");
6924 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6925 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6926 "" /* header */);
6927 pw.println();
6928 pw.close();
6929
6930 mLastANRState = sw.toString();
6931 }
6932 }
6933
6934 @Override
6935 public void clearSavedANRState() {
6936 synchronized (mGlobalLock) {
6937 mLastANRState = null;
6938 }
6939 }
6940
6941 @Override
6942 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6943 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6944 synchronized (mGlobalLock) {
6945 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6946 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6947 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6948 dumpLastANRLocked(pw);
6949 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6950 dumpLastANRTracesLocked(pw);
6951 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6952 dumpActivityStarterLocked(pw, dumpPackage);
6953 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6954 dumpActivityContainersLocked(pw);
6955 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6956 if (getRecentTasks() != null) {
6957 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6958 }
6959 }
6960 }
6961 }
6962
6963 @Override
6964 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6965 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6966 int wakefulness) {
6967 synchronized (mGlobalLock) {
6968 if (mHomeProcess != null && (dumpPackage == null
6969 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6970 if (needSep) {
6971 pw.println();
6972 needSep = false;
6973 }
6974 pw.println(" mHomeProcess: " + mHomeProcess);
6975 }
6976 if (mPreviousProcess != null && (dumpPackage == null
6977 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6978 if (needSep) {
6979 pw.println();
6980 needSep = false;
6981 }
6982 pw.println(" mPreviousProcess: " + mPreviousProcess);
6983 }
6984 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6985 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6986 StringBuilder sb = new StringBuilder(128);
6987 sb.append(" mPreviousProcessVisibleTime: ");
6988 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6989 pw.println(sb);
6990 }
6991 if (mHeavyWeightProcess != null && (dumpPackage == null
6992 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6993 if (needSep) {
6994 pw.println();
6995 needSep = false;
6996 }
6997 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6998 }
6999 if (dumpPackage == null) {
7000 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007001 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007002 }
7003 if (dumpAll) {
7004 if (dumpPackage == null) {
7005 pw.println(" mConfigWillChange: "
7006 + getTopDisplayFocusedStack().mConfigWillChange);
7007 }
7008 if (mCompatModePackages.getPackages().size() > 0) {
7009 boolean printed = false;
7010 for (Map.Entry<String, Integer> entry
7011 : mCompatModePackages.getPackages().entrySet()) {
7012 String pkg = entry.getKey();
7013 int mode = entry.getValue();
7014 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7015 continue;
7016 }
7017 if (!printed) {
7018 pw.println(" mScreenCompatPackages:");
7019 printed = true;
7020 }
7021 pw.println(" " + pkg + ": " + mode);
7022 }
7023 }
7024 }
7025
7026 if (dumpPackage == null) {
7027 pw.println(" mWakefulness="
7028 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007029 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 if (mRunningVoice != null) {
7031 pw.println(" mRunningVoice=" + mRunningVoice);
7032 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7033 }
7034 pw.println(" mSleeping=" + mSleeping);
7035 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7036 pw.println(" mVrController=" + mVrController);
7037 }
7038 if (mCurAppTimeTracker != null) {
7039 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7040 }
7041 if (mAllowAppSwitchUids.size() > 0) {
7042 boolean printed = false;
7043 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7044 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7045 for (int j = 0; j < types.size(); j++) {
7046 if (dumpPackage == null ||
7047 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7048 if (needSep) {
7049 pw.println();
7050 needSep = false;
7051 }
7052 if (!printed) {
7053 pw.println(" mAllowAppSwitchUids:");
7054 printed = true;
7055 }
7056 pw.print(" User ");
7057 pw.print(mAllowAppSwitchUids.keyAt(i));
7058 pw.print(": Type ");
7059 pw.print(types.keyAt(j));
7060 pw.print(" = ");
7061 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7062 pw.println();
7063 }
7064 }
7065 }
7066 }
7067 if (dumpPackage == null) {
7068 if (mController != null) {
7069 pw.println(" mController=" + mController
7070 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7071 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007072 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7073 pw.println(" mLaunchingActivityWakeLock="
7074 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007075 }
7076
7077 return needSep;
7078 }
7079 }
7080
7081 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007082 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7083 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 synchronized (mGlobalLock) {
7085 if (dumpPackage == null) {
7086 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7087 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007088 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7089 if (mRunningVoice != null) {
7090 final long vrToken = proto.start(
7091 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7092 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7093 mRunningVoice.toString());
7094 mVoiceWakeLock.writeToProto(
7095 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7096 proto.end(vrToken);
7097 }
7098 mVrController.writeToProto(proto,
7099 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 if (mController != null) {
7101 final long token = proto.start(CONTROLLER);
7102 proto.write(CONTROLLER, mController.toString());
7103 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7104 proto.end(token);
7105 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007106 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7107 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7108 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 }
7110
7111 if (mHomeProcess != null && (dumpPackage == null
7112 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007113 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007114 }
7115
7116 if (mPreviousProcess != null && (dumpPackage == null
7117 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007118 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7120 }
7121
7122 if (mHeavyWeightProcess != null && (dumpPackage == null
7123 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007124 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007125 }
7126
7127 for (Map.Entry<String, Integer> entry
7128 : mCompatModePackages.getPackages().entrySet()) {
7129 String pkg = entry.getKey();
7130 int mode = entry.getValue();
7131 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7132 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7133 proto.write(PACKAGE, pkg);
7134 proto.write(MODE, mode);
7135 proto.end(compatToken);
7136 }
7137 }
7138
7139 if (mCurAppTimeTracker != null) {
7140 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7141 }
7142
7143 }
7144 }
7145
7146 @Override
7147 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7148 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7149 boolean dumpFocusedStackOnly) {
7150 synchronized (mGlobalLock) {
7151 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7152 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7153 }
7154 }
7155
7156 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007157 public void dumpForOom(PrintWriter pw) {
7158 synchronized (mGlobalLock) {
7159 pw.println(" mHomeProcess: " + mHomeProcess);
7160 pw.println(" mPreviousProcess: " + mPreviousProcess);
7161 if (mHeavyWeightProcess != null) {
7162 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7163 }
7164 }
7165 }
7166
7167 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007168 public boolean canGcNow() {
7169 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007170 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007171 }
7172 }
7173
Riddle Hsua0536432019-02-16 00:38:59 +08007174 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007175 @Override
7176 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007177 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007178 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 return top != null ? top.app : null;
7180 }
7181 }
7182
Riddle Hsua0536432019-02-16 00:38:59 +08007183 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007184 @Override
7185 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007186 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007187 if (mRootActivityContainer != null) {
7188 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 }
7190 }
7191 }
7192
7193 @Override
7194 public void scheduleDestroyAllActivities(String reason) {
7195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007196 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007197 }
7198 }
7199
7200 @Override
7201 public void removeUser(int userId) {
7202 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007203 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 }
7205 }
7206
7207 @Override
7208 public boolean switchUser(int userId, UserState userState) {
7209 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007210 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 }
7212 }
7213
7214 @Override
7215 public void onHandleAppCrash(WindowProcessController wpc) {
7216 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007217 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007218 }
7219 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007220
7221 @Override
7222 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7223 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007224 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007225 }
7226 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007227
Riddle Hsua0536432019-02-16 00:38:59 +08007228 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007229 @Override
7230 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007231 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007232 }
7233
Riddle Hsua0536432019-02-16 00:38:59 +08007234 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007235 @Override
7236 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007237 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007238 }
7239
Riddle Hsua0536432019-02-16 00:38:59 +08007240 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007241 @Override
7242 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007243 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007244 }
7245
Riddle Hsua0536432019-02-16 00:38:59 +08007246 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007247 @Override
7248 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007249 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007250 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007251
7252 @Override
7253 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007254 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007255 mPendingTempWhitelist.put(uid, tag);
7256 }
7257 }
7258
7259 @Override
7260 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007261 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007262 mPendingTempWhitelist.remove(uid);
7263 }
7264 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007265
7266 @Override
7267 public boolean handleAppCrashInActivityController(String processName, int pid,
7268 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7269 Runnable killCrashingAppCallback) {
7270 synchronized (mGlobalLock) {
7271 if (mController == null) {
7272 return false;
7273 }
7274
7275 try {
7276 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7277 stackTrace)) {
7278 killCrashingAppCallback.run();
7279 return true;
7280 }
7281 } catch (RemoteException e) {
7282 mController = null;
7283 Watchdog.getInstance().setActivityController(null);
7284 }
7285 return false;
7286 }
7287 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007288
7289 @Override
7290 public void removeRecentTasksByPackageName(String packageName, int userId) {
7291 synchronized (mGlobalLock) {
7292 mRecentTasks.removeTasksByPackageName(packageName, userId);
7293 }
7294 }
7295
7296 @Override
7297 public void cleanupRecentTasksForUser(int userId) {
7298 synchronized (mGlobalLock) {
7299 mRecentTasks.cleanupLocked(userId);
7300 }
7301 }
7302
7303 @Override
7304 public void loadRecentTasksForUser(int userId) {
7305 synchronized (mGlobalLock) {
7306 mRecentTasks.loadUserRecentsLocked(userId);
7307 }
7308 }
7309
7310 @Override
7311 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7312 synchronized (mGlobalLock) {
7313 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7314 }
7315 }
7316
7317 @Override
7318 public void flushRecentTasks() {
7319 mRecentTasks.flush();
7320 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007321
7322 @Override
7323 public WindowProcessController getHomeProcess() {
7324 synchronized (mGlobalLock) {
7325 return mHomeProcess;
7326 }
7327 }
7328
7329 @Override
7330 public WindowProcessController getPreviousProcess() {
7331 synchronized (mGlobalLock) {
7332 return mPreviousProcess;
7333 }
7334 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007335
7336 @Override
7337 public void clearLockedTasks(String reason) {
7338 synchronized (mGlobalLock) {
7339 getLockTaskController().clearLockedTasks(reason);
7340 }
7341 }
7342
7343 @Override
7344 public void updateUserConfiguration() {
7345 synchronized (mGlobalLock) {
7346 final Configuration configuration = new Configuration(getGlobalConfiguration());
7347 final int currentUserId = mAmInternal.getCurrentUserId();
7348 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7349 configuration, currentUserId, Settings.System.canWrite(mContext));
7350 updateConfigurationLocked(configuration, null /* starting */,
7351 false /* initLocale */, false /* persistent */, currentUserId,
7352 false /* deferResume */);
7353 }
7354 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007355
7356 @Override
7357 public boolean canShowErrorDialogs() {
7358 synchronized (mGlobalLock) {
7359 return mShowDialogs && !mSleeping && !mShuttingDown
7360 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7361 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7362 mAmInternal.getCurrentUserId())
7363 && !(UserManager.isDeviceInDemoMode(mContext)
7364 && mAmInternal.getCurrentUser().isDemo());
7365 }
7366 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007367
7368 @Override
7369 public void setProfileApp(String profileApp) {
7370 synchronized (mGlobalLock) {
7371 mProfileApp = profileApp;
7372 }
7373 }
7374
7375 @Override
7376 public void setProfileProc(WindowProcessController wpc) {
7377 synchronized (mGlobalLock) {
7378 mProfileProc = wpc;
7379 }
7380 }
7381
7382 @Override
7383 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7384 synchronized (mGlobalLock) {
7385 mProfilerInfo = profilerInfo;
7386 }
7387 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007388
7389 @Override
7390 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7391 synchronized (mGlobalLock) {
7392 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7393 }
7394 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007395
7396 @Override
7397 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7398 synchronized (mGlobalLock) {
7399 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7400 }
7401 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007402
7403 @Override
7404 public boolean isUidForeground(int uid) {
7405 synchronized (mGlobalLock) {
7406 return ActivityTaskManagerService.this.isUidForeground(uid);
7407 }
7408 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007409
7410 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007411 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007412 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007413 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007414 }
7415 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007416
7417 @Override
7418 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007419 // Translate package names into UIDs
7420 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007421 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007422 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7423 if (uid >= 0) {
7424 result.add(uid);
7425 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007426 }
7427 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007428 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007429 }
7430 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007431 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007432}