blob: 7e741a01868b0894112a1a8c77ffc9b6cdad05db [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulian057a6512019-07-15 16:15:51 -070087import static com.android.server.wm.ActivityRecord.FINISH_RESULT_CANCELLED;
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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100314 // How long we permit background activity starts after an activity in the process
315 // started or finished.
316 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317
Wale Ogunwale98875612018-10-12 07:53:02 -0700318 /** Used to indicate that an app transition should be animated. */
319 static final boolean ANIMATE = true;
320
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700321 /** Hardware-reported OpenGLES version. */
322 final int GL_ES_VERSION;
323
Wale Ogunwale31913b52018-10-13 08:29:31 -0700324 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
325 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
326 public static final String DUMP_LASTANR_CMD = "lastanr" ;
327 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
328 public static final String DUMP_STARTER_CMD = "starter" ;
329 public static final String DUMP_CONTAINERS_CMD = "containers" ;
330 public static final String DUMP_RECENTS_CMD = "recents" ;
331 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
332
Wale Ogunwale64258362018-10-16 15:13:37 -0700333 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
334 public static final int RELAUNCH_REASON_NONE = 0;
335 /** This activity is being relaunched due to windowing mode change. */
336 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
337 /** This activity is being relaunched due to a free-resize operation. */
338 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
339
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700340 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700341
Wale Ogunwalef6733932018-06-27 05:14:34 -0700342 /**
343 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
344 * change at runtime. Use mContext for non-UI purposes.
345 */
346 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700348 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700351 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700352 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800353 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800354 @VisibleForTesting
355 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 PowerManagerInternal mPowerManagerInternal;
357 private UsageStatsManagerInternal mUsageStatsInternal;
358
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700359 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 IntentFirewall mIntentFirewall;
361
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700362 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800363 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 /**
365 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
366 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
367 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
368 *
369 * @see WindowManagerThreadPriorityBooster
370 */
371 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700372 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800373 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700374 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700375 private UserManagerService mUserManager;
376 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700377 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800378 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700379 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** All processes currently running that might have a window organized by name. */
381 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100382 /** All processes we currently have running mapped by pid and uid */
383 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** This is the process holding what we currently consider to be the "home" activity. */
385 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700386 /** The currently running heavy-weight process, if any. */
387 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700388 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /**
390 * This is the process holding the activity the user last visited that is in a different process
391 * from the one they are currently in.
392 */
393 WindowProcessController mPreviousProcess;
394 /** The time at which the previous process was last visible. */
395 long mPreviousProcessVisibleTime;
396
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700397 /** List of intents that were used to start the most recent tasks. */
398 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700399 /** State of external calls telling us if the device is awake or asleep. */
400 private boolean mKeyguardShown = false;
401
402 // Wrapper around VoiceInteractionServiceManager
403 private AssistUtils mAssistUtils;
404
405 // VoiceInteraction session ID that changes for each new request except when
406 // being called for multi-window assist in a single session.
407 private int mViSessionId = 1000;
408
409 // How long to wait in getAssistContextExtras for the activity and foreground services
410 // to respond with the result.
411 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
412
413 // How long top wait when going through the modern assist (which doesn't need to block
414 // on getting this result before starting to launch its UI).
415 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
416
417 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
418 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
419
Alison Cichowlas3e340502018-08-07 17:15:01 -0400420 // Permission tokens are used to temporarily granted a trusted app the ability to call
421 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
422 // showing any appropriate error messages to the user.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
424 10 * MINUTE_IN_MILLIS;
425
426 // How long before the service actually expires a token. This is slightly longer than
427 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
428 // expiration exception.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
430 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
431
432 // How long the service will remember expired tokens, for the purpose of providing error
433 // messaging when a client uses an expired token.
434 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
435 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
436
437 // Activity tokens of system activities that are delegating their call to
438 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
439 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
440
441 // Permission tokens that have expired, but we remember for error reporting.
442 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
443
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700444 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
445
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700446 // Keeps track of the active voice interaction service component, notified from
447 // VoiceInteractionManagerService
448 ComponentName mActiveVoiceInteractionServiceComponent;
449
Michal Karpinskida34cd42019-04-02 19:46:52 +0100450 // A map userId and all its companion app uids
451 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000452
Wale Ogunwalee2172292018-10-25 10:11:10 -0700453 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 KeyguardController mKeyguardController;
455 private final ClientLifecycleManager mLifecycleManager;
456 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700457 /** The controller for all operations related to locktask. */
458 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700459 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700461 boolean mSuppressResizeConfigChanges;
462
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700463 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 new UpdateConfigurationResult();
465
466 static final class UpdateConfigurationResult {
467 // Configuration changes that were updated.
468 int changes;
469 // If the activity was relaunched to match the new configuration.
470 boolean activityRelaunched;
471
472 void reset() {
473 changes = 0;
474 activityRelaunched = false;
475 }
476 }
477
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700478 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 private int mConfigurationSeq;
480 // To cache the list of supported system locales
481 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482
483 /**
484 * Temp object used when global and/or display override configuration is updated. It is also
485 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
486 * anyone...
487 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private Configuration mTempConfig = new Configuration();
489
Wale Ogunwalef6733932018-06-27 05:14:34 -0700490 /** Temporary to avoid allocations. */
491 final StringBuilder mStringBuilder = new StringBuilder(256);
492
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 // Amount of time after a call to stopAppSwitches() during which we will
494 // prevent further untrusted switches from happening.
495 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
496
497 /**
498 * The time at which we will allow normal application switches again,
499 * after a call to {@link #stopAppSwitches()}.
500 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
503 * This is set to true after the first switch after mAppSwitchesAllowedTime
504 * is set; any switches after that will clear the time.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507
Ricky Wai906af482019-06-03 17:25:28 +0100508 /**
509 * Last stop app switches time, apps finished before this time cannot start background activity
510 * even if they are in grace period.
511 */
512 private long mLastStopAppSwitchesTime;
513
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700514 IActivityController mController = null;
515 boolean mControllerIsAMonkey = false;
516
Wale Ogunwale214f3482018-10-04 11:00:47 -0700517 final int mFactoryTest;
518
519 /** Used to control how we initialize the service. */
520 ComponentName mTopComponent;
521 String mTopAction = Intent.ACTION_MAIN;
522 String mTopData;
523
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800524 /** Profiling app information. */
525 String mProfileApp = null;
526 WindowProcessController mProfileProc = null;
527 ProfilerInfo mProfilerInfo = null;
528
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700529 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700530 * Dump of the activity state at the time of the last ANR. Cleared after
531 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
532 */
533 String mLastANRState;
534
535 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700536 * Used to retain an update lock when the foreground activity is in
537 * immersive mode.
538 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700539 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540
541 /**
542 * Packages that are being allowed to perform unrestricted app switches. Mapping is
543 * User -> Type -> uid.
544 */
545 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
546
547 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700548 private int mThumbnailWidth;
549 private int mThumbnailHeight;
550 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700551
552 /**
553 * Flag that indicates if multi-window is enabled.
554 *
555 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
556 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
557 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
558 * At least one of the forms of multi-window must be enabled in order for this flag to be
559 * initialized to 'true'.
560 *
561 * @see #mSupportsSplitScreenMultiWindow
562 * @see #mSupportsFreeformWindowManagement
563 * @see #mSupportsPictureInPicture
564 * @see #mSupportsMultiDisplay
565 */
566 boolean mSupportsMultiWindow;
567 boolean mSupportsSplitScreenMultiWindow;
568 boolean mSupportsFreeformWindowManagement;
569 boolean mSupportsPictureInPicture;
570 boolean mSupportsMultiDisplay;
571 boolean mForceResizableActivities;
572
573 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
574
575 // VR Vr2d Display Id.
576 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700577
Wale Ogunwalef6733932018-06-27 05:14:34 -0700578 /**
579 * Set while we are wanting to sleep, to prevent any
580 * activities from being started/resumed.
581 *
582 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
583 *
584 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
585 * while in the sleep state until there is a pending transition out of sleep, in which case
586 * mSleeping is set to false, and remains false while awake.
587 *
588 * Whether mSleeping can quickly toggled between true/false without the device actually
589 * display changing states is undefined.
590 */
591 private boolean mSleeping = false;
592
593 /**
594 * The process state used for processes that are running the top activities.
595 * This changes between TOP and TOP_SLEEPING to following mSleeping.
596 */
597 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
598
599 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
600 // automatically. Important for devices without direct input devices.
601 private boolean mShowDialogs = true;
602
603 /** Set if we are shutting down the system, similar to sleeping. */
604 boolean mShuttingDown = false;
605
606 /**
607 * We want to hold a wake lock while running a voice interaction session, since
608 * this may happen with the screen off and we need to keep the CPU running to
609 * be able to continue to interact with the user.
610 */
611 PowerManager.WakeLock mVoiceWakeLock;
612
613 /**
614 * Set while we are running a voice interaction. This overrides sleeping while it is active.
615 */
616 IVoiceInteractionSession mRunningVoice;
617
618 /**
619 * The last resumed activity. This is identical to the current resumed activity most
620 * of the time but could be different when we're pausing one activity before we resume
621 * another activity.
622 */
623 ActivityRecord mLastResumedActivity;
624
625 /**
626 * The activity that is currently being traced as the active resumed activity.
627 *
628 * @see #updateResumedAppTrace
629 */
630 private @Nullable ActivityRecord mTracedResumedActivity;
631
632 /** If non-null, we are tracking the time the user spends in the currently focused app. */
633 AppTimeTracker mCurAppTimeTracker;
634
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700635 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700636
Wale Ogunwale53783742018-09-16 10:21:51 -0700637 /**
638 * Packages that the user has asked to have run in screen size
639 * compatibility mode instead of filling the screen.
640 */
641 CompatModePackages mCompatModePackages;
642
Wale Ogunwalef6733932018-06-27 05:14:34 -0700643 private FontScaleSettingObserver mFontScaleSettingObserver;
644
Ricky Wai96f5c352019-04-10 18:40:17 +0100645 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000646
Wale Ogunwalef6733932018-06-27 05:14:34 -0700647 private final class FontScaleSettingObserver extends ContentObserver {
648 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
649 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
650
651 public FontScaleSettingObserver() {
652 super(mH);
653 final ContentResolver resolver = mContext.getContentResolver();
654 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
655 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
656 UserHandle.USER_ALL);
657 }
658
659 @Override
660 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
661 if (mFontScaleUri.equals(uri)) {
662 updateFontScaleIfNeeded(userId);
663 } else if (mHideErrorDialogsUri.equals(uri)) {
664 synchronized (mGlobalLock) {
665 updateShouldShowDialogsLocked(getGlobalConfiguration());
666 }
667 }
668 }
669 }
670
Riddle Hsua0536432019-02-16 00:38:59 +0800671 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
672 @Target(ElementType.METHOD)
673 @Retention(RetentionPolicy.SOURCE)
674 @interface HotPath {
675 int NONE = 0;
676 int OOM_ADJUSTMENT = 1;
677 int LRU_UPDATE = 2;
678 int PROCESS_CHANGE = 3;
679 int caller() default NONE;
680 }
681
Charles Chen8d98dd22018-12-26 17:36:54 +0800682 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
683 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700685 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700686 mSystemThread = ActivityThread.currentActivityThread();
687 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700688 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800689 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700690 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700691 }
692
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700693 public void onSystemReady() {
694 synchronized (mGlobalLock) {
695 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
696 PackageManager.FEATURE_CANT_SAVE_STATE);
697 mAssistUtils = new AssistUtils(mContext);
698 mVrController.onSystemReady();
699 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700700 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700701 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700702 }
703
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700704 public void onInitPowerManagement() {
705 synchronized (mGlobalLock) {
706 mStackSupervisor.initPowerManagement();
707 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
708 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
709 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
710 mVoiceWakeLock.setReferenceCounted(false);
711 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700712 }
713
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700714 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700715 mFontScaleSettingObserver = new FontScaleSettingObserver();
716 }
717
Wale Ogunwale59507092018-10-29 09:00:30 -0700718 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700719 final boolean freeformWindowManagement =
720 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
721 || Settings.Global.getInt(
722 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
723
724 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
725 final boolean supportsPictureInPicture = supportsMultiWindow &&
726 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
727 final boolean supportsSplitScreenMultiWindow =
728 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
729 final boolean supportsMultiDisplay = mContext.getPackageManager()
730 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700731 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
732 final boolean forceResizable = Settings.Global.getInt(
733 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700734 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735
736 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900737 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700738
739 final Configuration configuration = new Configuration();
740 Settings.System.getConfiguration(resolver, configuration);
741 if (forceRtl) {
742 // This will take care of setting the correct layout direction flags
743 configuration.setLayoutDirection(configuration.locale);
744 }
745
746 synchronized (mGlobalLock) {
747 mForceResizableActivities = forceResizable;
748 final boolean multiWindowFormEnabled = freeformWindowManagement
749 || supportsSplitScreenMultiWindow
750 || supportsPictureInPicture
751 || supportsMultiDisplay;
752 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
753 mSupportsMultiWindow = true;
754 mSupportsFreeformWindowManagement = freeformWindowManagement;
755 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
756 mSupportsPictureInPicture = supportsPictureInPicture;
757 mSupportsMultiDisplay = supportsMultiDisplay;
758 } else {
759 mSupportsMultiWindow = false;
760 mSupportsFreeformWindowManagement = false;
761 mSupportsSplitScreenMultiWindow = false;
762 mSupportsPictureInPicture = false;
763 mSupportsMultiDisplay = false;
764 }
765 mWindowManager.setForceResizableTasks(mForceResizableActivities);
766 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700767 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
768 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700769 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700770 // This happens before any activities are started, so we can change global configuration
771 // in-place.
772 updateConfigurationLocked(configuration, null, true);
773 final Configuration globalConfig = getGlobalConfiguration();
774 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
775
776 // Load resources only after the current configuration has been set.
777 final Resources res = mContext.getResources();
778 mThumbnailWidth = res.getDimensionPixelSize(
779 com.android.internal.R.dimen.thumbnail_width);
780 mThumbnailHeight = res.getDimensionPixelSize(
781 com.android.internal.R.dimen.thumbnail_height);
782
783 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
784 mFullscreenThumbnailScale = (float) res
785 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
786 (float) globalConfig.screenWidthDp;
787 } else {
788 mFullscreenThumbnailScale = res.getFraction(
789 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
790 }
791 }
792 }
793
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800794 public WindowManagerGlobalLock getGlobalLock() {
795 return mGlobalLock;
796 }
797
Yunfan Chen585f2932019-01-29 16:04:45 +0900798 /** For test purpose only. */
799 @VisibleForTesting
800 public ActivityTaskManagerInternal getAtmInternal() {
801 return mInternal;
802 }
803
Riddle Hsud93a6c42018-11-29 21:50:06 +0800804 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
805 Looper looper) {
806 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700807 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700808 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700809 final File systemDir = SystemServiceManager.ensureSystemDir();
810 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
811 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
814 mTempConfig.setToDefaults();
815 mTempConfig.setLocales(LocaleList.getDefault());
816 mConfigurationSeq = mTempConfig.seq = 1;
817 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800818 mRootActivityContainer = new RootActivityContainer(this);
819 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700820
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700823 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700825 mRecentTasks = createRecentTasks();
826 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700827 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700828 mKeyguardController = mStackSupervisor.getKeyguardController();
829 }
830
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700831 public void onActivityManagerInternalAdded() {
832 synchronized (mGlobalLock) {
833 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
834 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
835 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700836 }
837
Yunfan Chen75157d72018-07-27 14:47:21 +0900838 int increaseConfigurationSeqLocked() {
839 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
840 return mConfigurationSeq;
841 }
842
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700843 protected ActivityStackSupervisor createStackSupervisor() {
844 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
845 supervisor.initialize();
846 return supervisor;
847 }
848
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 public void setWindowManager(WindowManagerService wm) {
850 synchronized (mGlobalLock) {
851 mWindowManager = wm;
852 mLockTaskController.setWindowManager(wm);
853 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800854 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700855 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700856 }
857
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
859 synchronized (mGlobalLock) {
860 mUsageStatsInternal = usageStatsManager;
861 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700862 }
863
Wale Ogunwalef6733932018-06-27 05:14:34 -0700864 UserManagerService getUserManager() {
865 if (mUserManager == null) {
866 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
867 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
868 }
869 return mUserManager;
870 }
871
872 AppOpsService getAppOpsService() {
873 if (mAppOpsService == null) {
874 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
875 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
876 }
877 return mAppOpsService;
878 }
879
880 boolean hasUserRestriction(String restriction, int userId) {
881 return getUserManager().hasUserRestriction(restriction, userId);
882 }
883
Michal Karpinski15486842019-04-25 17:33:42 +0100884 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
885 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
886 callingUid, callingPackage);
887 if (mode == AppOpsManager.MODE_DEFAULT) {
888 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
889 == PERMISSION_GRANTED;
890 }
891 return mode == AppOpsManager.MODE_ALLOWED;
892 }
893
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700894 protected RecentTasks createRecentTasks() {
895 return new RecentTasks(this, mStackSupervisor);
896 }
897
898 RecentTasks getRecentTasks() {
899 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700900 }
901
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700902 ClientLifecycleManager getLifecycleManager() {
903 return mLifecycleManager;
904 }
905
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700906 ActivityStartController getActivityStartController() {
907 return mActivityStartController;
908 }
909
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700910 TaskChangeNotificationController getTaskChangeNotificationController() {
911 return mTaskChangeNotificationController;
912 }
913
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700914 LockTaskController getLockTaskController() {
915 return mLockTaskController;
916 }
917
Yunfan Chen75157d72018-07-27 14:47:21 +0900918 /**
919 * Return the global configuration used by the process corresponding to the input pid. This is
920 * usually the global configuration with some overrides specific to that process.
921 */
922 Configuration getGlobalConfigurationForCallingPid() {
923 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800924 return getGlobalConfigurationForPid(pid);
925 }
926
927 /**
928 * Return the global configuration used by the process corresponding to the given pid.
929 */
930 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900931 if (pid == MY_PID || pid < 0) {
932 return getGlobalConfiguration();
933 }
934 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100935 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900936 return app != null ? app.getConfiguration() : getGlobalConfiguration();
937 }
938 }
939
940 /**
941 * Return the device configuration info used by the process corresponding to the input pid.
942 * The value is consistent with the global configuration for the process.
943 */
944 @Override
945 public ConfigurationInfo getDeviceConfigurationInfo() {
946 ConfigurationInfo config = new ConfigurationInfo();
947 synchronized (mGlobalLock) {
948 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
949 config.reqTouchScreen = globalConfig.touchscreen;
950 config.reqKeyboardType = globalConfig.keyboard;
951 config.reqNavigation = globalConfig.navigation;
952 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
953 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
954 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
955 }
956 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
957 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
958 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
959 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700960 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900961 }
962 return config;
963 }
964
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700965 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700966 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700967 }
968
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700969 public static final class Lifecycle extends SystemService {
970 private final ActivityTaskManagerService mService;
971
972 public Lifecycle(Context context) {
973 super(context);
974 mService = new ActivityTaskManagerService(context);
975 }
976
977 @Override
978 public void onStart() {
979 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700980 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700981 }
982
Garfield Tan891146c2018-10-09 12:14:00 -0700983 @Override
984 public void onUnlockUser(int userId) {
985 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800986 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700987 }
988 }
989
990 @Override
991 public void onCleanupUser(int userId) {
992 synchronized (mService.getGlobalLock()) {
993 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
994 }
995 }
996
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700997 public ActivityTaskManagerService getService() {
998 return mService;
999 }
1000 }
1001
1002 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001003 public final int startActivity(IApplicationThread caller, String callingPackage,
1004 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1005 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1006 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1007 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1008 UserHandle.getCallingUserId());
1009 }
1010
1011 @Override
1012 public final int startActivities(IApplicationThread caller, String callingPackage,
1013 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1014 int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001015 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001017 enforceNotIsolatedCaller(reason);
1018 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001020 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1021 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1022 reason, null /* originatingPendingIntent */,
1023 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 }
1025
1026 @Override
1027 public 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 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1031 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1032 true /*validateIncomingUser*/);
1033 }
1034
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001035 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1037 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1038 boolean validateIncomingUser) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001039 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001040 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001041
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001042 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1044
1045 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001046 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 .setCaller(caller)
1048 .setCallingPackage(callingPackage)
1049 .setResolvedType(resolvedType)
1050 .setResultTo(resultTo)
1051 .setResultWho(resultWho)
1052 .setRequestCode(requestCode)
1053 .setStartFlags(startFlags)
1054 .setProfilerInfo(profilerInfo)
1055 .setActivityOptions(bOptions)
1056 .setMayWait(userId)
1057 .execute();
1058
1059 }
1060
1061 @Override
1062 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1063 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1065 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 // Refuse possible leaked file descriptors
1067 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1068 throw new IllegalArgumentException("File descriptors passed in Intent");
1069 }
1070
1071 if (!(target instanceof PendingIntentRecord)) {
1072 throw new IllegalArgumentException("Bad PendingIntent object");
1073 }
1074
1075 PendingIntentRecord pir = (PendingIntentRecord)target;
1076
1077 synchronized (mGlobalLock) {
1078 // If this is coming from the currently resumed activity, it is
1079 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001080 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 if (stack.mResumedActivity != null &&
1082 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 }
1085 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001086 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 }
1089
1090 @Override
1091 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1092 Bundle bOptions) {
1093 // Refuse possible leaked file descriptors
1094 if (intent != null && intent.hasFileDescriptors()) {
1095 throw new IllegalArgumentException("File descriptors passed in Intent");
1096 }
1097 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1098
1099 synchronized (mGlobalLock) {
1100 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1101 if (r == null) {
1102 SafeActivityOptions.abort(options);
1103 return false;
1104 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001105 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 // The caller is not running... d'oh!
1107 SafeActivityOptions.abort(options);
1108 return false;
1109 }
1110 intent = new Intent(intent);
1111 // The caller is not allowed to change the data.
1112 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1113 // And we are resetting to find the next component...
1114 intent.setComponent(null);
1115
1116 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1117
1118 ActivityInfo aInfo = null;
1119 try {
1120 List<ResolveInfo> resolves =
1121 AppGlobals.getPackageManager().queryIntentActivities(
1122 intent, r.resolvedType,
1123 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1124 UserHandle.getCallingUserId()).getList();
1125
1126 // Look for the original activity in the list...
1127 final int N = resolves != null ? resolves.size() : 0;
1128 for (int i=0; i<N; i++) {
1129 ResolveInfo rInfo = resolves.get(i);
1130 if (rInfo.activityInfo.packageName.equals(r.packageName)
1131 && rInfo.activityInfo.name.equals(r.info.name)) {
1132 // We found the current one... the next matching is
1133 // after it.
1134 i++;
1135 if (i<N) {
1136 aInfo = resolves.get(i).activityInfo;
1137 }
1138 if (debug) {
1139 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1140 + "/" + r.info.name);
1141 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1142 ? "null" : aInfo.packageName + "/" + aInfo.name));
1143 }
1144 break;
1145 }
1146 }
1147 } catch (RemoteException e) {
1148 }
1149
1150 if (aInfo == null) {
1151 // Nobody who is next!
1152 SafeActivityOptions.abort(options);
1153 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1154 return false;
1155 }
1156
1157 intent.setComponent(new ComponentName(
1158 aInfo.applicationInfo.packageName, aInfo.name));
1159 intent.setFlags(intent.getFlags()&~(
1160 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1161 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1162 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1163 FLAG_ACTIVITY_NEW_TASK));
1164
1165 // Okay now we need to start the new activity, replacing the currently running activity.
1166 // This is a little tricky because we want to start the new one as if the current one is
1167 // finished, but not finish the current one first so that there is no flicker.
1168 // And thus...
1169 final boolean wasFinishing = r.finishing;
1170 r.finishing = true;
1171
1172 // Propagate reply information over to the new activity.
1173 final ActivityRecord resultTo = r.resultTo;
1174 final String resultWho = r.resultWho;
1175 final int requestCode = r.requestCode;
1176 r.resultTo = null;
1177 if (resultTo != null) {
1178 resultTo.removeResultsLocked(r, resultWho, requestCode);
1179 }
1180
1181 final long origId = Binder.clearCallingIdentity();
1182 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001183 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001184 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001185 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001186 .setResolvedType(r.resolvedType)
1187 .setActivityInfo(aInfo)
1188 .setResultTo(resultTo != null ? resultTo.appToken : null)
1189 .setResultWho(resultWho)
1190 .setRequestCode(requestCode)
1191 .setCallingPid(-1)
1192 .setCallingUid(r.launchedFromUid)
1193 .setCallingPackage(r.launchedFromPackage)
1194 .setRealCallingPid(-1)
1195 .setRealCallingUid(r.launchedFromUid)
1196 .setActivityOptions(options)
1197 .execute();
1198 Binder.restoreCallingIdentity(origId);
1199
1200 r.finishing = wasFinishing;
1201 if (res != ActivityManager.START_SUCCESS) {
1202 return false;
1203 }
1204 return true;
1205 }
1206 }
1207
1208 @Override
1209 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1210 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1211 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001212 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001213 final WaitResult res = new WaitResult();
1214 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001215 enforceNotIsolatedCaller("startActivityAndWait");
1216 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1217 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001218 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001219 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 .setCaller(caller)
1221 .setCallingPackage(callingPackage)
1222 .setResolvedType(resolvedType)
1223 .setResultTo(resultTo)
1224 .setResultWho(resultWho)
1225 .setRequestCode(requestCode)
1226 .setStartFlags(startFlags)
1227 .setActivityOptions(bOptions)
1228 .setMayWait(userId)
1229 .setProfilerInfo(profilerInfo)
1230 .setWaitResult(res)
1231 .execute();
1232 }
1233 return res;
1234 }
1235
1236 @Override
1237 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1238 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1239 int startFlags, Configuration config, Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001240 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001241 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001242 enforceNotIsolatedCaller("startActivityWithConfig");
1243 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1244 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001246 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001247 .setCaller(caller)
1248 .setCallingPackage(callingPackage)
1249 .setResolvedType(resolvedType)
1250 .setResultTo(resultTo)
1251 .setResultWho(resultWho)
1252 .setRequestCode(requestCode)
1253 .setStartFlags(startFlags)
1254 .setGlobalConfiguration(config)
1255 .setActivityOptions(bOptions)
1256 .setMayWait(userId)
1257 .execute();
1258 }
1259 }
1260
Alison Cichowlas3e340502018-08-07 17:15:01 -04001261
1262 @Override
1263 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1264 int callingUid = Binder.getCallingUid();
1265 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1266 throw new SecurityException("Only the system process can request a permission token, "
1267 + "received request from uid: " + callingUid);
1268 }
1269 IBinder permissionToken = new Binder();
1270 synchronized (mGlobalLock) {
1271 mStartActivitySources.put(permissionToken, delegatorToken);
1272 }
1273
1274 Message expireMsg = PooledLambda.obtainMessage(
1275 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1276 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1277
1278 Message forgetMsg = PooledLambda.obtainMessage(
1279 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1280 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1281
1282 return permissionToken;
1283 }
1284
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 @Override
1286 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1287 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001288 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1289 boolean ignoreTargetSecurity, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001290 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001292 // permission grants) as any app that may launch one of your own activities. So we only
1293 // allow this in two cases:
1294 // 1) The caller is an activity that is part of the core framework, and then only when it
1295 // is running as the system.
1296 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1297 // can only be requested by a system activity, which may then delegate this call to
1298 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 final ActivityRecord sourceRecord;
1300 final int targetUid;
1301 final String targetPackage;
1302 final boolean isResolver;
1303 synchronized (mGlobalLock) {
1304 if (resultTo == null) {
1305 throw new SecurityException("Must be called from an activity");
1306 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 final IBinder sourceToken;
1308 if (permissionToken != null) {
1309 // To even attempt to use a permissionToken, an app must also have this signature
1310 // permission.
1311 mAmInternal.enforceCallingPermission(
1312 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1313 "startActivityAsCaller");
1314 // If called with a permissionToken, we want the sourceRecord from the delegator
1315 // activity that requested this token.
1316 sourceToken = mStartActivitySources.remove(permissionToken);
1317 if (sourceToken == null) {
1318 // Invalid permissionToken, check if it recently expired.
1319 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1320 throw new SecurityException("Called with expired permission token: "
1321 + permissionToken);
1322 } else {
1323 throw new SecurityException("Called with invalid permission token: "
1324 + permissionToken);
1325 }
1326 }
1327 } else {
1328 // This method was called directly by the source.
1329 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331
Wale Ogunwaled32da472018-11-16 07:19:28 -08001332 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333 if (sourceRecord == null) {
1334 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 }
1336 if (sourceRecord.app == null) {
1337 throw new SecurityException("Called without a process attached to activity");
1338 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339
1340 // Whether called directly or from a delegate, the source activity must be from the
1341 // android package.
1342 if (!sourceRecord.info.packageName.equals("android")) {
1343 throw new SecurityException("Must be called from an activity that is "
1344 + "declared in the android package");
1345 }
1346
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001347 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 // This is still okay, as long as this activity is running under the
1349 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001350 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001352 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 + " must be system uid or original calling uid "
1354 + sourceRecord.launchedFromUid);
1355 }
1356 }
1357 if (ignoreTargetSecurity) {
1358 if (intent.getComponent() == null) {
1359 throw new SecurityException(
1360 "Component must be specified with ignoreTargetSecurity");
1361 }
1362 if (intent.getSelector() != null) {
1363 throw new SecurityException(
1364 "Selector not allowed with ignoreTargetSecurity");
1365 }
1366 }
1367 targetUid = sourceRecord.launchedFromUid;
1368 targetPackage = sourceRecord.launchedFromPackage;
1369 isResolver = sourceRecord.isResolverOrChildActivity();
1370 }
1371
1372 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001373 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 }
1375
1376 // TODO: Switch to user app stacks here.
1377 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(targetUid)
1380 .setCallingPackage(targetPackage)
1381 .setResolvedType(resolvedType)
1382 .setResultTo(resultTo)
1383 .setResultWho(resultWho)
1384 .setRequestCode(requestCode)
1385 .setStartFlags(startFlags)
1386 .setActivityOptions(bOptions)
1387 .setMayWait(userId)
1388 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1389 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001390 // The target may well be in the background, which would normally prevent it
1391 // from starting an activity. Here we definitely want the start to succeed.
1392 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001393 .execute();
1394 } catch (SecurityException e) {
1395 // XXX need to figure out how to propagate to original app.
1396 // A SecurityException here is generally actually a fault of the original
1397 // calling activity (such as a fairly granting permissions), so propagate it
1398 // back to them.
1399 /*
1400 StringBuilder msg = new StringBuilder();
1401 msg.append("While launching");
1402 msg.append(intent.toString());
1403 msg.append(": ");
1404 msg.append(e.getMessage());
1405 */
1406 throw e;
1407 }
1408 }
1409
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1411 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1412 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1413 }
1414
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 @Override
1416 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1417 Intent intent, String resolvedType, IVoiceInteractionSession session,
1418 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1419 Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001420 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001421 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 if (session == null || interactor == null) {
1423 throw new NullPointerException("null session or interactor");
1424 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001425 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001427 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 .setCallingUid(callingUid)
1429 .setCallingPackage(callingPackage)
1430 .setResolvedType(resolvedType)
1431 .setVoiceSession(session)
1432 .setVoiceInteractor(interactor)
1433 .setStartFlags(startFlags)
1434 .setProfilerInfo(profilerInfo)
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 int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1443 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001444 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001445 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1446 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001448 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 .setCallingUid(callingUid)
1450 .setCallingPackage(callingPackage)
1451 .setResolvedType(resolvedType)
1452 .setActivityOptions(bOptions)
1453 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001454 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 .execute();
1456 }
1457
Riddle Hsu609a8e22019-06-27 16:46:29 -06001458 /**
1459 * Start the recents activity to perform the recents animation.
1460 *
1461 * @param intent The intent to start the recents activity.
1462 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1463 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001465 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1466 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 final int callingPid = Binder.getCallingPid();
1469 final long origId = Binder.clearCallingIdentity();
1470 try {
1471 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001472 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1473 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474
1475 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001476 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001477 getActivityStartController(), mWindowManager, intent, recentsComponent,
1478 recentsUid, callingPid);
1479 if (recentsAnimationRunner == null) {
1480 anim.preloadRecentsActivity();
1481 } else {
1482 anim.startRecentsActivity(recentsAnimationRunner);
1483 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(origId);
1487 }
1488 }
1489
1490 @Override
1491 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001492 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 "startActivityFromRecents()");
1494
1495 final int callingPid = Binder.getCallingPid();
1496 final int callingUid = Binder.getCallingUid();
1497 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1498 final long origId = Binder.clearCallingIdentity();
1499 try {
1500 synchronized (mGlobalLock) {
1501 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1502 safeOptions);
1503 }
1504 } finally {
1505 Binder.restoreCallingIdentity(origId);
1506 }
1507 }
1508
1509 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001510 * Public API to check if the client is allowed to start an activity on specified display.
1511 *
1512 * If the target display is private or virtual, some restrictions will apply.
1513 *
1514 * @param displayId Target display id.
1515 * @param intent Intent used to launch the activity.
1516 * @param resolvedType The MIME type of the intent.
1517 * @param userId The id of the user for whom the call is made.
1518 * @return {@code true} if a call to start an activity on the target display should succeed and
1519 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1520 */
1521 @Override
1522 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1523 String resolvedType, int userId) {
1524 final int callingUid = Binder.getCallingUid();
1525 final int callingPid = Binder.getCallingPid();
1526 final long origId = Binder.clearCallingIdentity();
1527
1528 try {
1529 // Collect information about the target of the Intent.
1530 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1531 0 /* startFlags */, null /* profilerInfo */, userId,
1532 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1533 UserHandle.USER_NULL));
1534 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1535
1536 synchronized (mGlobalLock) {
1537 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1538 aInfo);
1539 }
1540 } finally {
1541 Binder.restoreCallingIdentity(origId);
1542 }
1543 }
1544
1545 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 * This is the internal entry point for handling Activity.finish().
1547 *
1548 * @param token The Binder token referencing the Activity we want to finish.
1549 * @param resultCode Result code, if any, from this Activity.
1550 * @param resultData Result data (Intent), if any, from this Activity.
1551 * @param finishTask Whether to finish the task associated with this Activity.
1552 *
1553 * @return Returns true if the activity successfully finished, or false if it is still running.
1554 */
1555 @Override
1556 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1557 int finishTask) {
1558 // Refuse possible leaked file descriptors
1559 if (resultData != null && resultData.hasFileDescriptors()) {
1560 throw new IllegalArgumentException("File descriptors passed in Intent");
1561 }
1562
1563 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001564 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 if (r == null) {
1566 return true;
1567 }
1568 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001569 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001570 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (rootR == null) {
1572 Slog.w(TAG, "Finishing task with all activities already finished");
1573 }
1574 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1575 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001576 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 return false;
1578 }
1579
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1581 // We should consolidate.
1582 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001584 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 if (next != null) {
1586 // ask watcher if this is allowed
1587 boolean resumeOK = true;
1588 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001589 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001591 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 Watchdog.getInstance().setActivityController(null);
1593 }
1594
1595 if (!resumeOK) {
1596 Slog.i(TAG, "Not finishing activity because controller resumed");
1597 return false;
1598 }
1599 }
1600 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001601
1602 // note down that the process has finished an activity and is in background activity
1603 // starts grace period
1604 if (r.app != null) {
1605 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1606 }
1607
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001608 final long origId = Binder.clearCallingIdentity();
1609 try {
1610 boolean res;
1611 final boolean finishWithRootActivity =
1612 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1613 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1614 || (finishWithRootActivity && r == rootR)) {
1615 // If requested, remove the task that is associated to this activity only if it
1616 // was the root activity in the task. The result code and data is ignored
1617 // because we don't support returning them across task boundaries. Also, to
1618 // keep backwards compatibility we remove the task from recents when finishing
1619 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001620 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 finishWithRootActivity, "finish-activity");
1622 if (!res) {
1623 Slog.i(TAG, "Removing task failed to finish activity");
1624 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001625 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001626 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001627 } else {
Andrii Kulian057a6512019-07-15 16:15:51 -07001628 res = r.finishActivityLocked(resultCode, resultData, "app-request",
1629 true /* oomAdj */) != FINISH_RESULT_CANCELLED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001630 if (!res) {
1631 Slog.i(TAG, "Failed to finish by app-request");
1632 }
1633 }
1634 return res;
1635 } finally {
1636 Binder.restoreCallingIdentity(origId);
1637 }
1638 }
1639 }
1640
1641 @Override
1642 public boolean finishActivityAffinity(IBinder token) {
1643 synchronized (mGlobalLock) {
1644 final long origId = Binder.clearCallingIdentity();
1645 try {
1646 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1647 if (r == null) {
1648 return false;
1649 }
1650
1651 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1652 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001653 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 return false;
1655 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001656 r.finishActivityAffinity();
1657 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 } finally {
1659 Binder.restoreCallingIdentity(origId);
1660 }
1661 }
1662 }
1663
1664 @Override
1665 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1666 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001667 try {
1668 WindowProcessController proc = null;
1669 synchronized (mGlobalLock) {
1670 ActivityStack stack = ActivityRecord.getStackLocked(token);
1671 if (stack == null) {
1672 return;
1673 }
1674 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1675 false /* fromTimeout */, false /* processPausingActivities */, config);
1676 if (r != null) {
1677 proc = r.app;
1678 }
1679 if (stopProfiling && proc != null) {
1680 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 }
1682 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001683 } finally {
1684 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 }
1687
1688 @Override
1689 public final void activityResumed(IBinder token) {
1690 final long origId = Binder.clearCallingIdentity();
1691 synchronized (mGlobalLock) {
1692 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001693 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 }
1695 Binder.restoreCallingIdentity(origId);
1696 }
1697
1698 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001699 public final void activityTopResumedStateLost() {
1700 final long origId = Binder.clearCallingIdentity();
1701 synchronized (mGlobalLock) {
1702 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1703 }
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708 public final void activityPaused(IBinder token) {
1709 final long origId = Binder.clearCallingIdentity();
1710 synchronized (mGlobalLock) {
1711 ActivityStack stack = ActivityRecord.getStackLocked(token);
1712 if (stack != null) {
1713 stack.activityPausedLocked(token, false);
1714 }
1715 }
1716 Binder.restoreCallingIdentity(origId);
1717 }
1718
1719 @Override
1720 public final void activityStopped(IBinder token, Bundle icicle,
1721 PersistableBundle persistentState, CharSequence description) {
1722 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1723
1724 // Refuse possible leaked file descriptors
1725 if (icicle != null && icicle.hasFileDescriptors()) {
1726 throw new IllegalArgumentException("File descriptors passed in Bundle");
1727 }
1728
1729 final long origId = Binder.clearCallingIdentity();
1730
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001731 String restartingName = null;
1732 int restartingUid = 0;
1733 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001735 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001737 if (r.attachedToProcess()
1738 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1739 // The activity was requested to restart from
1740 // {@link #restartActivityProcessIfVisible}.
1741 restartingName = r.app.mName;
1742 restartingUid = r.app.mUid;
1743 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 r.activityStoppedLocked(icicle, persistentState, description);
1745 }
1746 }
1747
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001748 if (restartingName != null) {
1749 // In order to let the foreground activity can be restarted with its saved state from
1750 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1751 // until the activity reports stopped with the state. And the activity record will be
1752 // kept because the record state is restarting, then the activity will be restarted
1753 // immediately if it is still the top one.
1754 mStackSupervisor.removeRestartTimeouts(r);
1755 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1756 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758
1759 Binder.restoreCallingIdentity(origId);
1760 }
1761
1762 @Override
1763 public final void activityDestroyed(IBinder token) {
1764 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1765 synchronized (mGlobalLock) {
1766 ActivityStack stack = ActivityRecord.getStackLocked(token);
1767 if (stack != null) {
1768 stack.activityDestroyedLocked(token, "activityDestroyed");
1769 }
1770 }
1771 }
1772
1773 @Override
1774 public final void activityRelaunched(IBinder token) {
1775 final long origId = Binder.clearCallingIdentity();
1776 synchronized (mGlobalLock) {
1777 mStackSupervisor.activityRelaunchedLocked(token);
1778 }
1779 Binder.restoreCallingIdentity(origId);
1780 }
1781
1782 public final void activitySlept(IBinder token) {
1783 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1784
1785 final long origId = Binder.clearCallingIdentity();
1786
1787 synchronized (mGlobalLock) {
1788 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1789 if (r != null) {
1790 mStackSupervisor.activitySleptLocked(r);
1791 }
1792 }
1793
1794 Binder.restoreCallingIdentity(origId);
1795 }
1796
1797 @Override
1798 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1799 synchronized (mGlobalLock) {
1800 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1801 if (r == null) {
1802 return;
1803 }
1804 final long origId = Binder.clearCallingIdentity();
1805 try {
1806 r.setRequestedOrientation(requestedOrientation);
1807 } finally {
1808 Binder.restoreCallingIdentity(origId);
1809 }
1810 }
1811 }
1812
1813 @Override
1814 public int getRequestedOrientation(IBinder token) {
1815 synchronized (mGlobalLock) {
1816 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1817 if (r == null) {
1818 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1819 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001820 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 }
1822 }
1823
1824 @Override
1825 public void setImmersive(IBinder token, boolean immersive) {
1826 synchronized (mGlobalLock) {
1827 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1828 if (r == null) {
1829 throw new IllegalArgumentException();
1830 }
1831 r.immersive = immersive;
1832
1833 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001834 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 }
1838 }
1839 }
1840
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001841 void applyUpdateLockStateLocked(ActivityRecord r) {
1842 // Modifications to the UpdateLock state are done on our handler, outside
1843 // the activity manager's locks. The new state is determined based on the
1844 // state *now* of the relevant activity record. The object is passed to
1845 // the handler solely for logging detail, not to be consulted/modified.
1846 final boolean nextState = r != null && r.immersive;
1847 mH.post(() -> {
1848 if (mUpdateLock.isHeld() != nextState) {
1849 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1850 "Applying new update lock state '" + nextState + "' for " + r);
1851 if (nextState) {
1852 mUpdateLock.acquire();
1853 } else {
1854 mUpdateLock.release();
1855 }
1856 }
1857 });
1858 }
1859
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 @Override
1861 public boolean isImmersive(IBinder token) {
1862 synchronized (mGlobalLock) {
1863 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1864 if (r == null) {
1865 throw new IllegalArgumentException();
1866 }
1867 return r.immersive;
1868 }
1869 }
1870
1871 @Override
1872 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001873 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001875 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 return (r != null) ? r.immersive : false;
1877 }
1878 }
1879
1880 @Override
1881 public void overridePendingTransition(IBinder token, String packageName,
1882 int enterAnim, int exitAnim) {
1883 synchronized (mGlobalLock) {
1884 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1885 if (self == null) {
1886 return;
1887 }
1888
1889 final long origId = Binder.clearCallingIdentity();
1890
1891 if (self.isState(
1892 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001893 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001894 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 }
1896
1897 Binder.restoreCallingIdentity(origId);
1898 }
1899 }
1900
1901 @Override
1902 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001905 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 if (r == null) {
1907 return ActivityManager.COMPAT_MODE_UNKNOWN;
1908 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001909 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 }
1911 }
1912
1913 @Override
1914 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001917 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001919 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 if (r == null) {
1921 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1922 return;
1923 }
1924 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001925 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 }
1927 }
1928
1929 @Override
1930 public int getLaunchedFromUid(IBinder activityToken) {
1931 ActivityRecord srec;
1932 synchronized (mGlobalLock) {
1933 srec = ActivityRecord.forTokenLocked(activityToken);
1934 }
1935 if (srec == null) {
1936 return -1;
1937 }
1938 return srec.launchedFromUid;
1939 }
1940
1941 @Override
1942 public String getLaunchedFromPackage(IBinder activityToken) {
1943 ActivityRecord srec;
1944 synchronized (mGlobalLock) {
1945 srec = ActivityRecord.forTokenLocked(activityToken);
1946 }
1947 if (srec == null) {
1948 return null;
1949 }
1950 return srec.launchedFromPackage;
1951 }
1952
1953 @Override
1954 public boolean convertFromTranslucent(IBinder token) {
1955 final long origId = Binder.clearCallingIdentity();
1956 try {
1957 synchronized (mGlobalLock) {
1958 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1959 if (r == null) {
1960 return false;
1961 }
1962 final boolean translucentChanged = r.changeWindowTranslucency(true);
1963 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001964 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001966 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 return translucentChanged;
1968 }
1969 } finally {
1970 Binder.restoreCallingIdentity(origId);
1971 }
1972 }
1973
1974 @Override
1975 public boolean convertToTranslucent(IBinder token, Bundle options) {
1976 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1977 final long origId = Binder.clearCallingIdentity();
1978 try {
1979 synchronized (mGlobalLock) {
1980 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1981 if (r == null) {
1982 return false;
1983 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001984 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 int index = task.mActivities.lastIndexOf(r);
1986 if (index > 0) {
1987 ActivityRecord under = task.mActivities.get(index - 1);
1988 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1989 }
1990 final boolean translucentChanged = r.changeWindowTranslucency(false);
1991 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001992 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001994 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 return translucentChanged;
1997 }
1998 } finally {
1999 Binder.restoreCallingIdentity(origId);
2000 }
2001 }
2002
2003 @Override
2004 public void notifyActivityDrawn(IBinder token) {
2005 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2006 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002007 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002009 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 }
2011 }
2012 }
2013
2014 @Override
2015 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2016 synchronized (mGlobalLock) {
2017 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2018 if (r == null) {
2019 return;
2020 }
2021 r.reportFullyDrawnLocked(restoredFromBundle);
2022 }
2023 }
2024
2025 @Override
2026 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2027 synchronized (mGlobalLock) {
2028 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2029 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2030 return stack.mDisplayId;
2031 }
2032 return DEFAULT_DISPLAY;
2033 }
2034 }
2035
2036 @Override
2037 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002038 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002039 long ident = Binder.clearCallingIdentity();
2040 try {
2041 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002042 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002044 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 }
2046 return null;
2047 }
2048 } finally {
2049 Binder.restoreCallingIdentity(ident);
2050 }
2051 }
2052
2053 @Override
2054 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002055 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2057 final long callingId = Binder.clearCallingIdentity();
2058 try {
2059 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002060 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 if (stack == null) {
2062 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2063 return;
2064 }
2065 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002066 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002067 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 }
2069 }
2070 } finally {
2071 Binder.restoreCallingIdentity(callingId);
2072 }
2073 }
2074
2075 @Override
2076 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002077 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2079 final long callingId = Binder.clearCallingIdentity();
2080 try {
2081 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002082 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002083 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 if (task == null) {
2085 return;
2086 }
2087 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002088 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002089 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 }
2091 }
2092 } finally {
2093 Binder.restoreCallingIdentity(callingId);
2094 }
2095 }
2096
2097 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002098 public void restartActivityProcessIfVisible(IBinder activityToken) {
2099 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2100 final long callingId = Binder.clearCallingIdentity();
2101 try {
2102 synchronized (mGlobalLock) {
2103 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2104 if (r == null) {
2105 return;
2106 }
2107 r.restartProcessIfVisible();
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(callingId);
2111 }
2112 }
2113
2114 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002116 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 synchronized (mGlobalLock) {
2118 final long ident = Binder.clearCallingIdentity();
2119 try {
2120 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2121 "remove-task");
2122 } finally {
2123 Binder.restoreCallingIdentity(ident);
2124 }
2125 }
2126 }
2127
2128 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002129 public void removeAllVisibleRecentTasks() {
2130 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2131 synchronized (mGlobalLock) {
2132 final long ident = Binder.clearCallingIdentity();
2133 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002134 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002135 } finally {
2136 Binder.restoreCallingIdentity(ident);
2137 }
2138 }
2139 }
2140
2141 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2143 synchronized (mGlobalLock) {
2144 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2145 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002146 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 }
2148 }
2149 return false;
2150 }
2151
2152 @Override
2153 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2154 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002155
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002156 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002157 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2158 if (r != null) {
2159 return r.getActivityStack().navigateUpToLocked(
2160 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002161 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002162 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 }
2164 }
2165
2166 /**
2167 * Attempts to move a task backwards in z-order (the order of activities within the task is
2168 * unchanged).
2169 *
2170 * There are several possible results of this call:
2171 * - if the task is locked, then we will show the lock toast
2172 * - if there is a task behind the provided task, then that task is made visible and resumed as
2173 * this task is moved to the back
2174 * - otherwise, if there are no other tasks in the stack:
2175 * - if this task is in the pinned stack, then we remove the stack completely, which will
2176 * have the effect of moving the task to the top or bottom of the fullscreen stack
2177 * (depending on whether it is visible)
2178 * - otherwise, we simply return home and hide this task
2179 *
2180 * @param token A reference to the activity we wish to move
2181 * @param nonRoot If false then this only works if the activity is the root
2182 * of a task; if true it will work for any activity in a task.
2183 * @return Returns true if the move completed, false if not.
2184 */
2185 @Override
2186 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002187 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 synchronized (mGlobalLock) {
2189 final long origId = Binder.clearCallingIdentity();
2190 try {
2191 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002192 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002193 if (task != null) {
2194 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2195 }
2196 } finally {
2197 Binder.restoreCallingIdentity(origId);
2198 }
2199 }
2200 return false;
2201 }
2202
2203 @Override
2204 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002205 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 long ident = Binder.clearCallingIdentity();
2207 Rect rect = new Rect();
2208 try {
2209 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002210 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2212 if (task == null) {
2213 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2214 return rect;
2215 }
2216 if (task.getStack() != null) {
2217 // Return the bounds from window manager since it will be adjusted for various
2218 // things like the presense of a docked stack for tasks that aren't resizeable.
2219 task.getWindowContainerBounds(rect);
2220 } else {
2221 // Task isn't in window manager yet since it isn't associated with a stack.
2222 // Return the persist value from activity manager
2223 if (!task.matchParentBounds()) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
2227 }
2228 }
2229 }
2230 } finally {
2231 Binder.restoreCallingIdentity(ident);
2232 }
2233 return rect;
2234 }
2235
2236 @Override
2237 public ActivityManager.TaskDescription getTaskDescription(int id) {
2238 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002239 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002241 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002242 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2243 if (tr != null) {
2244 return tr.lastTaskDescription;
2245 }
2246 }
2247 return null;
2248 }
2249
2250 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002251 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2252 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2253 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2254 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2255 return;
2256 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002257 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002258 synchronized (mGlobalLock) {
2259 final long ident = Binder.clearCallingIdentity();
2260 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002261 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002262 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002263 if (task == null) {
2264 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2265 return;
2266 }
2267
2268 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2269 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2270
2271 if (!task.isActivityTypeStandardOrUndefined()) {
2272 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2273 + " non-standard task " + taskId + " to windowing mode="
2274 + windowingMode);
2275 }
2276
2277 final ActivityStack stack = task.getStack();
2278 if (toTop) {
2279 stack.moveToFront("setTaskWindowingMode", task);
2280 }
2281 stack.setWindowingMode(windowingMode);
2282 } finally {
2283 Binder.restoreCallingIdentity(ident);
2284 }
2285 }
2286 }
2287
2288 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002290 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 ActivityRecord r = getCallingRecordLocked(token);
2292 return r != null ? r.info.packageName : null;
2293 }
2294 }
2295
2296 @Override
2297 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.intent.getComponent() : null;
2301 }
2302 }
2303
2304 private ActivityRecord getCallingRecordLocked(IBinder token) {
2305 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2306 if (r == null) {
2307 return null;
2308 }
2309 return r.resultTo;
2310 }
2311
2312 @Override
2313 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002314 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315
2316 synchronized (mGlobalLock) {
2317 final long origId = Binder.clearCallingIdentity();
2318 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002319 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 } finally {
2321 Binder.restoreCallingIdentity(origId);
2322 }
2323 }
2324 }
2325
Mark Renouf446251d2019-04-26 10:22:41 -04002326 @Override
2327 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2328 synchronized (mGlobalLock) {
2329 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2330 if (r == null) {
2331 return;
2332 }
2333 ActivityStack stack = r.getActivityStack();
2334 if (stack != null && stack.isSingleTaskInstance()) {
2335 // Single-task stacks are used for activities which are presented in floating
2336 // windows above full screen activities. Instead of directly finishing the
2337 // task, a task change listener is used to notify SystemUI so the action can be
2338 // handled specially.
2339 final TaskRecord task = r.getTaskRecord();
2340 mTaskChangeNotificationController
2341 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2342 } else {
2343 try {
2344 callback.requestFinish();
2345 } catch (RemoteException e) {
2346 Slog.e(TAG, "Failed to invoke request finish callback", e);
2347 }
2348 }
2349 }
2350 }
2351
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002352 /**
2353 * TODO: Add mController hook
2354 */
2355 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002356 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2357 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002358 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359
2360 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2361 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002362 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2363 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 }
2365 }
2366
Ricky Waiaca8a772019-04-04 16:01:06 +01002367 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2368 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 final int callingPid = Binder.getCallingPid();
2371 final int callingUid = Binder.getCallingUid();
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002372 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 SafeActivityOptions.abort(options);
2375 return;
2376 }
2377 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 WindowProcessController callerApp = null;
2379 if (appThread != null) {
2380 callerApp = getProcessController(appThread);
2381 }
2382 final ActivityStarter starter = getActivityStartController().obtainStarter(
2383 null /* intent */, "moveTaskToFront");
2384 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2385 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002386 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 return;
2388 }
2389 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002391 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 if (task == null) {
2393 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002394 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 return;
2396 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002397 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002399 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 return;
2401 }
2402 ActivityOptions realOptions = options != null
2403 ? options.getOptions(mStackSupervisor)
2404 : null;
2405 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2406 false /* forceNonResizable */);
2407
2408 final ActivityRecord topActivity = task.getTopActivity();
2409 if (topActivity != null) {
2410
2411 // We are reshowing a task, use a starting window to hide the initial draw delay
2412 // so the transition can start earlier.
2413 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2414 true /* taskSwitch */, fromRecents);
2415 }
2416 } finally {
2417 Binder.restoreCallingIdentity(origId);
2418 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 }
2420
Ricky Waiaca8a772019-04-04 16:01:06 +01002421 /**
2422 * Return true if callingUid is system, or packageName belongs to that callingUid.
2423 */
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002424 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002425 try {
2426 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2427 if (packageName == null) {
2428 return false;
2429 }
2430 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2431 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2432 UserHandle.getUserId(callingUid));
2433 return UserHandle.isSameApp(callingUid, uid);
2434 }
2435 } catch (RemoteException e) {
2436 // Should not happen
2437 }
2438 return true;
2439 }
2440
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002441 /**
2442 * Checks that the provided package name matches the current calling UID, throws a security
2443 * exception if it doesn't.
2444 */
2445 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2446 final int callingUid = Binder.getCallingUid();
2447 if (isSameApp(callingUid, packageName)) {
2448 return;
2449 }
2450 final String msg = "Permission Denial: package=" + packageName
2451 + " does not belong to uid=" + callingUid;
2452 Slog.w(TAG, msg);
2453 throw new SecurityException(msg);
2454 }
2455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2457 int callingPid, int callingUid, String name) {
2458 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2459 return true;
2460 }
2461
2462 if (getRecentTasks().isCallerRecents(sourceUid)) {
2463 return true;
2464 }
2465
2466 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2467 if (perm == PackageManager.PERMISSION_GRANTED) {
2468 return true;
2469 }
2470 if (checkAllowAppSwitchUid(sourceUid)) {
2471 return true;
2472 }
2473
2474 // If the actual IPC caller is different from the logical source, then
2475 // also see if they are allowed to control app switches.
2476 if (callingUid != -1 && callingUid != sourceUid) {
2477 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2478 if (perm == PackageManager.PERMISSION_GRANTED) {
2479 return true;
2480 }
2481 if (checkAllowAppSwitchUid(callingUid)) {
2482 return true;
2483 }
2484 }
2485
2486 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2487 return false;
2488 }
2489
2490 private boolean checkAllowAppSwitchUid(int uid) {
2491 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2492 if (types != null) {
2493 for (int i = types.size() - 1; i >= 0; i--) {
2494 if (types.valueAt(i).intValue() == uid) {
2495 return true;
2496 }
2497 }
2498 }
2499 return false;
2500 }
2501
2502 @Override
2503 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2504 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2505 "setActivityController()");
2506 synchronized (mGlobalLock) {
2507 mController = controller;
2508 mControllerIsAMonkey = imAMonkey;
2509 Watchdog.getInstance().setActivityController(controller);
2510 }
2511 }
2512
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002513 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 synchronized (mGlobalLock) {
2515 return mController != null && mControllerIsAMonkey;
2516 }
2517 }
2518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 @Override
2520 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2521 synchronized (mGlobalLock) {
2522 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2523 }
2524 }
2525
2526 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2528 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2529 }
2530
2531 @Override
2532 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2533 @WindowConfiguration.ActivityType int ignoreActivityType,
2534 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2535 final int callingUid = Binder.getCallingUid();
2536 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2537
2538 synchronized (mGlobalLock) {
2539 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2540
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002541 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002543 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 ignoreWindowingMode, callingUid, allowed);
2545 }
2546
2547 return list;
2548 }
2549
2550 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002551 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2552 synchronized (mGlobalLock) {
2553 final long origId = Binder.clearCallingIdentity();
2554 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2555 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002556 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 }
2558 Binder.restoreCallingIdentity(origId);
2559 }
2560 }
2561
2562 @Override
2563 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002564 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002565 ActivityStack stack = ActivityRecord.getStackLocked(token);
2566 if (stack != null) {
2567 return stack.willActivityBeVisibleLocked(token);
2568 }
2569 return false;
2570 }
2571 }
2572
2573 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002574 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002575 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576 synchronized (mGlobalLock) {
2577 final long ident = Binder.clearCallingIdentity();
2578 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002579 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 if (task == null) {
2581 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2582 return;
2583 }
2584
2585 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2586 + " to stackId=" + stackId + " toTop=" + toTop);
2587
Wale Ogunwaled32da472018-11-16 07:19:28 -08002588 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002589 if (stack == null) {
2590 throw new IllegalStateException(
2591 "moveTaskToStack: No stack for stackId=" + stackId);
2592 }
2593 if (!stack.isActivityTypeStandardOrUndefined()) {
2594 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2595 + taskId + " to stack " + stackId);
2596 }
2597 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2600 }
2601 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2602 "moveTaskToStack");
2603 } finally {
2604 Binder.restoreCallingIdentity(ident);
2605 }
2606 }
2607 }
2608
2609 @Override
2610 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2611 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002612 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613
2614 final long ident = Binder.clearCallingIdentity();
2615 try {
2616 synchronized (mGlobalLock) {
2617 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002618 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 if (stack == null) {
2620 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2621 return;
2622 }
2623 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2624 throw new IllegalArgumentException("Stack: " + stackId
2625 + " doesn't support animated resize.");
2626 }
2627 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2628 animationDuration, false /* fromFullscreen */);
2629 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002630 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002631 if (stack == null) {
2632 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2633 return;
2634 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002635 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002636 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2637 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2638 }
2639 }
2640 } finally {
2641 Binder.restoreCallingIdentity(ident);
2642 }
2643 }
2644
wilsonshih5c4cf522019-01-25 09:03:47 +08002645 @Override
2646 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2647 int animationDuration) {
2648 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2649
2650 final long ident = Binder.clearCallingIdentity();
2651 try {
2652 synchronized (mGlobalLock) {
2653 if (xOffset == 0 && yOffset == 0) {
2654 return;
2655 }
2656 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2657 if (stack == null) {
2658 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2659 return;
2660 }
2661 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2662 throw new IllegalArgumentException("Stack: " + stackId
2663 + " doesn't support animated resize.");
2664 }
2665 final Rect destBounds = new Rect();
2666 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002667 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002668 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2669 return;
2670 }
2671 destBounds.offset(xOffset, yOffset);
2672 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2673 animationDuration, false /* fromFullscreen */);
2674 }
2675 } finally {
2676 Binder.restoreCallingIdentity(ident);
2677 }
2678 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002679 /**
2680 * Moves the specified task to the primary-split-screen stack.
2681 *
2682 * @param taskId Id of task to move.
2683 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2684 * exist already. See
2685 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2686 * and
2687 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2688 * @param toTop If the task and stack should be moved to the top.
2689 * @param animate Whether we should play an animation for the moving the task.
2690 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2691 * stack. Pass {@code null} to use default bounds.
2692 * @param showRecents If the recents activity should be shown on the other side of the task
2693 * going into split-screen mode.
2694 */
2695 @Override
2696 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2697 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002698 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 "setTaskWindowingModeSplitScreenPrimary()");
2700 synchronized (mGlobalLock) {
2701 final long ident = Binder.clearCallingIdentity();
2702 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002703 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002704 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 if (task == null) {
2706 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2707 return false;
2708 }
2709 if (DEBUG_STACK) Slog.d(TAG_STACK,
2710 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2711 + " to createMode=" + createMode + " toTop=" + toTop);
2712 if (!task.isActivityTypeStandardOrUndefined()) {
2713 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2714 + " non-standard task " + taskId + " to split-screen windowing mode");
2715 }
2716
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002717 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 final int windowingMode = task.getWindowingMode();
2719 final ActivityStack stack = task.getStack();
2720 if (toTop) {
2721 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2722 }
2723 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002724 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2725 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002726 return windowingMode != task.getWindowingMode();
2727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731 }
2732
2733 /**
2734 * Removes stacks in the input windowing modes from the system if they are of activity type
2735 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2736 */
2737 @Override
2738 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002739 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 "removeStacksInWindowingModes()");
2741
2742 synchronized (mGlobalLock) {
2743 final long ident = Binder.clearCallingIdentity();
2744 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002745 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 } finally {
2747 Binder.restoreCallingIdentity(ident);
2748 }
2749 }
2750 }
2751
2752 @Override
2753 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002754 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002755 "removeStacksWithActivityTypes()");
2756
2757 synchronized (mGlobalLock) {
2758 final long ident = Binder.clearCallingIdentity();
2759 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002760 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002761 } finally {
2762 Binder.restoreCallingIdentity(ident);
2763 }
2764 }
2765 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766
2767 @Override
2768 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2769 int userId) {
2770 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002771 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2772 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002774 final boolean detailed = checkGetTasksPermission(
2775 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2776 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 == PackageManager.PERMISSION_GRANTED;
2778
2779 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002780 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002781 callingUid);
2782 }
2783 }
2784
2785 @Override
2786 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002788 long ident = Binder.clearCallingIdentity();
2789 try {
2790 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002791 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 }
2793 } finally {
2794 Binder.restoreCallingIdentity(ident);
2795 }
2796 }
2797
2798 @Override
2799 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 long ident = Binder.clearCallingIdentity();
2802 try {
2803 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002804 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 }
2806 } finally {
2807 Binder.restoreCallingIdentity(ident);
2808 }
2809 }
2810
2811 @Override
2812 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002813 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 final long callingUid = Binder.getCallingUid();
2815 final long origId = Binder.clearCallingIdentity();
2816 try {
2817 synchronized (mGlobalLock) {
2818 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002819 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002820 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2821 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2822 }
2823 } finally {
2824 Binder.restoreCallingIdentity(origId);
2825 }
2826 }
2827
2828 @Override
2829 public void startLockTaskModeByToken(IBinder token) {
2830 synchronized (mGlobalLock) {
2831 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2832 if (r == null) {
2833 return;
2834 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002835 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 }
2837 }
2838
2839 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002840 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002841 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 // This makes inner call to look as if it was initiated by system.
2843 long ident = Binder.clearCallingIdentity();
2844 try {
2845 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002846 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002847 MATCH_TASK_IN_STACKS_ONLY);
2848 if (task == null) {
2849 return;
2850 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002851
2852 // When starting lock task mode the stack must be in front and focused
2853 task.getStack().moveToFront("startSystemLockTaskMode");
2854 startLockTaskModeLocked(task, true /* isSystemCaller */);
2855 }
2856 } finally {
2857 Binder.restoreCallingIdentity(ident);
2858 }
2859 }
2860
2861 @Override
2862 public void stopLockTaskModeByToken(IBinder token) {
2863 synchronized (mGlobalLock) {
2864 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2865 if (r == null) {
2866 return;
2867 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002868 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 }
2870 }
2871
2872 /**
2873 * This API should be called by SystemUI only when user perform certain action to dismiss
2874 * lock task mode. We should only dismiss pinned lock task mode in this case.
2875 */
2876 @Override
2877 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002878 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2880 }
2881
2882 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2883 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2884 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2885 return;
2886 }
2887
Wale Ogunwaled32da472018-11-16 07:19:28 -08002888 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002889 if (stack == null || task != stack.topTask()) {
2890 throw new IllegalArgumentException("Invalid task, not in foreground");
2891 }
2892
2893 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2894 // system or a specific app.
2895 // * System-initiated requests will only start the pinned mode (screen pinning)
2896 // * App-initiated requests
2897 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2898 // - will start the pinned mode, otherwise
2899 final int callingUid = Binder.getCallingUid();
2900 long ident = Binder.clearCallingIdentity();
2901 try {
2902 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002903 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002904
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002905 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 } finally {
2907 Binder.restoreCallingIdentity(ident);
2908 }
2909 }
2910
2911 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2912 final int callingUid = Binder.getCallingUid();
2913 long ident = Binder.clearCallingIdentity();
2914 try {
2915 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002916 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 }
2918 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2919 // task and jumping straight into a call in the case of emergency call back.
2920 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2921 if (tm != null) {
2922 tm.showInCallScreen(false);
2923 }
2924 } finally {
2925 Binder.restoreCallingIdentity(ident);
2926 }
2927 }
2928
2929 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002930 public void updateLockTaskPackages(int userId, String[] packages) {
2931 final int callingUid = Binder.getCallingUid();
2932 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2933 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2934 "updateLockTaskPackages()");
2935 }
2936 synchronized (this) {
2937 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2938 + Arrays.toString(packages));
2939 getLockTaskController().updateLockTaskPackages(userId, packages);
2940 }
2941 }
2942
2943 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 public boolean isInLockTaskMode() {
2945 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2946 }
2947
2948 @Override
2949 public int getLockTaskModeState() {
2950 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002951 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 }
2953 }
2954
2955 @Override
2956 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2957 synchronized (mGlobalLock) {
2958 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2959 if (r != null) {
2960 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002961 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002962 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002963 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 }
2965 }
2966 }
2967
2968 @Override
2969 public Bundle getActivityOptions(IBinder token) {
2970 final long origId = Binder.clearCallingIdentity();
2971 try {
2972 synchronized (mGlobalLock) {
2973 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2974 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002975 final ActivityOptions activityOptions = r.takeOptionsLocked(
2976 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 return activityOptions == null ? null : activityOptions.toBundle();
2978 }
2979 return null;
2980 }
2981 } finally {
2982 Binder.restoreCallingIdentity(origId);
2983 }
2984 }
2985
2986 @Override
2987 public List<IBinder> getAppTasks(String callingPackage) {
2988 int callingUid = Binder.getCallingUid();
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002989 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 long ident = Binder.clearCallingIdentity();
2991 try {
2992 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002993 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 }
2995 } finally {
2996 Binder.restoreCallingIdentity(ident);
2997 }
2998 }
2999
3000 @Override
3001 public void finishVoiceTask(IVoiceInteractionSession session) {
3002 synchronized (mGlobalLock) {
3003 final long origId = Binder.clearCallingIdentity();
3004 try {
3005 // TODO: VI Consider treating local voice interactions and voice tasks
3006 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003007 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 } finally {
3009 Binder.restoreCallingIdentity(origId);
3010 }
3011 }
3012
3013 }
3014
3015 @Override
3016 public boolean isTopOfTask(IBinder token) {
3017 synchronized (mGlobalLock) {
3018 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003019 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 }
3021 }
3022
3023 @Override
3024 public void notifyLaunchTaskBehindComplete(IBinder token) {
3025 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3026 }
3027
3028 @Override
3029 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003030 mH.post(() -> {
3031 synchronized (mGlobalLock) {
3032 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003033 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003034 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003035 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003036 } catch (RemoteException e) {
3037 }
3038 }
3039 }
3040
3041 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 }
3043
3044 /** Called from an app when assist data is ready. */
3045 @Override
3046 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3047 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003048 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049 synchronized (pae) {
3050 pae.result = extras;
3051 pae.structure = structure;
3052 pae.content = content;
3053 if (referrer != null) {
3054 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3055 }
3056 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003057 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003058 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3059 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 structure.setHomeActivity(pae.isHome);
3061 }
3062 pae.haveResult = true;
3063 pae.notifyAll();
3064 if (pae.intent == null && pae.receiver == null) {
3065 // Caller is just waiting for the result.
3066 return;
3067 }
3068 }
3069 // We are now ready to launch the assist activity.
3070 IAssistDataReceiver sendReceiver = null;
3071 Bundle sendBundle = null;
3072 synchronized (mGlobalLock) {
3073 buildAssistBundleLocked(pae, extras);
3074 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003075 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 if (!exists) {
3077 // Timed out.
3078 return;
3079 }
3080
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003081 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003082 // Caller wants result sent back to them.
3083 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003084 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3085 pae.activity.getTaskRecord().taskId);
3086 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3087 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003088 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3089 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3090 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3091 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3092 }
3093 }
3094 if (sendReceiver != null) {
3095 try {
3096 sendReceiver.onHandleAssistData(sendBundle);
3097 } catch (RemoteException e) {
3098 }
3099 return;
3100 }
3101
3102 final long ident = Binder.clearCallingIdentity();
3103 try {
3104 if (TextUtils.equals(pae.intent.getAction(),
3105 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003106 // Start voice interaction through VoiceInteractionManagerService.
3107 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3108 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 } else {
3110 pae.intent.replaceExtras(pae.extras);
3111 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3112 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3113 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003114 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115
3116 try {
3117 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3118 } catch (ActivityNotFoundException e) {
3119 Slog.w(TAG, "No activity to handle assist action.", e);
3120 }
3121 }
3122 } finally {
3123 Binder.restoreCallingIdentity(ident);
3124 }
3125 }
3126
3127 @Override
3128 public int addAppTask(IBinder activityToken, Intent intent,
3129 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3130 final int callingUid = Binder.getCallingUid();
3131 final long callingIdent = Binder.clearCallingIdentity();
3132
3133 try {
3134 synchronized (mGlobalLock) {
3135 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3136 if (r == null) {
3137 throw new IllegalArgumentException("Activity does not exist; token="
3138 + activityToken);
3139 }
3140 ComponentName comp = intent.getComponent();
3141 if (comp == null) {
3142 throw new IllegalArgumentException("Intent " + intent
3143 + " must specify explicit component");
3144 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003145 if (thumbnail.getWidth() != mThumbnailWidth
3146 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 throw new IllegalArgumentException("Bad thumbnail size: got "
3148 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003149 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 }
3151 if (intent.getSelector() != null) {
3152 intent.setSelector(null);
3153 }
3154 if (intent.getSourceBounds() != null) {
3155 intent.setSourceBounds(null);
3156 }
3157 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3158 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3159 // The caller has added this as an auto-remove task... that makes no
3160 // sense, so turn off auto-remove.
3161 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3162 }
3163 }
3164 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3165 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3166 if (ainfo.applicationInfo.uid != callingUid) {
3167 throw new SecurityException(
3168 "Can't add task for another application: target uid="
3169 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3170 }
3171
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003172 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003174 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003176 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 // The app has too many tasks already and we can't add any more
3178 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3179 return INVALID_TASK_ID;
3180 }
3181 task.lastTaskDescription.copyFrom(description);
3182
3183 // TODO: Send the thumbnail to WM to store it.
3184
3185 return task.taskId;
3186 }
3187 } finally {
3188 Binder.restoreCallingIdentity(callingIdent);
3189 }
3190 }
3191
3192 @Override
3193 public Point getAppTaskThumbnailSize() {
3194 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003195 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 }
3198
3199 @Override
3200 public void setTaskResizeable(int taskId, int resizeableMode) {
3201 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003202 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3204 if (task == null) {
3205 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3206 return;
3207 }
3208 task.setResizeMode(resizeableMode);
3209 }
3210 }
3211
3212 @Override
3213 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003214 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 long ident = Binder.clearCallingIdentity();
3216 try {
3217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003218 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003219 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 if (task == null) {
3221 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3222 return;
3223 }
3224 // Place the task in the right stack if it isn't there already based on
3225 // the requested bounds.
3226 // The stack transition logic is:
3227 // - a null bounds on a freeform task moves that task to fullscreen
3228 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3229 // that task to freeform
3230 // - otherwise the task is not moved
3231 ActivityStack stack = task.getStack();
3232 if (!task.getWindowConfiguration().canResizeTask()) {
3233 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3234 }
3235 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3236 stack = stack.getDisplay().getOrCreateStack(
3237 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3238 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3239 stack = stack.getDisplay().getOrCreateStack(
3240 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3241 }
3242
3243 // Reparent the task to the right stack if necessary
3244 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3245 if (stack != task.getStack()) {
3246 // Defer resume until the task is resized below
3247 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3248 DEFER_RESUME, "resizeTask");
3249 preserveWindow = false;
3250 }
3251
3252 // After reparenting (which only resizes the task to the stack bounds), resize the
3253 // task to the actual bounds provided
3254 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3255 }
3256 } finally {
3257 Binder.restoreCallingIdentity(ident);
3258 }
3259 }
3260
3261 @Override
3262 public boolean releaseActivityInstance(IBinder token) {
3263 synchronized (mGlobalLock) {
3264 final long origId = Binder.clearCallingIdentity();
3265 try {
3266 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3267 if (r == null) {
3268 return false;
3269 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003270 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 } finally {
3272 Binder.restoreCallingIdentity(origId);
3273 }
3274 }
3275 }
3276
3277 @Override
3278 public void releaseSomeActivities(IApplicationThread appInt) {
3279 synchronized (mGlobalLock) {
3280 final long origId = Binder.clearCallingIdentity();
3281 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003282 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003283 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 } finally {
3285 Binder.restoreCallingIdentity(origId);
3286 }
3287 }
3288 }
3289
3290 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003291 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 != PackageManager.PERMISSION_GRANTED) {
3294 throw new SecurityException("Requires permission "
3295 + android.Manifest.permission.DEVICE_POWER);
3296 }
3297
3298 synchronized (mGlobalLock) {
3299 long ident = Binder.clearCallingIdentity();
3300 if (mKeyguardShown != keyguardShowing) {
3301 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003302 final Message msg = PooledLambda.obtainMessage(
3303 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3304 keyguardShowing);
3305 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 }
3307 try {
wilsonshih177261f2019-02-22 12:02:18 +08003308 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 } finally {
3310 Binder.restoreCallingIdentity(ident);
3311 }
3312 }
3313
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 mH.post(() -> {
3315 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3316 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3317 }
3318 });
3319 }
3320
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003321 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003322 mH.post(() -> {
3323 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3324 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3325 }
3326 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 }
3328
3329 @Override
3330 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3332 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333
3334 final File passedIconFile = new File(filePath);
3335 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3336 passedIconFile.getName());
3337 if (!legitIconFile.getPath().equals(filePath)
3338 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3339 throw new IllegalArgumentException("Bad file path: " + filePath
3340 + " passed for userId " + userId);
3341 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003342 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 }
3344
3345 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003346 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3348 final ActivityOptions activityOptions = safeOptions != null
3349 ? safeOptions.getOptions(mStackSupervisor)
3350 : null;
3351 if (activityOptions == null
3352 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3353 || activityOptions.getCustomInPlaceResId() == 0) {
3354 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3355 "with valid animation");
3356 }
lumark588a3e82018-07-20 18:53:54 +08003357 // Get top display of front most application.
3358 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3359 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003360 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3361 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3362 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003363 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003364 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003365 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 }
3367
3368 @Override
3369 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 synchronized (mGlobalLock) {
3372 final long ident = Binder.clearCallingIdentity();
3373 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003374 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 if (stack == null) {
3376 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3377 return;
3378 }
3379 if (!stack.isActivityTypeStandardOrUndefined()) {
3380 throw new IllegalArgumentException(
3381 "Removing non-standard stack is not allowed.");
3382 }
3383 mStackSupervisor.removeStack(stack);
3384 } finally {
3385 Binder.restoreCallingIdentity(ident);
3386 }
3387 }
3388 }
3389
3390 @Override
3391 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003392 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393
3394 synchronized (mGlobalLock) {
3395 final long ident = Binder.clearCallingIdentity();
3396 try {
3397 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3398 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003399 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
3403 }
3404 }
3405
3406 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003407 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 synchronized (mGlobalLock) {
3409 long ident = Binder.clearCallingIdentity();
3410 try {
3411 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3412 if (r == null) {
3413 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003414 "toggleFreeformWindowingMode: No activity record matching token="
3415 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 }
3417
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003418 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003419 if (stack == null) {
3420 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3421 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423
Yunfan Chend967af82019-01-17 18:30:18 +09003424 if (!stack.inFreeformWindowingMode()
3425 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3426 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3427 + "toggle between fullscreen and freeform.");
3428 }
3429
3430 if (stack.inFreeformWindowingMode()) {
3431 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003432 } else if (stack.getParent().inFreeformWindowingMode()) {
3433 // If the window is on a freeform display, set it to undefined. It will be
3434 // resolved to freeform and it can adjust windowing mode when the display mode
3435 // changes in runtime.
3436 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003437 } else {
3438 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3439 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 } finally {
3441 Binder.restoreCallingIdentity(ident);
3442 }
3443 }
3444 }
3445
3446 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3447 @Override
3448 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003449 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003450 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003451 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003452 }
3453
3454 /** Unregister a task stack listener so that it stops receiving callbacks. */
3455 @Override
3456 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003459 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460 }
3461
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 @Override
3463 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3464 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3465 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3466 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3467 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3468 }
3469
3470 @Override
3471 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3472 IBinder activityToken, int flags) {
3473 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3474 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3475 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3476 }
3477
3478 @Override
3479 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3480 Bundle args) {
3481 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3482 true /* focused */, true /* newSessionId */, userHandle, args,
3483 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3484 }
3485
3486 @Override
3487 public Bundle getAssistContextExtras(int requestType) {
3488 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3489 null, null, true /* focused */, true /* newSessionId */,
3490 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3491 if (pae == null) {
3492 return null;
3493 }
3494 synchronized (pae) {
3495 while (!pae.haveResult) {
3496 try {
3497 pae.wait();
3498 } catch (InterruptedException e) {
3499 }
3500 }
3501 }
3502 synchronized (mGlobalLock) {
3503 buildAssistBundleLocked(pae, pae.result);
3504 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003505 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 }
3507 return pae.extras;
3508 }
3509
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003510 /**
3511 * Binder IPC calls go through the public entry point.
3512 * This can be called with or without the global lock held.
3513 */
3514 private static int checkCallingPermission(String permission) {
3515 return checkPermission(
3516 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3517 }
3518
3519 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003520 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003521 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3522 mAmInternal.enforceCallingPermission(permission, func);
3523 }
3524 }
3525
3526 @VisibleForTesting
3527 int checkGetTasksPermission(String permission, int pid, int uid) {
3528 return checkPermission(permission, pid, uid);
3529 }
3530
3531 static int checkPermission(String permission, int pid, int uid) {
3532 if (permission == null) {
3533 return PackageManager.PERMISSION_DENIED;
3534 }
3535 return checkComponentPermission(permission, pid, uid, -1, true);
3536 }
3537
Wale Ogunwale214f3482018-10-04 11:00:47 -07003538 public static int checkComponentPermission(String permission, int pid, int uid,
3539 int owningUid, boolean exported) {
3540 return ActivityManagerService.checkComponentPermission(
3541 permission, pid, uid, owningUid, exported);
3542 }
3543
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003544 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3545 if (getRecentTasks().isCallerRecents(callingUid)) {
3546 // Always allow the recents component to get tasks
3547 return true;
3548 }
3549
3550 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3551 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3552 if (!allowed) {
3553 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3554 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3555 // Temporary compatibility: some existing apps on the system image may
3556 // still be requesting the old permission and not switched to the new
3557 // one; if so, we'll still allow them full access. This means we need
3558 // to see if they are holding the old permission and are a system app.
3559 try {
3560 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3561 allowed = true;
3562 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3563 + " is using old GET_TASKS but privileged; allowing");
3564 }
3565 } catch (RemoteException e) {
3566 }
3567 }
3568 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3569 + " does not hold REAL_GET_TASKS; limiting output");
3570 }
3571 return allowed;
3572 }
3573
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3575 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3576 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3577 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003578 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579 "enqueueAssistContext()");
3580
3581 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003582 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003583 if (activity == null) {
3584 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3585 return null;
3586 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003587 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3589 return null;
3590 }
3591 if (focused) {
3592 if (activityToken != null) {
3593 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3594 if (activity != caller) {
3595 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3596 + " is not current top " + activity);
3597 return null;
3598 }
3599 }
3600 } else {
3601 activity = ActivityRecord.forTokenLocked(activityToken);
3602 if (activity == null) {
3603 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3604 + " couldn't be found");
3605 return null;
3606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3609 return null;
3610 }
3611 }
3612
3613 PendingAssistExtras pae;
3614 Bundle extras = new Bundle();
3615 if (args != null) {
3616 extras.putAll(args);
3617 }
3618 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003619 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620
3621 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3622 userHandle);
3623 pae.isHome = activity.isActivityTypeHome();
3624
3625 // Increment the sessionId if necessary
3626 if (newSessionId) {
3627 mViSessionId++;
3628 }
3629 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003630 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3631 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003633 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003634 } catch (RemoteException e) {
3635 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3636 return null;
3637 }
3638 return pae;
3639 }
3640 }
3641
3642 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3643 if (result != null) {
3644 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3645 }
3646 if (pae.hint != null) {
3647 pae.extras.putBoolean(pae.hint, true);
3648 }
3649 }
3650
3651 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3652 IAssistDataReceiver receiver;
3653 synchronized (mGlobalLock) {
3654 mPendingAssistExtras.remove(pae);
3655 receiver = pae.receiver;
3656 }
3657 if (receiver != null) {
3658 // Caller wants result sent back to them.
3659 Bundle sendBundle = new Bundle();
3660 // At least return the receiver extras
3661 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3662 try {
3663 pae.receiver.onHandleAssistData(sendBundle);
3664 } catch (RemoteException e) {
3665 }
3666 }
3667 }
3668
3669 public class PendingAssistExtras extends Binder implements Runnable {
3670 public final ActivityRecord activity;
3671 public boolean isHome;
3672 public final Bundle extras;
3673 public final Intent intent;
3674 public final String hint;
3675 public final IAssistDataReceiver receiver;
3676 public final int userHandle;
3677 public boolean haveResult = false;
3678 public Bundle result = null;
3679 public AssistStructure structure = null;
3680 public AssistContent content = null;
3681 public Bundle receiverExtras;
3682
3683 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3684 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3685 int _userHandle) {
3686 activity = _activity;
3687 extras = _extras;
3688 intent = _intent;
3689 hint = _hint;
3690 receiver = _receiver;
3691 receiverExtras = _receiverExtras;
3692 userHandle = _userHandle;
3693 }
3694
3695 @Override
3696 public void run() {
3697 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3698 synchronized (this) {
3699 haveResult = true;
3700 notifyAll();
3701 }
3702 pendingAssistExtrasTimedOut(this);
3703 }
3704 }
3705
3706 @Override
3707 public boolean isAssistDataAllowedOnCurrentActivity() {
3708 int userId;
3709 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003710 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3712 return false;
3713 }
3714
3715 final ActivityRecord activity = focusedStack.getTopActivity();
3716 if (activity == null) {
3717 return false;
3718 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003719 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003720 }
3721 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3722 }
3723
3724 @Override
3725 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3726 long ident = Binder.clearCallingIdentity();
3727 try {
3728 synchronized (mGlobalLock) {
3729 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003730 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 if (top != caller) {
3732 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3733 + " is not current top " + top);
3734 return false;
3735 }
3736 if (!top.nowVisible) {
3737 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3738 + " is not visible");
3739 return false;
3740 }
3741 }
3742 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3743 token);
3744 } finally {
3745 Binder.restoreCallingIdentity(ident);
3746 }
3747 }
3748
3749 @Override
3750 public boolean isRootVoiceInteraction(IBinder token) {
3751 synchronized (mGlobalLock) {
3752 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3753 if (r == null) {
3754 return false;
3755 }
3756 return r.rootVoiceInteraction;
3757 }
3758 }
3759
Wale Ogunwalef6733932018-06-27 05:14:34 -07003760 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3761 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3762 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3763 if (activityToCallback == null) return;
3764 activityToCallback.setVoiceSessionLocked(voiceSession);
3765
3766 // Inform the activity
3767 try {
3768 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3769 voiceInteractor);
3770 long token = Binder.clearCallingIdentity();
3771 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003772 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003773 } finally {
3774 Binder.restoreCallingIdentity(token);
3775 }
3776 // TODO: VI Should we cache the activity so that it's easier to find later
3777 // rather than scan through all the stacks and activities?
3778 } catch (RemoteException re) {
3779 activityToCallback.clearVoiceSessionLocked();
3780 // TODO: VI Should this terminate the voice session?
3781 }
3782 }
3783
3784 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3785 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3786 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3787 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3788 boolean wasRunningVoice = mRunningVoice != null;
3789 mRunningVoice = session;
3790 if (!wasRunningVoice) {
3791 mVoiceWakeLock.acquire();
3792 updateSleepIfNeededLocked();
3793 }
3794 }
3795 }
3796
3797 void finishRunningVoiceLocked() {
3798 if (mRunningVoice != null) {
3799 mRunningVoice = null;
3800 mVoiceWakeLock.release();
3801 updateSleepIfNeededLocked();
3802 }
3803 }
3804
3805 @Override
3806 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3807 synchronized (mGlobalLock) {
3808 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3809 if (keepAwake) {
3810 mVoiceWakeLock.acquire();
3811 } else {
3812 mVoiceWakeLock.release();
3813 }
3814 }
3815 }
3816 }
3817
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 @Override
3819 public ComponentName getActivityClassForToken(IBinder token) {
3820 synchronized (mGlobalLock) {
3821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3822 if (r == null) {
3823 return null;
3824 }
3825 return r.intent.getComponent();
3826 }
3827 }
3828
3829 @Override
3830 public String getPackageForToken(IBinder token) {
3831 synchronized (mGlobalLock) {
3832 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3833 if (r == null) {
3834 return null;
3835 }
3836 return r.packageName;
3837 }
3838 }
3839
3840 @Override
3841 public void showLockTaskEscapeMessage(IBinder token) {
3842 synchronized (mGlobalLock) {
3843 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3844 if (r == null) {
3845 return;
3846 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003847 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 }
3849 }
3850
3851 @Override
3852 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003853 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854 final long token = Binder.clearCallingIdentity();
3855 try {
3856 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003857 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 }
3859 } finally {
3860 Binder.restoreCallingIdentity(token);
3861 }
3862 }
3863
3864 /**
3865 * Try to place task to provided position. The final position might be different depending on
3866 * current user and stacks state. The task will be moved to target stack if it's currently in
3867 * different stack.
3868 */
3869 @Override
3870 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003871 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 synchronized (mGlobalLock) {
3873 long ident = Binder.clearCallingIdentity();
3874 try {
3875 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3876 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003877 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 if (task == null) {
3879 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3880 + taskId);
3881 }
3882
Wale Ogunwaled32da472018-11-16 07:19:28 -08003883 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884
3885 if (stack == null) {
3886 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3887 + stackId);
3888 }
3889 if (!stack.isActivityTypeStandardOrUndefined()) {
3890 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3891 + " the position of task " + taskId + " in/to non-standard stack");
3892 }
3893
3894 // TODO: Have the callers of this API call a separate reparent method if that is
3895 // what they intended to do vs. having this method also do reparenting.
3896 if (task.getStack() == stack) {
3897 // Change position in current stack.
3898 stack.positionChildAt(task, position);
3899 } else {
3900 // Reparent to new stack.
3901 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3902 !DEFER_RESUME, "positionTaskInStack");
3903 }
3904 } finally {
3905 Binder.restoreCallingIdentity(ident);
3906 }
3907 }
3908 }
3909
3910 @Override
3911 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3912 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3913 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003914 + Arrays.toString(horizontalSizeConfiguration) + " "
3915 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 synchronized (mGlobalLock) {
3917 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3918 if (record == null) {
3919 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3920 + "found for: " + token);
3921 }
3922 record.setSizeConfigurations(horizontalSizeConfiguration,
3923 verticalSizeConfigurations, smallestSizeConfigurations);
3924 }
3925 }
3926
3927 /**
3928 * Dismisses split-screen multi-window mode.
3929 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3930 */
3931 @Override
3932 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003933 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3935 final long ident = Binder.clearCallingIdentity();
3936 try {
3937 synchronized (mGlobalLock) {
3938 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003939 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 if (stack == null) {
3941 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3942 return;
3943 }
3944
3945 if (toTop) {
3946 // Caller wants the current split-screen primary stack to be the top stack after
3947 // it goes fullscreen, so move it to the front.
3948 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003949 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003951 // stack after it goes fullscreen, so we move the focus to the top-most
3952 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3954 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3955 if (otherStack != null) {
3956 otherStack.moveToFront("dismissSplitScreenMode_other");
3957 }
3958 }
3959
Evan Rosky10475742018-09-05 19:02:48 -07003960 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 }
3962 } finally {
3963 Binder.restoreCallingIdentity(ident);
3964 }
3965 }
3966
3967 /**
3968 * Dismisses Pip
3969 * @param animate True if the dismissal should be animated.
3970 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3971 * default animation duration should be used.
3972 */
3973 @Override
3974 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003975 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 final long ident = Binder.clearCallingIdentity();
3977 try {
3978 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003979 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003980 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 if (stack == null) {
3982 Slog.w(TAG, "dismissPip: pinned stack not found.");
3983 return;
3984 }
3985 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3986 throw new IllegalArgumentException("Stack: " + stack
3987 + " doesn't support animated resize.");
3988 }
3989 if (animate) {
3990 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3991 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3992 } else {
3993 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3994 }
3995 }
3996 } finally {
3997 Binder.restoreCallingIdentity(ident);
3998 }
3999 }
4000
4001 @Override
4002 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004003 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004004 synchronized (mGlobalLock) {
4005 mSuppressResizeConfigChanges = suppress;
4006 }
4007 }
4008
4009 /**
4010 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4011 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4012 * activity and clearing the task at the same time.
4013 */
4014 @Override
4015 // TODO: API should just be about changing windowing modes...
4016 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004017 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 "moveTasksToFullscreenStack()");
4019 synchronized (mGlobalLock) {
4020 final long origId = Binder.clearCallingIdentity();
4021 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004022 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 if (stack != null){
4024 if (!stack.isActivityTypeStandardOrUndefined()) {
4025 throw new IllegalArgumentException(
4026 "You can't move tasks from non-standard stacks.");
4027 }
4028 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4029 }
4030 } finally {
4031 Binder.restoreCallingIdentity(origId);
4032 }
4033 }
4034 }
4035
4036 /**
4037 * Moves the top activity in the input stackId to the pinned stack.
4038 *
4039 * @param stackId Id of stack to move the top activity to pinned stack.
4040 * @param bounds Bounds to use for pinned stack.
4041 *
4042 * @return True if the top activity of the input stack was successfully moved to the pinned
4043 * stack.
4044 */
4045 @Override
4046 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004047 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004048 "moveTopActivityToPinnedStack()");
4049 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4052 + "Device doesn't support picture-in-picture mode");
4053 }
4054
4055 long ident = Binder.clearCallingIdentity();
4056 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004057 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004058 } finally {
4059 Binder.restoreCallingIdentity(ident);
4060 }
4061 }
4062 }
4063
4064 @Override
4065 public boolean isInMultiWindowMode(IBinder token) {
4066 final long origId = Binder.clearCallingIdentity();
4067 try {
4068 synchronized (mGlobalLock) {
4069 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4070 if (r == null) {
4071 return false;
4072 }
4073 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4074 return r.inMultiWindowMode();
4075 }
4076 } finally {
4077 Binder.restoreCallingIdentity(origId);
4078 }
4079 }
4080
4081 @Override
4082 public boolean isInPictureInPictureMode(IBinder token) {
4083 final long origId = Binder.clearCallingIdentity();
4084 try {
4085 synchronized (mGlobalLock) {
4086 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4087 }
4088 } finally {
4089 Binder.restoreCallingIdentity(origId);
4090 }
4091 }
4092
4093 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004094 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4095 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004096 return false;
4097 }
4098
4099 // If we are animating to fullscreen then we have already dispatched the PIP mode
4100 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004101 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4102 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 }
4104
4105 @Override
4106 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4107 final long origId = Binder.clearCallingIdentity();
4108 try {
4109 synchronized (mGlobalLock) {
4110 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4111 "enterPictureInPictureMode", token, params);
4112
4113 // If the activity is already in picture in picture mode, then just return early
4114 if (isInPictureInPictureMode(r)) {
4115 return true;
4116 }
4117
4118 // Activity supports picture-in-picture, now check that we can enter PiP at this
4119 // point, if it is
4120 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4121 false /* beforeStopping */)) {
4122 return false;
4123 }
4124
4125 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004126 synchronized (mGlobalLock) {
4127 // Only update the saved args from the args that are set
4128 r.pictureInPictureArgs.copyOnlySet(params);
4129 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4130 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4131 // Adjust the source bounds by the insets for the transition down
4132 final Rect sourceBounds = new Rect(
4133 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004134 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004135 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004136 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004137 stack.setPictureInPictureAspectRatio(aspectRatio);
4138 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004139 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4140 r.info.applicationInfo.uid, r.shortComponentName,
4141 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004142 logPictureInPictureArgs(params);
4143 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 };
4145
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004146 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 // If the keyguard is showing or occluded, then try and dismiss it before
4148 // entering picture-in-picture (this will prompt the user to authenticate if the
4149 // device is currently locked).
4150 dismissKeyguard(token, new KeyguardDismissCallback() {
4151 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004152 public void onDismissSucceeded() {
4153 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 }
4155 }, null /* message */);
4156 } else {
4157 // Enter picture in picture immediately otherwise
4158 enterPipRunnable.run();
4159 }
4160 return true;
4161 }
4162 } finally {
4163 Binder.restoreCallingIdentity(origId);
4164 }
4165 }
4166
4167 @Override
4168 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4169 final long origId = Binder.clearCallingIdentity();
4170 try {
4171 synchronized (mGlobalLock) {
4172 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4173 "setPictureInPictureParams", token, params);
4174
4175 // Only update the saved args from the args that are set
4176 r.pictureInPictureArgs.copyOnlySet(params);
4177 if (r.inPinnedWindowingMode()) {
4178 // If the activity is already in picture-in-picture, update the pinned stack now
4179 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4180 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004181 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 if (!stack.isAnimatingBoundsToFullscreen()) {
4183 stack.setPictureInPictureAspectRatio(
4184 r.pictureInPictureArgs.getAspectRatio());
4185 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4186 }
4187 }
4188 logPictureInPictureArgs(params);
4189 }
4190 } finally {
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194
4195 @Override
4196 public int getMaxNumPictureInPictureActions(IBinder token) {
4197 // Currently, this is a static constant, but later, we may change this to be dependent on
4198 // the context of the activity
4199 return 3;
4200 }
4201
4202 private void logPictureInPictureArgs(PictureInPictureParams params) {
4203 if (params.hasSetActions()) {
4204 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4205 params.getActions().size());
4206 }
4207 if (params.hasSetAspectRatio()) {
4208 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4209 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4210 MetricsLogger.action(lm);
4211 }
4212 }
4213
4214 /**
4215 * Checks the state of the system and the activity associated with the given {@param token} to
4216 * verify that picture-in-picture is supported for that activity.
4217 *
4218 * @return the activity record for the given {@param token} if all the checks pass.
4219 */
4220 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4221 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004222 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004223 throw new IllegalStateException(caller
4224 + ": Device doesn't support picture-in-picture mode.");
4225 }
4226
4227 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4228 if (r == null) {
4229 throw new IllegalStateException(caller
4230 + ": Can't find activity for token=" + token);
4231 }
4232
4233 if (!r.supportsPictureInPicture()) {
4234 throw new IllegalStateException(caller
4235 + ": Current activity does not support picture-in-picture.");
4236 }
4237
4238 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004239 && !mWindowManager.isValidPictureInPictureAspectRatio(
4240 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 final float minAspectRatio = mContext.getResources().getFloat(
4242 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4243 final float maxAspectRatio = mContext.getResources().getFloat(
4244 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4245 throw new IllegalArgumentException(String.format(caller
4246 + ": Aspect ratio is too extreme (must be between %f and %f).",
4247 minAspectRatio, maxAspectRatio));
4248 }
4249
4250 // Truncate the number of actions if necessary
4251 params.truncateActions(getMaxNumPictureInPictureActions(token));
4252
4253 return r;
4254 }
4255
4256 @Override
4257 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 synchronized (mGlobalLock) {
4260 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4261 if (r == null) {
4262 throw new IllegalArgumentException("Activity does not exist; token="
4263 + activityToken);
4264 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004265 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 }
4267 }
4268
4269 @Override
4270 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4271 Rect tempDockedTaskInsetBounds,
4272 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 long ident = Binder.clearCallingIdentity();
4275 try {
4276 synchronized (mGlobalLock) {
4277 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4278 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4279 PRESERVE_WINDOWS);
4280 }
4281 } finally {
4282 Binder.restoreCallingIdentity(ident);
4283 }
4284 }
4285
4286 @Override
4287 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004288 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 final long ident = Binder.clearCallingIdentity();
4290 try {
4291 synchronized (mGlobalLock) {
4292 mStackSupervisor.setSplitScreenResizing(resizing);
4293 }
4294 } finally {
4295 Binder.restoreCallingIdentity(ident);
4296 }
4297 }
4298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 /**
4300 * Check that we have the features required for VR-related API calls, and throw an exception if
4301 * not.
4302 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004303 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004304 if (!mContext.getPackageManager().hasSystemFeature(
4305 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4306 throw new UnsupportedOperationException("VR mode not supported on this device!");
4307 }
4308 }
4309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 @Override
4311 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004312 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313
4314 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4315
4316 ActivityRecord r;
4317 synchronized (mGlobalLock) {
4318 r = ActivityRecord.isInStackLocked(token);
4319 }
4320
4321 if (r == null) {
4322 throw new IllegalArgumentException();
4323 }
4324
4325 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004326 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 VrManagerInternal.NO_ERROR) {
4328 return err;
4329 }
4330
4331 // Clear the binder calling uid since this path may call moveToTask().
4332 final long callingId = Binder.clearCallingIdentity();
4333 try {
4334 synchronized (mGlobalLock) {
4335 r.requestedVrComponent = (enabled) ? packageName : null;
4336
4337 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004338 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004339 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 }
4341 return 0;
4342 }
4343 } finally {
4344 Binder.restoreCallingIdentity(callingId);
4345 }
4346 }
4347
4348 @Override
4349 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4350 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4351 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004352 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004353 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4354 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4355 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004356 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004357 || activity.voiceSession != null) {
4358 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4359 return;
4360 }
4361 if (activity.pendingVoiceInteractionStart) {
4362 Slog.w(TAG, "Pending start of voice interaction already.");
4363 return;
4364 }
4365 activity.pendingVoiceInteractionStart = true;
4366 }
4367 LocalServices.getService(VoiceInteractionManagerInternal.class)
4368 .startLocalVoiceInteraction(callingActivity, options);
4369 }
4370
4371 @Override
4372 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4373 LocalServices.getService(VoiceInteractionManagerInternal.class)
4374 .stopLocalVoiceInteraction(callingActivity);
4375 }
4376
4377 @Override
4378 public boolean supportsLocalVoiceInteraction() {
4379 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4380 .supportsLocalVoiceInteraction();
4381 }
4382
4383 /** Notifies all listeners when the pinned stack animation starts. */
4384 @Override
4385 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004386 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 }
4388
4389 /** Notifies all listeners when the pinned stack animation ends. */
4390 @Override
4391 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004392 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 }
4394
4395 @Override
4396 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004397 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 final long ident = Binder.clearCallingIdentity();
4399 try {
4400 synchronized (mGlobalLock) {
4401 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4402 }
4403 } finally {
4404 Binder.restoreCallingIdentity(ident);
4405 }
4406 }
4407
4408 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004410 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411
4412 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004415 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 }
4417
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004418 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004419 final Message msg = PooledLambda.obtainMessage(
4420 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4421 DEFAULT_DISPLAY);
4422 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 }
4424
4425 final long origId = Binder.clearCallingIdentity();
4426 try {
4427 if (values != null) {
4428 Settings.System.clearConfiguration(values);
4429 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 UserHandle.USER_NULL, false /* deferResume */,
4432 mTmpUpdateConfigurationResult);
4433 return mTmpUpdateConfigurationResult.changes != 0;
4434 } finally {
4435 Binder.restoreCallingIdentity(origId);
4436 }
4437 }
4438 }
4439
4440 @Override
4441 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4442 CharSequence message) {
4443 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4446 }
4447 final long callingId = Binder.clearCallingIdentity();
4448 try {
4449 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004450 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 }
4452 } finally {
4453 Binder.restoreCallingIdentity(callingId);
4454 }
4455 }
4456
4457 @Override
4458 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 "cancelTaskWindowTransition()");
4461 final long ident = Binder.clearCallingIdentity();
4462 try {
4463 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004464 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 MATCH_TASK_IN_STACKS_ONLY);
4466 if (task == null) {
4467 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4468 return;
4469 }
4470 task.cancelWindowTransition();
4471 }
4472 } finally {
4473 Binder.restoreCallingIdentity(ident);
4474 }
4475 }
4476
4477 @Override
4478 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 final long ident = Binder.clearCallingIdentity();
4481 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004482 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 } finally {
4484 Binder.restoreCallingIdentity(ident);
4485 }
4486 }
4487
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004488 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4489 boolean restoreFromDisk) {
4490 final TaskRecord task;
4491 synchronized (mGlobalLock) {
4492 task = mRootActivityContainer.anyTaskForId(taskId,
4493 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4494 if (task == null) {
4495 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4496 return null;
4497 }
4498 }
4499 // Don't call this while holding the lock as this operation might hit the disk.
4500 return task.getSnapshot(reducedResolution, restoreFromDisk);
4501 }
4502
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 @Override
4504 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4505 synchronized (mGlobalLock) {
4506 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4507 if (r == null) {
4508 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4509 + token);
4510 return;
4511 }
4512 final long origId = Binder.clearCallingIdentity();
4513 try {
4514 r.setDisablePreviewScreenshots(disable);
4515 } finally {
4516 Binder.restoreCallingIdentity(origId);
4517 }
4518 }
4519 }
4520
4521 /** Return the user id of the last resumed activity. */
4522 @Override
4523 public @UserIdInt
4524 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004525 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004526 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4527 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004528 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004529 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004530 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004531 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004532 }
4533 }
4534
4535 @Override
4536 public void updateLockTaskFeatures(int userId, int flags) {
4537 final int callingUid = Binder.getCallingUid();
4538 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004539 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 "updateLockTaskFeatures()");
4541 }
4542 synchronized (mGlobalLock) {
4543 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4544 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004545 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004546 }
4547 }
4548
4549 @Override
4550 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4551 synchronized (mGlobalLock) {
4552 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4553 if (r == null) {
4554 return;
4555 }
4556 final long origId = Binder.clearCallingIdentity();
4557 try {
4558 r.setShowWhenLocked(showWhenLocked);
4559 } finally {
4560 Binder.restoreCallingIdentity(origId);
4561 }
4562 }
4563 }
4564
4565 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004566 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4567 synchronized (mGlobalLock) {
4568 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4569 if (r == null) {
4570 return;
4571 }
4572 final long origId = Binder.clearCallingIdentity();
4573 try {
4574 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4575 } finally {
4576 Binder.restoreCallingIdentity(origId);
4577 }
4578 }
4579 }
4580
4581 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4583 synchronized (mGlobalLock) {
4584 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4585 if (r == null) {
4586 return;
4587 }
4588 final long origId = Binder.clearCallingIdentity();
4589 try {
4590 r.setTurnScreenOn(turnScreenOn);
4591 } finally {
4592 Binder.restoreCallingIdentity(origId);
4593 }
4594 }
4595 }
4596
4597 @Override
4598 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004599 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 "registerRemoteAnimations");
4601 definition.setCallingPid(Binder.getCallingPid());
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.registerRemoteAnimations(definition);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
4617 public void registerRemoteAnimationForNextActivityStart(String packageName,
4618 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004619 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004620 "registerRemoteAnimationForNextActivityStart");
4621 adapter.setCallingPid(Binder.getCallingPid());
4622 synchronized (mGlobalLock) {
4623 final long origId = Binder.clearCallingIdentity();
4624 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004625 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004626 packageName, adapter);
4627 } finally {
4628 Binder.restoreCallingIdentity(origId);
4629 }
4630 }
4631 }
4632
Evan Rosky966759f2019-01-15 10:33:58 -08004633 @Override
4634 public void registerRemoteAnimationsForDisplay(int displayId,
4635 RemoteAnimationDefinition definition) {
4636 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4637 "registerRemoteAnimations");
4638 definition.setCallingPid(Binder.getCallingPid());
4639 synchronized (mGlobalLock) {
4640 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4641 if (display == null) {
4642 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4643 return;
4644 }
4645 final long origId = Binder.clearCallingIdentity();
4646 try {
4647 display.mDisplayContent.registerRemoteAnimations(definition);
4648 } finally {
4649 Binder.restoreCallingIdentity(origId);
4650 }
4651 }
4652 }
4653
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004654 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4655 @Override
4656 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4657 synchronized (mGlobalLock) {
4658 final long origId = Binder.clearCallingIdentity();
4659 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004660 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004661 } finally {
4662 Binder.restoreCallingIdentity(origId);
4663 }
4664 }
4665 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004666
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004667 @Override
4668 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004669 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004670 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004671 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004672 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004673 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004674 }
4675 }
4676
4677 @Override
4678 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004679 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004680 != PERMISSION_GRANTED) {
4681 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4682 + Binder.getCallingPid()
4683 + ", uid=" + Binder.getCallingUid()
4684 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4685 Slog.w(TAG, msg);
4686 throw new SecurityException(msg);
4687 }
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 proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004692 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004693 }
4694 }
4695
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 @Override
4697 public void stopAppSwitches() {
4698 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4699 synchronized (mGlobalLock) {
4700 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004701 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004702 mDidAppSwitch = false;
4703 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4704 }
4705 }
4706
4707 @Override
4708 public void resumeAppSwitches() {
4709 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4710 synchronized (mGlobalLock) {
4711 // Note that we don't execute any pending app switches... we will
4712 // let those wait until either the timeout, or the next start
4713 // activity request.
4714 mAppSwitchesAllowedTime = 0;
4715 }
4716 }
4717
Ricky Wai906af482019-06-03 17:25:28 +01004718 long getLastStopAppSwitchesTime() {
4719 return mLastStopAppSwitchesTime;
4720 }
4721
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004722 void onStartActivitySetDidAppSwitch() {
4723 if (mDidAppSwitch) {
4724 // This is the second allowed switch since we stopped switches, so now just generally
4725 // allow switches. Use case:
4726 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4727 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4728 // anyone to switch again).
4729 mAppSwitchesAllowedTime = 0;
4730 } else {
4731 mDidAppSwitch = true;
4732 }
4733 }
4734
4735 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004736 boolean shouldDisableNonVrUiLocked() {
4737 return mVrController.shouldDisableNonVrUiLocked();
4738 }
4739
Wale Ogunwale53783742018-09-16 10:21:51 -07004740 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004741 // VR apps are expected to run in a main display. If an app is turning on VR for
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004742 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004744 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4745 + " to main display for VR");
4746 mRootActivityContainer.moveStackToDisplay(
4747 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004748 }
4749 mH.post(() -> {
4750 if (!mVrController.onVrModeChanged(r)) {
4751 return;
4752 }
4753 synchronized (mGlobalLock) {
4754 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4755 mWindowManager.disableNonVrUi(disableNonVrUi);
4756 if (disableNonVrUi) {
4757 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4758 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004759 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004760 }
4761 }
4762 });
4763 }
4764
Wale Ogunwale53783742018-09-16 10:21:51 -07004765 @Override
4766 public int getPackageScreenCompatMode(String packageName) {
4767 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4768 synchronized (mGlobalLock) {
4769 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4770 }
4771 }
4772
4773 @Override
4774 public void setPackageScreenCompatMode(String packageName, int mode) {
4775 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4776 "setPackageScreenCompatMode");
4777 synchronized (mGlobalLock) {
4778 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4779 }
4780 }
4781
4782 @Override
4783 public boolean getPackageAskScreenCompat(String packageName) {
4784 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4785 synchronized (mGlobalLock) {
4786 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4787 }
4788 }
4789
4790 @Override
4791 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4792 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4793 "setPackageAskScreenCompat");
4794 synchronized (mGlobalLock) {
4795 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4796 }
4797 }
4798
Wale Ogunwale64258362018-10-16 15:13:37 -07004799 public static String relaunchReasonToString(int relaunchReason) {
4800 switch (relaunchReason) {
4801 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4802 return "window_resize";
4803 case RELAUNCH_REASON_FREE_RESIZE:
4804 return "free_resize";
4805 default:
4806 return null;
4807 }
4808 }
4809
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004810 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004811 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004812 }
4813
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004814 /** Pokes the task persister. */
4815 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4816 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4817 }
4818
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004819 boolean isKeyguardLocked() {
4820 return mKeyguardController.isKeyguardLocked();
4821 }
4822
Garfield Tan01548632018-11-27 10:15:48 -08004823 /**
4824 * Clears launch params for the given package.
4825 * @param packageNames the names of the packages of which the launch params are to be cleared
4826 */
4827 @Override
4828 public void clearLaunchParamsForPackages(List<String> packageNames) {
4829 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4830 "clearLaunchParamsForPackages");
4831 synchronized (mGlobalLock) {
4832 for (int i = 0; i < packageNames.size(); ++i) {
4833 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4834 }
4835 }
4836 }
4837
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004838 /**
4839 * Makes the display with the given id a single task instance display. I.e the display can only
4840 * contain one task.
4841 */
4842 @Override
4843 public void setDisplayToSingleTaskInstance(int displayId) {
4844 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4845 "setDisplayToSingleTaskInstance");
4846 final long origId = Binder.clearCallingIdentity();
4847 try {
4848 final ActivityDisplay display =
4849 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4850 if (display != null) {
4851 display.setDisplayToSingleTaskInstance();
4852 }
4853 } finally {
4854 Binder.restoreCallingIdentity(origId);
4855 }
4856 }
4857
Wale Ogunwale31913b52018-10-13 08:29:31 -07004858 void dumpLastANRLocked(PrintWriter pw) {
4859 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4860 if (mLastANRState == null) {
4861 pw.println(" <no ANR has occurred since boot>");
4862 } else {
4863 pw.println(mLastANRState);
4864 }
4865 }
4866
4867 void dumpLastANRTracesLocked(PrintWriter pw) {
4868 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4869
4870 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4871 if (ArrayUtils.isEmpty(files)) {
4872 pw.println(" <no ANR has occurred since boot>");
4873 return;
4874 }
4875 // Find the latest file.
4876 File latest = null;
4877 for (File f : files) {
4878 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4879 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004880 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004881 }
4882 pw.print("File: ");
4883 pw.print(latest.getName());
4884 pw.println();
4885 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4886 String line;
4887 while ((line = in.readLine()) != null) {
4888 pw.println(line);
4889 }
4890 } catch (IOException e) {
4891 pw.print("Unable to read: ");
4892 pw.print(e);
4893 pw.println();
4894 }
4895 }
4896
4897 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4898 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4899 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4900 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4901 }
4902
4903 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4904 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4905 pw.println(header);
4906
Wale Ogunwaled32da472018-11-16 07:19:28 -08004907 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004908 dumpPackage);
4909 boolean needSep = printedAnything;
4910
4911 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004912 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004913 " ResumedActivity: ");
4914 if (printed) {
4915 printedAnything = true;
4916 needSep = false;
4917 }
4918
4919 if (dumpPackage == null) {
4920 if (needSep) {
4921 pw.println();
4922 }
4923 printedAnything = true;
4924 mStackSupervisor.dump(pw, " ");
4925 }
4926
4927 if (!printedAnything) {
4928 pw.println(" (nothing)");
4929 }
4930 }
4931
4932 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004933 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004934 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004935 pw.println(" ");
4936 }
4937
4938 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4939 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4940 getActivityStartController().dump(pw, "", dumpPackage);
4941 }
4942
4943 /**
4944 * There are three things that cmd can be:
4945 * - a flattened component name that matches an existing activity
4946 * - the cmd arg isn't the flattened component name of an existing activity:
4947 * dump all activity whose component contains the cmd as a substring
4948 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004949 * <p>
4950 * The caller should not hold lock when calling this method because it will wait for the
4951 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004952 *
4953 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4954 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4955 */
4956 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4957 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4958 ArrayList<ActivityRecord> activities;
4959
4960 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004961 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 dumpFocusedStackOnly);
4963 }
4964
4965 if (activities.size() <= 0) {
4966 return false;
4967 }
4968
4969 String[] newArgs = new String[args.length - opti];
4970 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4971
4972 TaskRecord lastTask = null;
4973 boolean needSep = false;
4974 for (int i = activities.size() - 1; i >= 0; i--) {
4975 ActivityRecord r = activities.get(i);
4976 if (needSep) {
4977 pw.println();
4978 }
4979 needSep = true;
4980 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004981 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 if (lastTask != task) {
4983 lastTask = task;
4984 pw.print("TASK "); pw.print(lastTask.affinity);
4985 pw.print(" id="); pw.print(lastTask.taskId);
4986 pw.print(" userId="); pw.println(lastTask.userId);
4987 if (dumpAll) {
4988 lastTask.dump(pw, " ");
4989 }
4990 }
4991 }
4992 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4993 }
4994 return true;
4995 }
4996
4997 /**
4998 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4999 * there is a thread associated with the activity.
5000 */
5001 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5002 final ActivityRecord r, String[] args, boolean dumpAll) {
5003 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005004 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005005 synchronized (mGlobalLock) {
5006 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5007 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5008 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005009 if (r.hasProcess()) {
5010 pw.println(r.app.getPid());
5011 appThread = r.app.getThread();
5012 } else {
5013 pw.println("(not running)");
5014 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005015 if (dumpAll) {
5016 r.dump(pw, innerPrefix);
5017 }
5018 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005019 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005020 // flush anything that is already in the PrintWriter since the thread is going
5021 // to write to the file descriptor directly
5022 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005023 try (TransferPipe tp = new TransferPipe()) {
5024 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5025 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005026 } catch (IOException e) {
5027 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5028 } catch (RemoteException e) {
5029 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5030 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005031 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005032 }
5033
sanryhuang498e77e2018-12-06 14:57:01 +08005034 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5035 boolean testPssMode) {
5036 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5037 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5038 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005039 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005040 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5041 st.toString());
5042 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005043 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5044 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5045 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005046 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5047 testPssMode);
5048 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005049 }
5050
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051 int getCurrentUserId() {
5052 return mAmInternal.getCurrentUserId();
5053 }
5054
5055 private void enforceNotIsolatedCaller(String caller) {
5056 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5057 throw new SecurityException("Isolated process not allowed to call " + caller);
5058 }
5059 }
5060
Wale Ogunwalef6733932018-06-27 05:14:34 -07005061 public Configuration getConfiguration() {
5062 Configuration ci;
5063 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005064 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005065 ci.userSetLocale = false;
5066 }
5067 return ci;
5068 }
5069
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005070 /**
5071 * Current global configuration information. Contains general settings for the entire system,
5072 * also corresponds to the merged configuration of the default display.
5073 */
5074 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005075 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076 }
5077
5078 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5079 boolean initLocale) {
5080 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5081 }
5082
5083 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5084 boolean initLocale, boolean deferResume) {
5085 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5086 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5087 UserHandle.USER_NULL, deferResume);
5088 }
5089
Wale Ogunwale59507092018-10-29 09:00:30 -07005090 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005091 final long origId = Binder.clearCallingIdentity();
5092 try {
5093 synchronized (mGlobalLock) {
5094 updateConfigurationLocked(values, null, false, true, userId,
5095 false /* deferResume */);
5096 }
5097 } finally {
5098 Binder.restoreCallingIdentity(origId);
5099 }
5100 }
5101
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005102 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5103 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5104 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5105 deferResume, null /* result */);
5106 }
5107
5108 /**
5109 * Do either or both things: (1) change the current configuration, and (2)
5110 * make sure the given activity is running with the (now) current
5111 * configuration. Returns true if the activity has been left running, or
5112 * false if <var>starting</var> is being destroyed to match the new
5113 * configuration.
5114 *
5115 * @param userId is only used when persistent parameter is set to true to persist configuration
5116 * for that particular user
5117 */
5118 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5119 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5120 ActivityTaskManagerService.UpdateConfigurationResult result) {
5121 int changes = 0;
5122 boolean kept = true;
5123
5124 if (mWindowManager != null) {
5125 mWindowManager.deferSurfaceLayout();
5126 }
5127 try {
5128 if (values != null) {
5129 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5130 deferResume);
5131 }
5132
5133 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5134 } finally {
5135 if (mWindowManager != null) {
5136 mWindowManager.continueSurfaceLayout();
5137 }
5138 }
5139
5140 if (result != null) {
5141 result.changes = changes;
5142 result.activityRelaunched = !kept;
5143 }
5144 return kept;
5145 }
5146
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005148 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005149 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005150
5151 final ActivityDisplay defaultDisplay =
5152 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5153
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005154 mTempConfig.setTo(getGlobalConfiguration());
5155 final int changes = mTempConfig.updateFrom(values);
5156 if (changes == 0) {
5157 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5158 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5159 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5160 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005161 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 return 0;
5163 }
5164
5165 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5166 "Updating global configuration to: " + values);
5167
5168 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5169 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5170 values.colorMode,
5171 values.densityDpi,
5172 values.fontScale,
5173 values.hardKeyboardHidden,
5174 values.keyboard,
5175 values.keyboardHidden,
5176 values.mcc,
5177 values.mnc,
5178 values.navigation,
5179 values.navigationHidden,
5180 values.orientation,
5181 values.screenHeightDp,
5182 values.screenLayout,
5183 values.screenWidthDp,
5184 values.smallestScreenWidthDp,
5185 values.touchscreen,
5186 values.uiMode);
5187
5188
5189 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5190 final LocaleList locales = values.getLocales();
5191 int bestLocaleIndex = 0;
5192 if (locales.size() > 1) {
5193 if (mSupportedSystemLocales == null) {
5194 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5195 }
5196 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5197 }
5198 SystemProperties.set("persist.sys.locale",
5199 locales.get(bestLocaleIndex).toLanguageTag());
5200 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005201
5202 final Message m = PooledLambda.obtainMessage(
5203 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5204 locales.get(bestLocaleIndex));
5205 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005206 }
5207
Yunfan Chen75157d72018-07-27 14:47:21 +09005208 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209
5210 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005211 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005212
5213 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5214 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005215 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216
5217 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005218 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219
5220 AttributeCache ac = AttributeCache.instance();
5221 if (ac != null) {
5222 ac.updateConfiguration(mTempConfig);
5223 }
5224
5225 // Make sure all resources in our process are updated right now, so that anyone who is going
5226 // to retrieve resource values after we return will be sure to get the new ones. This is
5227 // especially important during boot, where the first config change needs to guarantee all
5228 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005229 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005230
5231 // We need another copy of global config because we're scheduling some calls instead of
5232 // running them in place. We need to be sure that object we send will be handled unchanged.
5233 final Configuration configCopy = new Configuration(mTempConfig);
5234 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005235 final Message msg = PooledLambda.obtainMessage(
5236 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5237 this, userId, configCopy);
5238 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239 }
5240
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005241 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5242 for (int i = pidMap.size() - 1; i >= 0; i--) {
5243 final int pid = pidMap.keyAt(i);
5244 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005245 if (DEBUG_CONFIGURATION) {
5246 Slog.v(TAG_CONFIGURATION, "Update process config of "
5247 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005249 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250 }
5251
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005252 final Message msg = PooledLambda.obtainMessage(
5253 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5254 mAmInternal, changes, initLocale);
5255 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005256
5257 // Override configuration of the default display duplicates global config, so we need to
5258 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005259 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5260 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005261
5262 return changes;
5263 }
5264
Wale Ogunwalef6733932018-06-27 05:14:34 -07005265 private void updateEventDispatchingLocked(boolean booted) {
5266 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5267 }
5268
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005269 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5270 final ContentResolver resolver = mContext.getContentResolver();
5271 Settings.System.putConfigurationForUser(resolver, config, userId);
5272 }
5273
5274 private void sendLocaleToMountDaemonMsg(Locale l) {
5275 try {
5276 IBinder service = ServiceManager.getService("mount");
5277 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5278 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5279 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5280 } catch (RemoteException e) {
5281 Log.e(TAG, "Error storing locale for decryption UI", e);
5282 }
5283 }
5284
Alison Cichowlas3e340502018-08-07 17:15:01 -04005285 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5286 mStartActivitySources.remove(permissionToken);
5287 mExpiredStartAsCallerTokens.add(permissionToken);
5288 }
5289
5290 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5291 mExpiredStartAsCallerTokens.remove(permissionToken);
5292 }
5293
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005294 boolean isActivityStartsLoggingEnabled() {
5295 return mAmInternal.isActivityStartsLoggingEnabled();
5296 }
5297
Michal Karpinski8596ded2018-11-14 14:43:48 +00005298 boolean isBackgroundActivityStartsEnabled() {
5299 return mAmInternal.isBackgroundActivityStartsEnabled();
5300 }
5301
Wale Ogunwalef6733932018-06-27 05:14:34 -07005302 void enableScreenAfterBoot(boolean booted) {
5303 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5304 SystemClock.uptimeMillis());
5305 mWindowManager.enableScreenAfterBoot();
5306
5307 synchronized (mGlobalLock) {
5308 updateEventDispatchingLocked(booted);
5309 }
5310 }
5311
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005312 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5313 if (r == null || !r.hasProcess()) {
5314 return KEY_DISPATCHING_TIMEOUT_MS;
5315 }
5316 return getInputDispatchingTimeoutLocked(r.app);
5317 }
5318
5319 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005320 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005321 }
5322
Wale Ogunwalef6733932018-06-27 05:14:34 -07005323 /**
5324 * Decide based on the configuration whether we should show the ANR,
5325 * crash, etc dialogs. The idea is that if there is no affordance to
5326 * press the on-screen buttons, or the user experience would be more
5327 * greatly impacted than the crash itself, we shouldn't show the dialog.
5328 *
5329 * A thought: SystemUI might also want to get told about this, the Power
5330 * dialog / global actions also might want different behaviors.
5331 */
5332 private void updateShouldShowDialogsLocked(Configuration config) {
5333 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5334 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5335 && config.navigation == Configuration.NAVIGATION_NONAV);
5336 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5337 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5338 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5339 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5340 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5341 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5342 HIDE_ERROR_DIALOGS, 0) != 0;
5343 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5344 }
5345
5346 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5347 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5348 FONT_SCALE, 1.0f, userId);
5349
5350 synchronized (this) {
5351 if (getGlobalConfiguration().fontScale == scaleFactor) {
5352 return;
5353 }
5354
5355 final Configuration configuration
5356 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5357 configuration.fontScale = scaleFactor;
5358 updatePersistentConfiguration(configuration, userId);
5359 }
5360 }
5361
5362 // Actually is sleeping or shutting down or whatever else in the future
5363 // is an inactive state.
5364 boolean isSleepingOrShuttingDownLocked() {
5365 return isSleepingLocked() || mShuttingDown;
5366 }
5367
5368 boolean isSleepingLocked() {
5369 return mSleeping;
5370 }
5371
Riddle Hsu16567132018-08-16 21:37:47 +08005372 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005373 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005374 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005375 if (task.isActivityTypeStandard()) {
5376 if (mCurAppTimeTracker != r.appTimeTracker) {
5377 // We are switching app tracking. Complete the current one.
5378 if (mCurAppTimeTracker != null) {
5379 mCurAppTimeTracker.stop();
5380 mH.obtainMessage(
5381 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005382 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005383 mCurAppTimeTracker = null;
5384 }
5385 if (r.appTimeTracker != null) {
5386 mCurAppTimeTracker = r.appTimeTracker;
5387 startTimeTrackingFocusedActivityLocked();
5388 }
5389 } else {
5390 startTimeTrackingFocusedActivityLocked();
5391 }
5392 } else {
5393 r.appTimeTracker = null;
5394 }
5395 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5396 // TODO: Probably not, because we don't want to resume voice on switching
5397 // back to this activity
5398 if (task.voiceInteractor != null) {
5399 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5400 } else {
5401 finishRunningVoiceLocked();
5402
5403 if (mLastResumedActivity != null) {
5404 final IVoiceInteractionSession session;
5405
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005406 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005407 if (lastResumedActivityTask != null
5408 && lastResumedActivityTask.voiceSession != null) {
5409 session = lastResumedActivityTask.voiceSession;
5410 } else {
5411 session = mLastResumedActivity.voiceSession;
5412 }
5413
5414 if (session != null) {
5415 // We had been in a voice interaction session, but now focused has
5416 // move to something different. Just finish the session, we can't
5417 // return to it and retain the proper state and synchronization with
5418 // the voice interaction service.
5419 finishVoiceTask(session);
5420 }
5421 }
5422 }
5423
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005424 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5425 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005426 }
5427 updateResumedAppTrace(r);
5428 mLastResumedActivity = r;
5429
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005430 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431
5432 applyUpdateLockStateLocked(r);
5433 applyUpdateVrModeLocked(r);
5434
5435 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005436 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 r == null ? "NULL" : r.shortComponentName,
5438 reason);
5439 }
5440
5441 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5442 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005443 final ActivityTaskManagerInternal.SleepToken token =
5444 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005445 updateSleepIfNeededLocked();
5446 return token;
5447 }
5448 }
5449
5450 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005451 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005452 final boolean wasSleeping = mSleeping;
5453 boolean updateOomAdj = false;
5454
5455 if (!shouldSleep) {
5456 // If wasSleeping is true, we need to wake up activity manager state from when
5457 // we started sleeping. In either case, we need to apply the sleep tokens, which
5458 // will wake up stacks or put them to sleep as appropriate.
5459 if (wasSleeping) {
5460 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005461 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5462 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 startTimeTrackingFocusedActivityLocked();
5464 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005465 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5467 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005468 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 if (wasSleeping) {
5470 updateOomAdj = true;
5471 }
5472 } else if (!mSleeping && shouldSleep) {
5473 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005474 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5475 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005476 if (mCurAppTimeTracker != null) {
5477 mCurAppTimeTracker.stop();
5478 }
5479 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005480 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 mStackSupervisor.goingToSleepLocked();
5482 updateResumedAppTrace(null /* resumed */);
5483 updateOomAdj = true;
5484 }
5485 if (updateOomAdj) {
5486 mH.post(mAmInternal::updateOomAdj);
5487 }
5488 }
5489
5490 void updateOomAdj() {
5491 mH.post(mAmInternal::updateOomAdj);
5492 }
5493
Wale Ogunwale53783742018-09-16 10:21:51 -07005494 void updateCpuStats() {
5495 mH.post(mAmInternal::updateCpuStats);
5496 }
5497
Hui Yu03d12402018-12-06 18:00:37 -08005498 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5499 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005500 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5501 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005502 mH.sendMessage(m);
5503 }
5504
Hui Yu03d12402018-12-06 18:00:37 -08005505 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005506 ComponentName taskRoot = null;
5507 final TaskRecord task = activity.getTaskRecord();
5508 if (task != null) {
5509 final ActivityRecord rootActivity = task.getRootActivity();
5510 if (rootActivity != null) {
5511 taskRoot = rootActivity.mActivityComponent;
5512 }
5513 }
5514
Hui Yu03d12402018-12-06 18:00:37 -08005515 final Message m = PooledLambda.obtainMessage(
5516 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005517 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005518 mH.sendMessage(m);
5519 }
5520
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005521 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5522 String hostingType) {
5523 try {
5524 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5525 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5526 + activity.processName);
5527 }
5528 // Post message to start process to avoid possible deadlock of calling into AMS with the
5529 // ATMS lock held.
5530 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5531 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5532 isTop, hostingType, activity.intent.getComponent());
5533 mH.sendMessage(m);
5534 } finally {
5535 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5536 }
5537 }
5538
Wale Ogunwale53783742018-09-16 10:21:51 -07005539 void setBooting(boolean booting) {
5540 mAmInternal.setBooting(booting);
5541 }
5542
5543 boolean isBooting() {
5544 return mAmInternal.isBooting();
5545 }
5546
5547 void setBooted(boolean booted) {
5548 mAmInternal.setBooted(booted);
5549 }
5550
5551 boolean isBooted() {
5552 return mAmInternal.isBooted();
5553 }
5554
5555 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5556 mH.post(() -> {
5557 if (finishBooting) {
5558 mAmInternal.finishBooting();
5559 }
5560 if (enableScreen) {
5561 mInternal.enableScreenAfterBoot(isBooted());
5562 }
5563 });
5564 }
5565
5566 void setHeavyWeightProcess(ActivityRecord root) {
5567 mHeavyWeightProcess = root.app;
5568 final Message m = PooledLambda.obtainMessage(
5569 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005570 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005571 mH.sendMessage(m);
5572 }
5573
5574 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5575 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5576 return;
5577 }
5578
5579 mHeavyWeightProcess = null;
5580 final Message m = PooledLambda.obtainMessage(
5581 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5582 proc.mUserId);
5583 mH.sendMessage(m);
5584 }
5585
5586 private void cancelHeavyWeightProcessNotification(int userId) {
5587 final INotificationManager inm = NotificationManager.getService();
5588 if (inm == null) {
5589 return;
5590 }
5591 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005592 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005593 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5594 } catch (RuntimeException e) {
5595 Slog.w(TAG, "Error canceling notification for service", e);
5596 } catch (RemoteException e) {
5597 }
5598
5599 }
5600
5601 private void postHeavyWeightProcessNotification(
5602 WindowProcessController proc, Intent intent, int userId) {
5603 if (proc == null) {
5604 return;
5605 }
5606
5607 final INotificationManager inm = NotificationManager.getService();
5608 if (inm == null) {
5609 return;
5610 }
5611
5612 try {
5613 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5614 String text = mContext.getString(R.string.heavy_weight_notification,
5615 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5616 Notification notification =
5617 new Notification.Builder(context,
5618 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5619 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5620 .setWhen(0)
5621 .setOngoing(true)
5622 .setTicker(text)
5623 .setColor(mContext.getColor(
5624 com.android.internal.R.color.system_notification_accent_color))
5625 .setContentTitle(text)
5626 .setContentText(
5627 mContext.getText(R.string.heavy_weight_notification_detail))
5628 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5629 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5630 new UserHandle(userId)))
5631 .build();
5632 try {
5633 inm.enqueueNotificationWithTag("android", "android", null,
5634 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5635 } catch (RuntimeException e) {
5636 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5637 } catch (RemoteException e) {
5638 }
5639 } catch (PackageManager.NameNotFoundException e) {
5640 Slog.w(TAG, "Unable to create context for heavy notification", e);
5641 }
5642
5643 }
5644
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005645 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5646 IBinder token, String resultWho, int requestCode, Intent[] intents,
5647 String[] resolvedTypes, int flags, Bundle bOptions) {
5648
5649 ActivityRecord activity = null;
5650 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5651 activity = ActivityRecord.isInStackLocked(token);
5652 if (activity == null) {
5653 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5654 return null;
5655 }
5656 if (activity.finishing) {
5657 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5658 return null;
5659 }
5660 }
5661
5662 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5663 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5664 bOptions);
5665 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5666 if (noCreate) {
5667 return rec;
5668 }
5669 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5670 if (activity.pendingResults == null) {
5671 activity.pendingResults = new HashSet<>();
5672 }
5673 activity.pendingResults.add(rec.ref);
5674 }
5675 return rec;
5676 }
5677
Andrii Kulian52d255c2018-07-13 11:32:19 -07005678 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005679 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005680 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005681 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5682 mCurAppTimeTracker.start(resumedActivity.packageName);
5683 }
5684 }
5685
5686 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5687 if (mTracedResumedActivity != null) {
5688 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5689 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5690 }
5691 if (resumed != null) {
5692 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5693 constructResumedTraceName(resumed.packageName), 0);
5694 }
5695 mTracedResumedActivity = resumed;
5696 }
5697
5698 private String constructResumedTraceName(String packageName) {
5699 return "focused app: " + packageName;
5700 }
5701
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005702 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005703 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005704 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005705 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005706 // mainStack is null during startup.
5707 if (mainStack != null) {
5708 if (changes != 0 && starting == null) {
5709 // If the configuration changed, and the caller is not already
5710 // in the process of starting an activity, then find the top
5711 // activity to check if its configuration needs to change.
5712 starting = mainStack.topRunningActivityLocked();
5713 }
5714
5715 if (starting != null) {
5716 kept = starting.ensureActivityConfiguration(changes,
5717 false /* preserveWindow */);
5718 // And we need to make sure at this point that all other activities
5719 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005720 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005721 !PRESERVE_WINDOWS);
5722 }
5723 }
5724
5725 return kept;
5726 }
5727
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005728 void scheduleAppGcsLocked() {
5729 mH.post(() -> mAmInternal.scheduleAppGcs());
5730 }
5731
Wale Ogunwale53783742018-09-16 10:21:51 -07005732 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5733 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5734 }
5735
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005736 /**
5737 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5738 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5739 * on demand.
5740 */
5741 IPackageManager getPackageManager() {
5742 return AppGlobals.getPackageManager();
5743 }
5744
5745 PackageManagerInternal getPackageManagerInternalLocked() {
5746 if (mPmInternal == null) {
5747 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5748 }
5749 return mPmInternal;
5750 }
5751
Hai Zhangf4da9be2019-05-01 13:46:06 +08005752 PermissionPolicyInternal getPermissionPolicyInternal() {
5753 if (mPermissionPolicyInternal == null) {
5754 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5755 }
5756 return mPermissionPolicyInternal;
5757 }
5758
Wale Ogunwale008163e2018-07-23 23:11:08 -07005759 AppWarnings getAppWarningsLocked() {
5760 return mAppWarnings;
5761 }
5762
Wale Ogunwale214f3482018-10-04 11:00:47 -07005763 Intent getHomeIntent() {
5764 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5765 intent.setComponent(mTopComponent);
5766 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5767 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5768 intent.addCategory(Intent.CATEGORY_HOME);
5769 }
5770 return intent;
5771 }
5772
Chilun2ef71f72018-11-16 17:57:15 +08005773 /**
5774 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5775 * activities.
5776 *
5777 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5778 * component defined in config_secondaryHomeComponent.
5779 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5780 */
5781 Intent getSecondaryHomeIntent(String preferredPackage) {
5782 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005783 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5784 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5785 if (preferredPackage == null || useSystemProvidedLauncher) {
5786 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005787 final String secondaryHomeComponent = mContext.getResources().getString(
5788 com.android.internal.R.string.config_secondaryHomeComponent);
5789 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5790 } else {
5791 intent.setPackage(preferredPackage);
5792 }
5793 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5794 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5795 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5796 }
5797 return intent;
5798 }
5799
Wale Ogunwale214f3482018-10-04 11:00:47 -07005800 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5801 if (info == null) return null;
5802 ApplicationInfo newInfo = new ApplicationInfo(info);
5803 newInfo.initForUser(userId);
5804 return newInfo;
5805 }
5806
Wale Ogunwale9c103022018-10-18 07:44:54 -07005807 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005808 if (uid == SYSTEM_UID) {
5809 // The system gets to run in any process. If there are multiple processes with the same
5810 // uid, just pick the first (this should never happen).
5811 final SparseArray<WindowProcessController> procs =
5812 mProcessNames.getMap().get(processName);
5813 if (procs == null) return null;
5814 final int procCount = procs.size();
5815 for (int i = 0; i < procCount; i++) {
5816 final int procUid = procs.keyAt(i);
5817 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5818 // Don't use an app process or different user process for system component.
5819 continue;
5820 }
5821 return procs.valueAt(i);
5822 }
5823 }
5824
5825 return mProcessNames.get(processName, uid);
5826 }
5827
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005828 WindowProcessController getProcessController(IApplicationThread thread) {
5829 if (thread == null) {
5830 return null;
5831 }
5832
5833 final IBinder threadBinder = thread.asBinder();
5834 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5835 for (int i = pmap.size()-1; i >= 0; i--) {
5836 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5837 for (int j = procs.size() - 1; j >= 0; j--) {
5838 final WindowProcessController proc = procs.valueAt(j);
5839 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5840 return proc;
5841 }
5842 }
5843 }
5844
5845 return null;
5846 }
5847
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005848 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005849 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005850 if (proc == null) return null;
5851 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5852 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005853 }
5854 return null;
5855 }
5856
Riddle Hsua0536432019-02-16 00:38:59 +08005857 int getUidState(int uid) {
5858 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005859 }
5860
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005861 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005862 // A uid is considered to be foreground if it has a visible non-toast window.
5863 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005864 }
5865
Ricky Wai96f5c352019-04-10 18:40:17 +01005866 boolean isDeviceOwner(int uid) {
5867 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005868 }
5869
Ricky Wai96f5c352019-04-10 18:40:17 +01005870 void setDeviceOwnerUid(int uid) {
5871 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005872 }
5873
Wale Ogunwale9de19442018-10-18 19:05:03 -07005874 /**
5875 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5876 * the whitelist
5877 */
5878 String getPendingTempWhitelistTagForUidLocked(int uid) {
5879 return mPendingTempWhitelist.get(uid);
5880 }
5881
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005882 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5883 if (true || Build.IS_USER) {
5884 return;
5885 }
5886
5887 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5888 StrictMode.allowThreadDiskWrites();
5889 try {
5890 File tracesDir = new File("/data/anr");
5891 File tracesFile = null;
5892 try {
5893 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5894
5895 StringBuilder sb = new StringBuilder();
5896 Time tobj = new Time();
5897 tobj.set(System.currentTimeMillis());
5898 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5899 sb.append(": ");
5900 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5901 sb.append(" since ");
5902 sb.append(msg);
5903 FileOutputStream fos = new FileOutputStream(tracesFile);
5904 fos.write(sb.toString().getBytes());
5905 if (app == null) {
5906 fos.write("\n*** No application process!".getBytes());
5907 }
5908 fos.close();
5909 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5910 } catch (IOException e) {
5911 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5912 return;
5913 }
5914
5915 if (app != null && app.getPid() > 0) {
5916 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5917 firstPids.add(app.getPid());
5918 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5919 }
5920
5921 File lastTracesFile = null;
5922 File curTracesFile = null;
5923 for (int i=9; i>=0; i--) {
5924 String name = String.format(Locale.US, "slow%02d.txt", i);
5925 curTracesFile = new File(tracesDir, name);
5926 if (curTracesFile.exists()) {
5927 if (lastTracesFile != null) {
5928 curTracesFile.renameTo(lastTracesFile);
5929 } else {
5930 curTracesFile.delete();
5931 }
5932 }
5933 lastTracesFile = curTracesFile;
5934 }
5935 tracesFile.renameTo(curTracesFile);
5936 } finally {
5937 StrictMode.setThreadPolicy(oldPolicy);
5938 }
5939 }
5940
Michal Karpinskida34cd42019-04-02 19:46:52 +01005941 boolean isAssociatedCompanionApp(int userId, int uid) {
5942 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5943 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005944 return false;
5945 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005946 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005947 }
5948
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005949 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005950 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005951
5952
Wale Ogunwale98875612018-10-12 07:53:02 -07005953 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5954 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005955
Riddle Hsud93a6c42018-11-29 21:50:06 +08005956 H(Looper looper) {
5957 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005958 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005959
5960 @Override
5961 public void handleMessage(Message msg) {
5962 switch (msg.what) {
5963 case REPORT_TIME_TRACKER_MSG: {
5964 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5965 tracker.deliverResult(mContext);
5966 } break;
5967 }
5968 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005969 }
5970
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005971 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005973
5974 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005975 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005976 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005977
5978 @Override
5979 public void handleMessage(Message msg) {
5980 switch (msg.what) {
5981 case DISMISS_DIALOG_UI_MSG: {
5982 final Dialog d = (Dialog) msg.obj;
5983 d.dismiss();
5984 break;
5985 }
5986 }
5987 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005988 }
5989
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005990 final class LocalService extends ActivityTaskManagerInternal {
5991 @Override
5992 public SleepToken acquireSleepToken(String tag, int displayId) {
5993 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005994 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005995 }
5996
5997 @Override
5998 public ComponentName getHomeActivityForUser(int userId) {
5999 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006000 final ActivityRecord homeActivity =
6001 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006002 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 }
6004 }
6005
6006 @Override
6007 public void onLocalVoiceInteractionStarted(IBinder activity,
6008 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6009 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006010 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006011 }
6012 }
6013
6014 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006015 public void notifyAppTransitionStarting(SparseIntArray reasons,
6016 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006017 synchronized (mGlobalLock) {
6018 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6019 reasons, timestamp);
6020 }
6021 }
6022
6023 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006024 public void notifySingleTaskDisplayDrawn(int displayId) {
6025 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6026 }
6027
6028 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006029 public void notifyAppTransitionFinished() {
6030 synchronized (mGlobalLock) {
6031 mStackSupervisor.notifyAppTransitionDone();
6032 }
6033 }
6034
6035 @Override
6036 public void notifyAppTransitionCancelled() {
6037 synchronized (mGlobalLock) {
6038 mStackSupervisor.notifyAppTransitionDone();
6039 }
6040 }
6041
6042 @Override
6043 public List<IBinder> getTopVisibleActivities() {
6044 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006045 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006046 }
6047 }
6048
6049 @Override
6050 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006052 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 }
6054 }
6055
6056 @Override
6057 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6058 Bundle bOptions) {
6059 Preconditions.checkNotNull(intents, "intents");
6060 final String[] resolvedTypes = new String[intents.length];
6061
6062 // UID of the package on user userId.
6063 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6064 // packageUid may not be initialized.
6065 int packageUid = 0;
6066 final long ident = Binder.clearCallingIdentity();
6067
6068 try {
6069 for (int i = 0; i < intents.length; i++) {
6070 resolvedTypes[i] =
6071 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6072 }
6073
6074 packageUid = AppGlobals.getPackageManager().getPackageUid(
6075 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6076 } catch (RemoteException e) {
6077 // Shouldn't happen.
6078 } finally {
6079 Binder.restoreCallingIdentity(ident);
6080 }
6081
Riddle Hsu591bf612019-02-14 17:55:31 +08006082 return getActivityStartController().startActivitiesInPackage(
6083 packageUid, packageName,
6084 intents, resolvedTypes, null /* resultTo */,
6085 SafeActivityOptions.fromBundle(bOptions), userId,
6086 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6087 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006088 }
6089
6090 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006091 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6092 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6093 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6094 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006095 boolean allowBackgroundActivityStart) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07006096 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006097 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006098 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6099 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6100 userId, validateIncomingUser, originatingPendingIntent,
6101 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006102 }
6103 }
6104
6105 @Override
6106 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6107 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6108 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6109 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006110 PendingIntentRecord originatingPendingIntent,
6111 boolean allowBackgroundActivityStart) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07006112 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006113 synchronized (mGlobalLock) {
6114 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6115 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6116 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006117 validateIncomingUser, originatingPendingIntent,
6118 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006119 }
6120 }
6121
6122 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6124 Intent intent, Bundle options, int userId) {
6125 return ActivityTaskManagerService.this.startActivityAsUser(
6126 caller, callerPacakge, intent,
6127 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6128 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6129 false /*validateIncomingUser*/);
6130 }
6131
6132 @Override
lumark588a3e82018-07-20 18:53:54 +08006133 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 synchronized (mGlobalLock) {
6135
6136 // We might change the visibilities here, so prepare an empty app transition which
6137 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006138 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006139 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006140 if (activityDisplay == null) {
6141 return;
6142 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006143 final DisplayContent dc = activityDisplay.mDisplayContent;
6144 final boolean wasTransitionSet =
6145 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006147 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006149 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006150
6151 // If there was a transition set already we don't want to interfere with it as we
6152 // might be starting it too early.
6153 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006154 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 }
6156 }
6157 if (callback != null) {
6158 callback.run();
6159 }
6160 }
6161
6162 @Override
6163 public void notifyKeyguardTrustedChanged() {
6164 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006165 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006166 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 }
6168 }
6169 }
6170
6171 /**
6172 * Called after virtual display Id is updated by
6173 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6174 * {@param vrVr2dDisplayId}.
6175 */
6176 @Override
6177 public void setVr2dDisplayId(int vr2dDisplayId) {
6178 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6179 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006180 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182 }
6183
6184 @Override
6185 public void setFocusedActivity(IBinder token) {
6186 synchronized (mGlobalLock) {
6187 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6188 if (r == null) {
6189 throw new IllegalArgumentException(
6190 "setFocusedActivity: No activity record matching token=" + token);
6191 }
Louis Chang19443452018-10-09 12:10:21 +08006192 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006193 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 }
6195 }
6196 }
6197
6198 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006199 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006200 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 }
6202
6203 @Override
6204 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006205 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 }
6207
6208 @Override
6209 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006210 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 }
6212
6213 @Override
6214 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6215 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6216 }
6217
6218 @Override
6219 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006220 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006222
6223 @Override
6224 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6225 synchronized (mGlobalLock) {
6226 mActiveVoiceInteractionServiceComponent = component;
6227 }
6228 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006229
6230 @Override
6231 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6232 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6233 return;
6234 }
6235 synchronized (mGlobalLock) {
6236 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6237 if (types == null) {
6238 if (uid < 0) {
6239 return;
6240 }
6241 types = new ArrayMap<>();
6242 mAllowAppSwitchUids.put(userId, types);
6243 }
6244 if (uid < 0) {
6245 types.remove(type);
6246 } else {
6247 types.put(type, uid);
6248 }
6249 }
6250 }
6251
6252 @Override
6253 public void onUserStopped(int userId) {
6254 synchronized (mGlobalLock) {
6255 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6256 mAllowAppSwitchUids.remove(userId);
6257 }
6258 }
6259
6260 @Override
6261 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6262 synchronized (mGlobalLock) {
6263 return ActivityTaskManagerService.this.isGetTasksAllowed(
6264 caller, callingPid, callingUid);
6265 }
6266 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006267
Riddle Hsua0536432019-02-16 00:38:59 +08006268 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006269 @Override
6270 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006271 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006272 mProcessNames.put(proc.mName, proc.mUid, proc);
6273 }
6274 }
6275
Riddle Hsua0536432019-02-16 00:38:59 +08006276 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006277 @Override
6278 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006279 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006280 mProcessNames.remove(name, uid);
6281 }
6282 }
6283
Riddle Hsua0536432019-02-16 00:38:59 +08006284 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006285 @Override
6286 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006287 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006288 if (proc == mHomeProcess) {
6289 mHomeProcess = null;
6290 }
6291 if (proc == mPreviousProcess) {
6292 mPreviousProcess = null;
6293 }
6294 }
6295 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006296
Riddle Hsua0536432019-02-16 00:38:59 +08006297 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006298 @Override
6299 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006300 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006301 return mTopProcessState;
6302 }
6303 }
6304
Riddle Hsua0536432019-02-16 00:38:59 +08006305 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006306 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006307 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006308 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006309 return proc == mHeavyWeightProcess;
6310 }
6311 }
6312
Riddle Hsua0536432019-02-16 00:38:59 +08006313 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 @Override
6315 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006316 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006317 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6318 }
6319 }
6320
6321 @Override
6322 public void finishHeavyWeightApp() {
6323 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006324 if (mHeavyWeightProcess != null) {
6325 mHeavyWeightProcess.finishActivities();
6326 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006327 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6328 mHeavyWeightProcess);
6329 }
6330 }
6331
Riddle Hsua0536432019-02-16 00:38:59 +08006332 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006333 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006334 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006335 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006336 return isSleepingLocked();
6337 }
6338 }
6339
6340 @Override
6341 public boolean isShuttingDown() {
6342 synchronized (mGlobalLock) {
6343 return mShuttingDown;
6344 }
6345 }
6346
6347 @Override
6348 public boolean shuttingDown(boolean booted, int timeout) {
6349 synchronized (mGlobalLock) {
6350 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006351 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006352 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006353 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006354 return mStackSupervisor.shutdownLocked(timeout);
6355 }
6356 }
6357
6358 @Override
6359 public void enableScreenAfterBoot(boolean booted) {
6360 synchronized (mGlobalLock) {
6361 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6362 SystemClock.uptimeMillis());
6363 mWindowManager.enableScreenAfterBoot();
6364 updateEventDispatchingLocked(booted);
6365 }
6366 }
6367
6368 @Override
6369 public boolean showStrictModeViolationDialog() {
6370 synchronized (mGlobalLock) {
6371 return mShowDialogs && !mSleeping && !mShuttingDown;
6372 }
6373 }
6374
6375 @Override
6376 public void showSystemReadyErrorDialogsIfNeeded() {
6377 synchronized (mGlobalLock) {
6378 try {
6379 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6380 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6381 + " data partition or your device will be unstable.");
6382 mUiHandler.post(() -> {
6383 if (mShowDialogs) {
6384 AlertDialog d = new BaseErrorDialog(mUiContext);
6385 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6386 d.setCancelable(false);
6387 d.setTitle(mUiContext.getText(R.string.android_system_label));
6388 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6389 d.setButton(DialogInterface.BUTTON_POSITIVE,
6390 mUiContext.getText(R.string.ok),
6391 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6392 d.show();
6393 }
6394 });
6395 }
6396 } catch (RemoteException e) {
6397 }
6398
6399 if (!Build.isBuildConsistent()) {
6400 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6401 mUiHandler.post(() -> {
6402 if (mShowDialogs) {
6403 AlertDialog d = new BaseErrorDialog(mUiContext);
6404 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6405 d.setCancelable(false);
6406 d.setTitle(mUiContext.getText(R.string.android_system_label));
6407 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6408 d.setButton(DialogInterface.BUTTON_POSITIVE,
6409 mUiContext.getText(R.string.ok),
6410 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6411 d.show();
6412 }
6413 });
6414 }
6415 }
6416 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006417
6418 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006419 public void onProcessMapped(int pid, WindowProcessController proc) {
6420 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006421 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006422 }
6423 }
6424
6425 @Override
6426 public void onProcessUnMapped(int pid) {
6427 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006428 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006429 }
6430 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006431
6432 @Override
6433 public void onPackageDataCleared(String name) {
6434 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006436 mAppWarnings.onPackageDataCleared(name);
6437 }
6438 }
6439
6440 @Override
6441 public void onPackageUninstalled(String name) {
6442 synchronized (mGlobalLock) {
6443 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006444 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006445 }
6446 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006447
6448 @Override
6449 public void onPackageAdded(String name, boolean replacing) {
6450 synchronized (mGlobalLock) {
6451 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6452 }
6453 }
6454
6455 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006456 public void onPackageReplaced(ApplicationInfo aInfo) {
6457 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006458 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006459 }
6460 }
6461
6462 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006463 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6464 synchronized (mGlobalLock) {
6465 return compatibilityInfoForPackageLocked(ai);
6466 }
6467 }
6468
Yunfan Chen75157d72018-07-27 14:47:21 +09006469 /**
6470 * Set the corresponding display information for the process global configuration. To be
6471 * called when we need to show IME on a different display.
6472 *
6473 * @param pid The process id associated with the IME window.
6474 * @param displayId The ID of the display showing the IME.
6475 */
6476 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006477 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006478 // Don't update process-level configuration for Multi-Client IME process since other
6479 // IMEs on other displays will also receive this configuration change due to IME
6480 // services use the same application config/context.
6481 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006482
Yunfan Chen75157d72018-07-27 14:47:21 +09006483 if (pid == MY_PID || pid < 0) {
6484 if (DEBUG_CONFIGURATION) {
6485 Slog.w(TAG,
6486 "Trying to update display configuration for system/invalid process.");
6487 }
6488 return;
6489 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006490 synchronized (mGlobalLock) {
6491 final ActivityDisplay activityDisplay =
6492 mRootActivityContainer.getActivityDisplay(displayId);
6493 if (activityDisplay == null) {
6494 // Call might come when display is not yet added or has been removed.
6495 if (DEBUG_CONFIGURATION) {
6496 Slog.w(TAG, "Trying to update display configuration for non-existing "
6497 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006498 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006499 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006500 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006501 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006502 if (process == null) {
6503 if (DEBUG_CONFIGURATION) {
6504 Slog.w(TAG, "Trying to update display configuration for invalid "
6505 + "process, pid=" + pid);
6506 }
6507 return;
6508 }
6509 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6510 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006511 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006512
6513 @Override
6514 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006515 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006516 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006517 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6518 if (r != null && r.getActivityStack() != null) {
6519 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6520 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006521 }
6522 }
6523 }
6524
6525 @Override
6526 public void clearPendingResultForActivity(IBinder activityToken,
6527 WeakReference<PendingIntentRecord> pir) {
6528 synchronized (mGlobalLock) {
6529 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6530 if (r != null && r.pendingResults != null) {
6531 r.pendingResults.remove(pir);
6532 }
6533 }
6534 }
6535
6536 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006537 public ActivityTokens getTopActivityForTask(int taskId) {
6538 synchronized (mGlobalLock) {
6539 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6540 if (taskRecord == null) {
6541 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6542 + " Requested task not found");
6543 return null;
6544 }
6545 final ActivityRecord activity = taskRecord.getTopActivity();
6546 if (activity == null) {
6547 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6548 + " Requested activity not found");
6549 return null;
6550 }
6551 if (!activity.attachedToProcess()) {
6552 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6553 + activity);
6554 return null;
6555 }
6556 return new ActivityTokens(activity.appToken, activity.assistToken,
6557 activity.app.getThread());
6558 }
6559 }
6560
6561 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006562 public IIntentSender getIntentSender(int type, String packageName,
6563 int callingUid, int userId, IBinder token, String resultWho,
6564 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6565 Bundle bOptions) {
6566 synchronized (mGlobalLock) {
6567 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6568 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6569 }
6570 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006571
6572 @Override
6573 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6574 synchronized (mGlobalLock) {
6575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6576 if (r == null) {
6577 return null;
6578 }
6579 if (r.mServiceConnectionsHolder == null) {
6580 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6581 ActivityTaskManagerService.this, r);
6582 }
6583
6584 return r.mServiceConnectionsHolder;
6585 }
6586 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006587
6588 @Override
6589 public Intent getHomeIntent() {
6590 synchronized (mGlobalLock) {
6591 return ActivityTaskManagerService.this.getHomeIntent();
6592 }
6593 }
6594
6595 @Override
6596 public boolean startHomeActivity(int userId, String reason) {
6597 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006598 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006599 }
6600 }
6601
6602 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006603 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006604 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006605 synchronized (mGlobalLock) {
6606 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006607 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006608 }
Chilun8b1f1be2019-03-13 17:14:36 +08006609 }
6610
6611 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006612 public boolean startHomeOnAllDisplays(int userId, String reason) {
6613 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006614 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006615 }
6616 }
6617
Riddle Hsua0536432019-02-16 00:38:59 +08006618 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006619 @Override
6620 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006621 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006622 if (mFactoryTest == FACTORY_TEST_OFF) {
6623 return false;
6624 }
6625 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6626 && wpc.mName.equals(mTopComponent.getPackageName())) {
6627 return true;
6628 }
6629 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6630 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6631 }
6632 }
6633
6634 @Override
6635 public void updateTopComponentForFactoryTest() {
6636 synchronized (mGlobalLock) {
6637 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6638 return;
6639 }
6640 final ResolveInfo ri = mContext.getPackageManager()
6641 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6642 final CharSequence errorMsg;
6643 if (ri != null) {
6644 final ActivityInfo ai = ri.activityInfo;
6645 final ApplicationInfo app = ai.applicationInfo;
6646 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6647 mTopAction = Intent.ACTION_FACTORY_TEST;
6648 mTopData = null;
6649 mTopComponent = new ComponentName(app.packageName, ai.name);
6650 errorMsg = null;
6651 } else {
6652 errorMsg = mContext.getResources().getText(
6653 com.android.internal.R.string.factorytest_not_system);
6654 }
6655 } else {
6656 errorMsg = mContext.getResources().getText(
6657 com.android.internal.R.string.factorytest_no_action);
6658 }
6659 if (errorMsg == null) {
6660 return;
6661 }
6662
6663 mTopAction = null;
6664 mTopData = null;
6665 mTopComponent = null;
6666 mUiHandler.post(() -> {
6667 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6668 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006669 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006670 });
6671 }
6672 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006673
Riddle Hsua0536432019-02-16 00:38:59 +08006674 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006675 @Override
6676 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6677 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006678 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006679 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006680 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006681
6682 wpc.clearRecentTasks();
6683 wpc.clearActivities();
6684
6685 if (wpc.isInstrumenting()) {
6686 finishInstrumentationCallback.run();
6687 }
6688
Jorim Jaggid0752812018-10-16 16:07:20 +02006689 if (!restarting && hasVisibleActivities) {
6690 mWindowManager.deferSurfaceLayout();
6691 try {
6692 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6693 // If there was nothing to resume, and we are not already restarting
6694 // this process, but there is a visible activity that is hosted by the
6695 // process...then make sure all visible activities are running, taking
6696 // care of restarting this process.
6697 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6698 !PRESERVE_WINDOWS);
6699 }
6700 } finally {
6701 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006702 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006703 }
6704 }
6705 }
6706
6707 @Override
6708 public void closeSystemDialogs(String reason) {
6709 enforceNotIsolatedCaller("closeSystemDialogs");
6710
6711 final int pid = Binder.getCallingPid();
6712 final int uid = Binder.getCallingUid();
6713 final long origId = Binder.clearCallingIdentity();
6714 try {
6715 synchronized (mGlobalLock) {
6716 // Only allow this from foreground processes, so that background
6717 // applications can't abuse it to prevent system UI from being shown.
6718 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006719 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006720 if (!proc.isPerceptible()) {
6721 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6722 + " from background process " + proc);
6723 return;
6724 }
6725 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006726 mWindowManager.closeSystemDialogs(reason);
6727
Wale Ogunwaled32da472018-11-16 07:19:28 -08006728 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006730 // Call into AM outside the synchronized block.
6731 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006732 } finally {
6733 Binder.restoreCallingIdentity(origId);
6734 }
6735 }
6736
6737 @Override
6738 public void cleanupDisabledPackageComponents(
6739 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6740 synchronized (mGlobalLock) {
6741 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006742 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006744 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006745 mStackSupervisor.scheduleIdleLocked();
6746 }
6747
6748 // Clean-up disabled tasks
6749 getRecentTasks().cleanupDisabledPackageTasksLocked(
6750 packageName, disabledClasses, userId);
6751 }
6752 }
6753
6754 @Override
6755 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6756 int userId) {
6757 synchronized (mGlobalLock) {
6758
6759 boolean didSomething =
6760 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006761 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006762 null, doit, evenPersistent, userId);
6763 return didSomething;
6764 }
6765 }
6766
6767 @Override
6768 public void resumeTopActivities(boolean scheduleIdle) {
6769 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006770 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 if (scheduleIdle) {
6772 mStackSupervisor.scheduleIdleLocked();
6773 }
6774 }
6775 }
6776
Riddle Hsua0536432019-02-16 00:38:59 +08006777 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 @Override
6779 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006780 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6782 }
6783 }
6784
Riddle Hsua0536432019-02-16 00:38:59 +08006785 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 @Override
6787 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006788 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006789 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 }
6791 }
6792
6793 @Override
6794 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6795 try {
6796 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6797 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6798 }
6799 } catch (RemoteException ex) {
6800 throw new SecurityException("Fail to check is caller a privileged app", ex);
6801 }
6802
6803 synchronized (mGlobalLock) {
6804 final long ident = Binder.clearCallingIdentity();
6805 try {
6806 if (mAmInternal.shouldConfirmCredentials(userId)) {
6807 if (mKeyguardController.isKeyguardLocked()) {
6808 // Showing launcher to avoid user entering credential twice.
6809 startHomeActivity(currentUserId, "notifyLockedProfile");
6810 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006811 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 }
6813 } finally {
6814 Binder.restoreCallingIdentity(ident);
6815 }
6816 }
6817 }
6818
6819 @Override
6820 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6821 mAmInternal.enforceCallingPermission(
6822 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6823
6824 synchronized (mGlobalLock) {
6825 final long ident = Binder.clearCallingIdentity();
6826 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006827 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6828 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006829 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6831 UserHandle.CURRENT);
6832 } finally {
6833 Binder.restoreCallingIdentity(ident);
6834 }
6835 }
6836 }
6837
6838 @Override
6839 public void writeActivitiesToProto(ProtoOutputStream proto) {
6840 synchronized (mGlobalLock) {
6841 // The output proto of "activity --proto activities"
6842 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006843 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006844 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6845 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
6847 }
6848
6849 @Override
6850 public void saveANRState(String reason) {
6851 synchronized (mGlobalLock) {
6852 final StringWriter sw = new StringWriter();
6853 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6854 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6855 if (reason != null) {
6856 pw.println(" Reason: " + reason);
6857 }
6858 pw.println();
6859 getActivityStartController().dump(pw, " ", null);
6860 pw.println();
6861 pw.println("-------------------------------------------------------------------------------");
6862 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6863 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6864 "" /* header */);
6865 pw.println();
6866 pw.close();
6867
6868 mLastANRState = sw.toString();
6869 }
6870 }
6871
6872 @Override
6873 public void clearSavedANRState() {
6874 synchronized (mGlobalLock) {
6875 mLastANRState = null;
6876 }
6877 }
6878
6879 @Override
6880 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6881 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6882 synchronized (mGlobalLock) {
6883 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6884 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6885 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6886 dumpLastANRLocked(pw);
6887 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6888 dumpLastANRTracesLocked(pw);
6889 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6890 dumpActivityStarterLocked(pw, dumpPackage);
6891 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6892 dumpActivityContainersLocked(pw);
6893 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6894 if (getRecentTasks() != null) {
6895 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6896 }
6897 }
6898 }
6899 }
6900
6901 @Override
6902 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6903 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6904 int wakefulness) {
6905 synchronized (mGlobalLock) {
6906 if (mHomeProcess != null && (dumpPackage == null
6907 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6908 if (needSep) {
6909 pw.println();
6910 needSep = false;
6911 }
6912 pw.println(" mHomeProcess: " + mHomeProcess);
6913 }
6914 if (mPreviousProcess != null && (dumpPackage == null
6915 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6916 if (needSep) {
6917 pw.println();
6918 needSep = false;
6919 }
6920 pw.println(" mPreviousProcess: " + mPreviousProcess);
6921 }
6922 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6923 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6924 StringBuilder sb = new StringBuilder(128);
6925 sb.append(" mPreviousProcessVisibleTime: ");
6926 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6927 pw.println(sb);
6928 }
6929 if (mHeavyWeightProcess != null && (dumpPackage == null
6930 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6931 if (needSep) {
6932 pw.println();
6933 needSep = false;
6934 }
6935 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6936 }
6937 if (dumpPackage == null) {
6938 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006939 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 }
6941 if (dumpAll) {
6942 if (dumpPackage == null) {
6943 pw.println(" mConfigWillChange: "
6944 + getTopDisplayFocusedStack().mConfigWillChange);
6945 }
6946 if (mCompatModePackages.getPackages().size() > 0) {
6947 boolean printed = false;
6948 for (Map.Entry<String, Integer> entry
6949 : mCompatModePackages.getPackages().entrySet()) {
6950 String pkg = entry.getKey();
6951 int mode = entry.getValue();
6952 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6953 continue;
6954 }
6955 if (!printed) {
6956 pw.println(" mScreenCompatPackages:");
6957 printed = true;
6958 }
6959 pw.println(" " + pkg + ": " + mode);
6960 }
6961 }
6962 }
6963
6964 if (dumpPackage == null) {
6965 pw.println(" mWakefulness="
6966 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006967 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006968 if (mRunningVoice != null) {
6969 pw.println(" mRunningVoice=" + mRunningVoice);
6970 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6971 }
6972 pw.println(" mSleeping=" + mSleeping);
6973 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6974 pw.println(" mVrController=" + mVrController);
6975 }
6976 if (mCurAppTimeTracker != null) {
6977 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6978 }
6979 if (mAllowAppSwitchUids.size() > 0) {
6980 boolean printed = false;
6981 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6982 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6983 for (int j = 0; j < types.size(); j++) {
6984 if (dumpPackage == null ||
6985 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6986 if (needSep) {
6987 pw.println();
6988 needSep = false;
6989 }
6990 if (!printed) {
6991 pw.println(" mAllowAppSwitchUids:");
6992 printed = true;
6993 }
6994 pw.print(" User ");
6995 pw.print(mAllowAppSwitchUids.keyAt(i));
6996 pw.print(": Type ");
6997 pw.print(types.keyAt(j));
6998 pw.print(" = ");
6999 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7000 pw.println();
7001 }
7002 }
7003 }
7004 }
7005 if (dumpPackage == null) {
7006 if (mController != null) {
7007 pw.println(" mController=" + mController
7008 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7009 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007010 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7011 pw.println(" mLaunchingActivityWakeLock="
7012 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007013 }
7014
7015 return needSep;
7016 }
7017 }
7018
7019 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007020 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7021 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007022 synchronized (mGlobalLock) {
7023 if (dumpPackage == null) {
7024 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7025 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007026 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7027 if (mRunningVoice != null) {
7028 final long vrToken = proto.start(
7029 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7030 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7031 mRunningVoice.toString());
7032 mVoiceWakeLock.writeToProto(
7033 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7034 proto.end(vrToken);
7035 }
7036 mVrController.writeToProto(proto,
7037 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 if (mController != null) {
7039 final long token = proto.start(CONTROLLER);
7040 proto.write(CONTROLLER, mController.toString());
7041 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7042 proto.end(token);
7043 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007044 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7045 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7046 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007047 }
7048
7049 if (mHomeProcess != null && (dumpPackage == null
7050 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007051 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007052 }
7053
7054 if (mPreviousProcess != null && (dumpPackage == null
7055 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007056 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007057 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7058 }
7059
7060 if (mHeavyWeightProcess != null && (dumpPackage == null
7061 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007062 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007063 }
7064
7065 for (Map.Entry<String, Integer> entry
7066 : mCompatModePackages.getPackages().entrySet()) {
7067 String pkg = entry.getKey();
7068 int mode = entry.getValue();
7069 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7070 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7071 proto.write(PACKAGE, pkg);
7072 proto.write(MODE, mode);
7073 proto.end(compatToken);
7074 }
7075 }
7076
7077 if (mCurAppTimeTracker != null) {
7078 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7079 }
7080
7081 }
7082 }
7083
7084 @Override
7085 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7086 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7087 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007088 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7089 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 }
7091
7092 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007093 public void dumpForOom(PrintWriter pw) {
7094 synchronized (mGlobalLock) {
7095 pw.println(" mHomeProcess: " + mHomeProcess);
7096 pw.println(" mPreviousProcess: " + mPreviousProcess);
7097 if (mHeavyWeightProcess != null) {
7098 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7099 }
7100 }
7101 }
7102
7103 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 public boolean canGcNow() {
7105 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007106 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 }
7108 }
7109
Riddle Hsua0536432019-02-16 00:38:59 +08007110 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007111 @Override
7112 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007113 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007114 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 return top != null ? top.app : null;
7116 }
7117 }
7118
Riddle Hsua0536432019-02-16 00:38:59 +08007119 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 @Override
7121 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007122 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007123 if (mRootActivityContainer != null) {
7124 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007125 }
7126 }
7127 }
7128
7129 @Override
7130 public void scheduleDestroyAllActivities(String reason) {
7131 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007132 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007133 }
7134 }
7135
7136 @Override
7137 public void removeUser(int userId) {
7138 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007139 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 }
7141 }
7142
7143 @Override
7144 public boolean switchUser(int userId, UserState userState) {
7145 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007146 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007147 }
7148 }
7149
7150 @Override
7151 public void onHandleAppCrash(WindowProcessController wpc) {
7152 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007153 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 }
7155 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007156
7157 @Override
7158 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7159 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007160 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007161 }
7162 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007163
Riddle Hsua0536432019-02-16 00:38:59 +08007164 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007165 @Override
7166 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007167 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007168 }
7169
Riddle Hsua0536432019-02-16 00:38:59 +08007170 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007171 @Override
7172 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007173 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007174 }
7175
Riddle Hsua0536432019-02-16 00:38:59 +08007176 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007177 @Override
7178 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007179 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007180 }
7181
Riddle Hsua0536432019-02-16 00:38:59 +08007182 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007183 @Override
7184 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007185 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007186 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007187
7188 @Override
7189 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007190 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007191 mPendingTempWhitelist.put(uid, tag);
7192 }
7193 }
7194
7195 @Override
7196 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007197 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007198 mPendingTempWhitelist.remove(uid);
7199 }
7200 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007201
7202 @Override
7203 public boolean handleAppCrashInActivityController(String processName, int pid,
7204 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7205 Runnable killCrashingAppCallback) {
7206 synchronized (mGlobalLock) {
7207 if (mController == null) {
7208 return false;
7209 }
7210
7211 try {
7212 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7213 stackTrace)) {
7214 killCrashingAppCallback.run();
7215 return true;
7216 }
7217 } catch (RemoteException e) {
7218 mController = null;
7219 Watchdog.getInstance().setActivityController(null);
7220 }
7221 return false;
7222 }
7223 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007224
7225 @Override
7226 public void removeRecentTasksByPackageName(String packageName, int userId) {
7227 synchronized (mGlobalLock) {
7228 mRecentTasks.removeTasksByPackageName(packageName, userId);
7229 }
7230 }
7231
7232 @Override
7233 public void cleanupRecentTasksForUser(int userId) {
7234 synchronized (mGlobalLock) {
7235 mRecentTasks.cleanupLocked(userId);
7236 }
7237 }
7238
7239 @Override
7240 public void loadRecentTasksForUser(int userId) {
7241 synchronized (mGlobalLock) {
7242 mRecentTasks.loadUserRecentsLocked(userId);
7243 }
7244 }
7245
7246 @Override
7247 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7248 synchronized (mGlobalLock) {
7249 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7250 }
7251 }
7252
7253 @Override
7254 public void flushRecentTasks() {
7255 mRecentTasks.flush();
7256 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007257
7258 @Override
7259 public WindowProcessController getHomeProcess() {
7260 synchronized (mGlobalLock) {
7261 return mHomeProcess;
7262 }
7263 }
7264
7265 @Override
7266 public WindowProcessController getPreviousProcess() {
7267 synchronized (mGlobalLock) {
7268 return mPreviousProcess;
7269 }
7270 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007271
7272 @Override
7273 public void clearLockedTasks(String reason) {
7274 synchronized (mGlobalLock) {
7275 getLockTaskController().clearLockedTasks(reason);
7276 }
7277 }
7278
7279 @Override
7280 public void updateUserConfiguration() {
7281 synchronized (mGlobalLock) {
7282 final Configuration configuration = new Configuration(getGlobalConfiguration());
7283 final int currentUserId = mAmInternal.getCurrentUserId();
7284 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7285 configuration, currentUserId, Settings.System.canWrite(mContext));
7286 updateConfigurationLocked(configuration, null /* starting */,
7287 false /* initLocale */, false /* persistent */, currentUserId,
7288 false /* deferResume */);
7289 }
7290 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007291
7292 @Override
7293 public boolean canShowErrorDialogs() {
7294 synchronized (mGlobalLock) {
7295 return mShowDialogs && !mSleeping && !mShuttingDown
7296 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7297 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7298 mAmInternal.getCurrentUserId())
7299 && !(UserManager.isDeviceInDemoMode(mContext)
7300 && mAmInternal.getCurrentUser().isDemo());
7301 }
7302 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007303
7304 @Override
7305 public void setProfileApp(String profileApp) {
7306 synchronized (mGlobalLock) {
7307 mProfileApp = profileApp;
7308 }
7309 }
7310
7311 @Override
7312 public void setProfileProc(WindowProcessController wpc) {
7313 synchronized (mGlobalLock) {
7314 mProfileProc = wpc;
7315 }
7316 }
7317
7318 @Override
7319 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7320 synchronized (mGlobalLock) {
7321 mProfilerInfo = profilerInfo;
7322 }
7323 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007324
7325 @Override
7326 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7327 synchronized (mGlobalLock) {
7328 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7329 }
7330 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007331
7332 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007333 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7334 boolean reducedResolution) {
7335 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7336 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007337 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007338
7339 @Override
7340 public boolean isUidForeground(int uid) {
7341 synchronized (mGlobalLock) {
7342 return ActivityTaskManagerService.this.isUidForeground(uid);
7343 }
7344 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007345
7346 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007347 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007348 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007349 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007350 }
7351 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007352
7353 @Override
7354 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007355 // Translate package names into UIDs
7356 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007357 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007358 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7359 if (uid >= 0) {
7360 result.add(uid);
7361 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007362 }
7363 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007364 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007365 }
7366 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007367 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007368}