blob: ea86f29ff0e0cc66b821e21196f990822c40fd2d [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Jeff Sharkey344ce7c2019-05-29 14:52:59 -0600268import com.android.server.uri.NeededUriGrants;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100315 // How long we permit background activity starts after an activity in the process
316 // started or finished.
317 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318
Wale Ogunwale98875612018-10-12 07:53:02 -0700319 /** Used to indicate that an app transition should be animated. */
320 static final boolean ANIMATE = true;
321
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700322 /** Hardware-reported OpenGLES version. */
323 final int GL_ES_VERSION;
324
Wale Ogunwale31913b52018-10-13 08:29:31 -0700325 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
326 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
327 public static final String DUMP_LASTANR_CMD = "lastanr" ;
328 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
329 public static final String DUMP_STARTER_CMD = "starter" ;
330 public static final String DUMP_CONTAINERS_CMD = "containers" ;
331 public static final String DUMP_RECENTS_CMD = "recents" ;
332 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
333
Wale Ogunwale64258362018-10-16 15:13:37 -0700334 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
335 public static final int RELAUNCH_REASON_NONE = 0;
336 /** This activity is being relaunched due to windowing mode change. */
337 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
338 /** This activity is being relaunched due to a free-resize operation. */
339 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
340
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700341 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700342
Wale Ogunwalef6733932018-06-27 05:14:34 -0700343 /**
344 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
345 * change at runtime. Use mContext for non-UI purposes.
346 */
347 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700349 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700352 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700353 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800354 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800355 @VisibleForTesting
356 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 PowerManagerInternal mPowerManagerInternal;
358 private UsageStatsManagerInternal mUsageStatsInternal;
359
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700360 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 IntentFirewall mIntentFirewall;
362
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700363 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800364 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 /**
366 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
367 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
368 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
369 *
370 * @see WindowManagerThreadPriorityBooster
371 */
372 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700373 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800374 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700375 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700376 private UserManagerService mUserManager;
377 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700378 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800379 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700380 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** All processes currently running that might have a window organized by name. */
382 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100383 /** All processes we currently have running mapped by pid and uid */
384 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** This is the process holding what we currently consider to be the "home" activity. */
386 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700387 /** The currently running heavy-weight process, if any. */
388 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700389 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /**
391 * This is the process holding the activity the user last visited that is in a different process
392 * from the one they are currently in.
393 */
394 WindowProcessController mPreviousProcess;
395 /** The time at which the previous process was last visible. */
396 long mPreviousProcessVisibleTime;
397
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700398 /** List of intents that were used to start the most recent tasks. */
399 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700400 /** State of external calls telling us if the device is awake or asleep. */
401 private boolean mKeyguardShown = false;
402
403 // Wrapper around VoiceInteractionServiceManager
404 private AssistUtils mAssistUtils;
405
406 // VoiceInteraction session ID that changes for each new request except when
407 // being called for multi-window assist in a single session.
408 private int mViSessionId = 1000;
409
410 // How long to wait in getAssistContextExtras for the activity and foreground services
411 // to respond with the result.
412 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
413
414 // How long top wait when going through the modern assist (which doesn't need to block
415 // on getting this result before starting to launch its UI).
416 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
417
418 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
419 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
420
Alison Cichowlas3e340502018-08-07 17:15:01 -0400421 // Permission tokens are used to temporarily granted a trusted app the ability to call
422 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
423 // showing any appropriate error messages to the user.
424 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
425 10 * MINUTE_IN_MILLIS;
426
427 // How long before the service actually expires a token. This is slightly longer than
428 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
429 // expiration exception.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
431 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
432
433 // How long the service will remember expired tokens, for the purpose of providing error
434 // messaging when a client uses an expired token.
435 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
436 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
437
Marvin Ramin830d4e32019-03-12 13:16:58 +0100438 // How long to whitelist the Services for when requested.
439 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
440
Alison Cichowlas3e340502018-08-07 17:15:01 -0400441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
467 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
554 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
603 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
604 // automatically. Important for devices without direct input devices.
605 private boolean mShowDialogs = true;
606
607 /** Set if we are shutting down the system, similar to sleeping. */
608 boolean mShuttingDown = false;
609
610 /**
611 * We want to hold a wake lock while running a voice interaction session, since
612 * this may happen with the screen off and we need to keep the CPU running to
613 * be able to continue to interact with the user.
614 */
615 PowerManager.WakeLock mVoiceWakeLock;
616
617 /**
618 * Set while we are running a voice interaction. This overrides sleeping while it is active.
619 */
620 IVoiceInteractionSession mRunningVoice;
621
622 /**
623 * The last resumed activity. This is identical to the current resumed activity most
624 * of the time but could be different when we're pausing one activity before we resume
625 * another activity.
626 */
627 ActivityRecord mLastResumedActivity;
628
629 /**
630 * The activity that is currently being traced as the active resumed activity.
631 *
632 * @see #updateResumedAppTrace
633 */
634 private @Nullable ActivityRecord mTracedResumedActivity;
635
636 /** If non-null, we are tracking the time the user spends in the currently focused app. */
637 AppTimeTracker mCurAppTimeTracker;
638
Wale Ogunwale008163e2018-07-23 23:11:08 -0700639 private AppWarnings mAppWarnings;
640
Wale Ogunwale53783742018-09-16 10:21:51 -0700641 /**
642 * Packages that the user has asked to have run in screen size
643 * compatibility mode instead of filling the screen.
644 */
645 CompatModePackages mCompatModePackages;
646
Wale Ogunwalef6733932018-06-27 05:14:34 -0700647 private FontScaleSettingObserver mFontScaleSettingObserver;
648
Ricky Wai96f5c352019-04-10 18:40:17 +0100649 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000650
Wale Ogunwalef6733932018-06-27 05:14:34 -0700651 private final class FontScaleSettingObserver extends ContentObserver {
652 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
653 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
654
655 public FontScaleSettingObserver() {
656 super(mH);
657 final ContentResolver resolver = mContext.getContentResolver();
658 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
659 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
660 UserHandle.USER_ALL);
661 }
662
663 @Override
664 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
665 if (mFontScaleUri.equals(uri)) {
666 updateFontScaleIfNeeded(userId);
667 } else if (mHideErrorDialogsUri.equals(uri)) {
668 synchronized (mGlobalLock) {
669 updateShouldShowDialogsLocked(getGlobalConfiguration());
670 }
671 }
672 }
673 }
674
Riddle Hsua0536432019-02-16 00:38:59 +0800675 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
676 @Target(ElementType.METHOD)
677 @Retention(RetentionPolicy.SOURCE)
678 @interface HotPath {
679 int NONE = 0;
680 int OOM_ADJUSTMENT = 1;
681 int LRU_UPDATE = 2;
682 int PROCESS_CHANGE = 3;
683 int caller() default NONE;
684 }
685
Charles Chen8d98dd22018-12-26 17:36:54 +0800686 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
687 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700688 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700689 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700690 mSystemThread = ActivityThread.currentActivityThread();
691 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700692 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800693 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700694 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700695 }
696
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700697 public void onSystemReady() {
698 synchronized (mGlobalLock) {
699 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
700 PackageManager.FEATURE_CANT_SAVE_STATE);
701 mAssistUtils = new AssistUtils(mContext);
702 mVrController.onSystemReady();
703 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700704 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700705 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700706 }
707
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700708 public void onInitPowerManagement() {
709 synchronized (mGlobalLock) {
710 mStackSupervisor.initPowerManagement();
711 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
712 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
713 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
714 mVoiceWakeLock.setReferenceCounted(false);
715 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700716 }
717
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700719 mFontScaleSettingObserver = new FontScaleSettingObserver();
720 }
721
Wale Ogunwale59507092018-10-29 09:00:30 -0700722 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700723 final boolean freeformWindowManagement =
724 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
725 || Settings.Global.getInt(
726 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
727
728 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
729 final boolean supportsPictureInPicture = supportsMultiWindow &&
730 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
731 final boolean supportsSplitScreenMultiWindow =
732 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
733 final boolean supportsMultiDisplay = mContext.getPackageManager()
734 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
736 final boolean forceResizable = Settings.Global.getInt(
737 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700738 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700739
740 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900741 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700742
743 final Configuration configuration = new Configuration();
744 Settings.System.getConfiguration(resolver, configuration);
745 if (forceRtl) {
746 // This will take care of setting the correct layout direction flags
747 configuration.setLayoutDirection(configuration.locale);
748 }
749
750 synchronized (mGlobalLock) {
751 mForceResizableActivities = forceResizable;
752 final boolean multiWindowFormEnabled = freeformWindowManagement
753 || supportsSplitScreenMultiWindow
754 || supportsPictureInPicture
755 || supportsMultiDisplay;
756 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
757 mSupportsMultiWindow = true;
758 mSupportsFreeformWindowManagement = freeformWindowManagement;
759 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
760 mSupportsPictureInPicture = supportsPictureInPicture;
761 mSupportsMultiDisplay = supportsMultiDisplay;
762 } else {
763 mSupportsMultiWindow = false;
764 mSupportsFreeformWindowManagement = false;
765 mSupportsSplitScreenMultiWindow = false;
766 mSupportsPictureInPicture = false;
767 mSupportsMultiDisplay = false;
768 }
769 mWindowManager.setForceResizableTasks(mForceResizableActivities);
770 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700771 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
772 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700773 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 // This happens before any activities are started, so we can change global configuration
775 // in-place.
776 updateConfigurationLocked(configuration, null, true);
777 final Configuration globalConfig = getGlobalConfiguration();
778 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
779
780 // Load resources only after the current configuration has been set.
781 final Resources res = mContext.getResources();
782 mThumbnailWidth = res.getDimensionPixelSize(
783 com.android.internal.R.dimen.thumbnail_width);
784 mThumbnailHeight = res.getDimensionPixelSize(
785 com.android.internal.R.dimen.thumbnail_height);
786
787 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
788 mFullscreenThumbnailScale = (float) res
789 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
790 (float) globalConfig.screenWidthDp;
791 } else {
792 mFullscreenThumbnailScale = res.getFraction(
793 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
794 }
795 }
796 }
797
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800798 public WindowManagerGlobalLock getGlobalLock() {
799 return mGlobalLock;
800 }
801
Yunfan Chen585f2932019-01-29 16:04:45 +0900802 /** For test purpose only. */
803 @VisibleForTesting
804 public ActivityTaskManagerInternal getAtmInternal() {
805 return mInternal;
806 }
807
Riddle Hsud93a6c42018-11-29 21:50:06 +0800808 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
809 Looper looper) {
810 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700811 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700813 final File systemDir = SystemServiceManager.ensureSystemDir();
814 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
815 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700816 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817
818 mTempConfig.setToDefaults();
819 mTempConfig.setLocales(LocaleList.getDefault());
820 mConfigurationSeq = mTempConfig.seq = 1;
821 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800822 mRootActivityContainer = new RootActivityContainer(this);
823 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700825 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700827 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700828 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700829 mRecentTasks = createRecentTasks();
830 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mKeyguardController = mStackSupervisor.getKeyguardController();
833 }
834
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700835 public void onActivityManagerInternalAdded() {
836 synchronized (mGlobalLock) {
837 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
838 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
839 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700840 }
841
Yunfan Chen75157d72018-07-27 14:47:21 +0900842 int increaseConfigurationSeqLocked() {
843 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
844 return mConfigurationSeq;
845 }
846
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700847 protected ActivityStackSupervisor createStackSupervisor() {
848 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
849 supervisor.initialize();
850 return supervisor;
851 }
852
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700853 public void setWindowManager(WindowManagerService wm) {
854 synchronized (mGlobalLock) {
855 mWindowManager = wm;
856 mLockTaskController.setWindowManager(wm);
857 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800858 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700859 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700860 }
861
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700862 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
863 synchronized (mGlobalLock) {
864 mUsageStatsInternal = usageStatsManager;
865 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700866 }
867
Wale Ogunwalef6733932018-06-27 05:14:34 -0700868 UserManagerService getUserManager() {
869 if (mUserManager == null) {
870 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
871 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
872 }
873 return mUserManager;
874 }
875
876 AppOpsService getAppOpsService() {
877 if (mAppOpsService == null) {
878 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
879 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
880 }
881 return mAppOpsService;
882 }
883
884 boolean hasUserRestriction(String restriction, int userId) {
885 return getUserManager().hasUserRestriction(restriction, userId);
886 }
887
Michal Karpinski15486842019-04-25 17:33:42 +0100888 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
889 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
890 callingUid, callingPackage);
891 if (mode == AppOpsManager.MODE_DEFAULT) {
892 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
893 == PERMISSION_GRANTED;
894 }
895 return mode == AppOpsManager.MODE_ALLOWED;
896 }
897
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700898 protected RecentTasks createRecentTasks() {
899 return new RecentTasks(this, mStackSupervisor);
900 }
901
902 RecentTasks getRecentTasks() {
903 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700904 }
905
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700906 ClientLifecycleManager getLifecycleManager() {
907 return mLifecycleManager;
908 }
909
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700910 ActivityStartController getActivityStartController() {
911 return mActivityStartController;
912 }
913
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700914 TaskChangeNotificationController getTaskChangeNotificationController() {
915 return mTaskChangeNotificationController;
916 }
917
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700918 LockTaskController getLockTaskController() {
919 return mLockTaskController;
920 }
921
Yunfan Chen75157d72018-07-27 14:47:21 +0900922 /**
923 * Return the global configuration used by the process corresponding to the input pid. This is
924 * usually the global configuration with some overrides specific to that process.
925 */
926 Configuration getGlobalConfigurationForCallingPid() {
927 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800928 return getGlobalConfigurationForPid(pid);
929 }
930
931 /**
932 * Return the global configuration used by the process corresponding to the given pid.
933 */
934 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900935 if (pid == MY_PID || pid < 0) {
936 return getGlobalConfiguration();
937 }
938 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100939 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900940 return app != null ? app.getConfiguration() : getGlobalConfiguration();
941 }
942 }
943
944 /**
945 * Return the device configuration info used by the process corresponding to the input pid.
946 * The value is consistent with the global configuration for the process.
947 */
948 @Override
949 public ConfigurationInfo getDeviceConfigurationInfo() {
950 ConfigurationInfo config = new ConfigurationInfo();
951 synchronized (mGlobalLock) {
952 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
953 config.reqTouchScreen = globalConfig.touchscreen;
954 config.reqKeyboardType = globalConfig.keyboard;
955 config.reqNavigation = globalConfig.navigation;
956 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
957 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
958 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
959 }
960 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
961 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
962 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
963 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700964 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900965 }
966 return config;
967 }
968
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700969 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700970 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700971 }
972
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700973 public static final class Lifecycle extends SystemService {
974 private final ActivityTaskManagerService mService;
975
976 public Lifecycle(Context context) {
977 super(context);
978 mService = new ActivityTaskManagerService(context);
979 }
980
981 @Override
982 public void onStart() {
983 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700984 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700985 }
986
Garfield Tan891146c2018-10-09 12:14:00 -0700987 @Override
988 public void onUnlockUser(int userId) {
989 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800990 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700991 }
992 }
993
994 @Override
995 public void onCleanupUser(int userId) {
996 synchronized (mService.getGlobalLock()) {
997 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
998 }
999 }
1000
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001001 public ActivityTaskManagerService getService() {
1002 return mService;
1003 }
1004 }
1005
1006 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001007 public final int startActivity(IApplicationThread caller, String callingPackage,
1008 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1009 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1010 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1011 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1012 UserHandle.getCallingUserId());
1013 }
1014
1015 @Override
1016 public final int startActivities(IApplicationThread caller, String callingPackage,
1017 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1018 int userId) {
1019 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001020 enforceNotIsolatedCaller(reason);
1021 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001023 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1024 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1025 reason, null /* originatingPendingIntent */,
1026 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1031 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1032 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1033 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1034 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1035 true /*validateIncomingUser*/);
1036 }
1037
1038 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1039 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1040 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1041 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001042 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001044 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1046
1047 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001048 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001049 .setCaller(caller)
1050 .setCallingPackage(callingPackage)
1051 .setResolvedType(resolvedType)
1052 .setResultTo(resultTo)
1053 .setResultWho(resultWho)
1054 .setRequestCode(requestCode)
1055 .setStartFlags(startFlags)
1056 .setProfilerInfo(profilerInfo)
1057 .setActivityOptions(bOptions)
1058 .setMayWait(userId)
1059 .execute();
1060
1061 }
1062
1063 @Override
1064 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1065 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001066 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1067 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001068 // Refuse possible leaked file descriptors
1069 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1070 throw new IllegalArgumentException("File descriptors passed in Intent");
1071 }
1072
1073 if (!(target instanceof PendingIntentRecord)) {
1074 throw new IllegalArgumentException("Bad PendingIntent object");
1075 }
1076
1077 PendingIntentRecord pir = (PendingIntentRecord)target;
1078
1079 synchronized (mGlobalLock) {
1080 // If this is coming from the currently resumed activity, it is
1081 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001082 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 if (stack.mResumedActivity != null &&
1084 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001085 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001086 }
1087 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001088 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 }
1091
1092 @Override
1093 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1094 Bundle bOptions) {
1095 // Refuse possible leaked file descriptors
1096 if (intent != null && intent.hasFileDescriptors()) {
1097 throw new IllegalArgumentException("File descriptors passed in Intent");
1098 }
1099 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1100
1101 synchronized (mGlobalLock) {
1102 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1103 if (r == null) {
1104 SafeActivityOptions.abort(options);
1105 return false;
1106 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001107 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001108 // The caller is not running... d'oh!
1109 SafeActivityOptions.abort(options);
1110 return false;
1111 }
1112 intent = new Intent(intent);
1113 // The caller is not allowed to change the data.
1114 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1115 // And we are resetting to find the next component...
1116 intent.setComponent(null);
1117
1118 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1119
1120 ActivityInfo aInfo = null;
1121 try {
1122 List<ResolveInfo> resolves =
1123 AppGlobals.getPackageManager().queryIntentActivities(
1124 intent, r.resolvedType,
1125 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1126 UserHandle.getCallingUserId()).getList();
1127
1128 // Look for the original activity in the list...
1129 final int N = resolves != null ? resolves.size() : 0;
1130 for (int i=0; i<N; i++) {
1131 ResolveInfo rInfo = resolves.get(i);
1132 if (rInfo.activityInfo.packageName.equals(r.packageName)
1133 && rInfo.activityInfo.name.equals(r.info.name)) {
1134 // We found the current one... the next matching is
1135 // after it.
1136 i++;
1137 if (i<N) {
1138 aInfo = resolves.get(i).activityInfo;
1139 }
1140 if (debug) {
1141 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1142 + "/" + r.info.name);
1143 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1144 ? "null" : aInfo.packageName + "/" + aInfo.name));
1145 }
1146 break;
1147 }
1148 }
1149 } catch (RemoteException e) {
1150 }
1151
1152 if (aInfo == null) {
1153 // Nobody who is next!
1154 SafeActivityOptions.abort(options);
1155 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1156 return false;
1157 }
1158
1159 intent.setComponent(new ComponentName(
1160 aInfo.applicationInfo.packageName, aInfo.name));
1161 intent.setFlags(intent.getFlags()&~(
1162 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1163 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1164 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1165 FLAG_ACTIVITY_NEW_TASK));
1166
1167 // Okay now we need to start the new activity, replacing the currently running activity.
1168 // This is a little tricky because we want to start the new one as if the current one is
1169 // finished, but not finish the current one first so that there is no flicker.
1170 // And thus...
1171 final boolean wasFinishing = r.finishing;
1172 r.finishing = true;
1173
1174 // Propagate reply information over to the new activity.
1175 final ActivityRecord resultTo = r.resultTo;
1176 final String resultWho = r.resultWho;
1177 final int requestCode = r.requestCode;
1178 r.resultTo = null;
1179 if (resultTo != null) {
1180 resultTo.removeResultsLocked(r, resultWho, requestCode);
1181 }
1182
1183 final long origId = Binder.clearCallingIdentity();
1184 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001185 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001186 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001187 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001188 .setResolvedType(r.resolvedType)
1189 .setActivityInfo(aInfo)
1190 .setResultTo(resultTo != null ? resultTo.appToken : null)
1191 .setResultWho(resultWho)
1192 .setRequestCode(requestCode)
1193 .setCallingPid(-1)
1194 .setCallingUid(r.launchedFromUid)
1195 .setCallingPackage(r.launchedFromPackage)
1196 .setRealCallingPid(-1)
1197 .setRealCallingUid(r.launchedFromUid)
1198 .setActivityOptions(options)
1199 .execute();
1200 Binder.restoreCallingIdentity(origId);
1201
1202 r.finishing = wasFinishing;
1203 if (res != ActivityManager.START_SUCCESS) {
1204 return false;
1205 }
1206 return true;
1207 }
1208 }
1209
1210 @Override
1211 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1212 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1213 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1214 final WaitResult res = new WaitResult();
1215 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001216 enforceNotIsolatedCaller("startActivityAndWait");
1217 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1218 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001220 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 .setCaller(caller)
1222 .setCallingPackage(callingPackage)
1223 .setResolvedType(resolvedType)
1224 .setResultTo(resultTo)
1225 .setResultWho(resultWho)
1226 .setRequestCode(requestCode)
1227 .setStartFlags(startFlags)
1228 .setActivityOptions(bOptions)
1229 .setMayWait(userId)
1230 .setProfilerInfo(profilerInfo)
1231 .setWaitResult(res)
1232 .execute();
1233 }
1234 return res;
1235 }
1236
1237 @Override
1238 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1239 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1240 int startFlags, Configuration config, Bundle bOptions, int userId) {
1241 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) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001291 // permission grants) as any app that may launch one of your own activities. So we only
1292 // allow this in two cases:
1293 // 1) The caller is an activity that is part of the core framework, and then only when it
1294 // is running as the system.
1295 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1296 // can only be requested by a system activity, which may then delegate this call to
1297 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 final ActivityRecord sourceRecord;
1299 final int targetUid;
1300 final String targetPackage;
1301 final boolean isResolver;
1302 synchronized (mGlobalLock) {
1303 if (resultTo == null) {
1304 throw new SecurityException("Must be called from an activity");
1305 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001306 final IBinder sourceToken;
1307 if (permissionToken != null) {
1308 // To even attempt to use a permissionToken, an app must also have this signature
1309 // permission.
1310 mAmInternal.enforceCallingPermission(
1311 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1312 "startActivityAsCaller");
1313 // If called with a permissionToken, we want the sourceRecord from the delegator
1314 // activity that requested this token.
1315 sourceToken = mStartActivitySources.remove(permissionToken);
1316 if (sourceToken == null) {
1317 // Invalid permissionToken, check if it recently expired.
1318 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1319 throw new SecurityException("Called with expired permission token: "
1320 + permissionToken);
1321 } else {
1322 throw new SecurityException("Called with invalid permission token: "
1323 + permissionToken);
1324 }
1325 }
1326 } else {
1327 // This method was called directly by the source.
1328 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001330
Wale Ogunwaled32da472018-11-16 07:19:28 -08001331 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001332 if (sourceRecord == null) {
1333 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001334 }
1335 if (sourceRecord.app == null) {
1336 throw new SecurityException("Called without a process attached to activity");
1337 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001338
1339 // Whether called directly or from a delegate, the source activity must be from the
1340 // android package.
1341 if (!sourceRecord.info.packageName.equals("android")) {
1342 throw new SecurityException("Must be called from an activity that is "
1343 + "declared in the android package");
1344 }
1345
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001346 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 // This is still okay, as long as this activity is running under the
1348 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001349 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001351 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001352 + " must be system uid or original calling uid "
1353 + sourceRecord.launchedFromUid);
1354 }
1355 }
1356 if (ignoreTargetSecurity) {
1357 if (intent.getComponent() == null) {
1358 throw new SecurityException(
1359 "Component must be specified with ignoreTargetSecurity");
1360 }
1361 if (intent.getSelector() != null) {
1362 throw new SecurityException(
1363 "Selector not allowed with ignoreTargetSecurity");
1364 }
1365 }
1366 targetUid = sourceRecord.launchedFromUid;
1367 targetPackage = sourceRecord.launchedFromPackage;
1368 isResolver = sourceRecord.isResolverOrChildActivity();
1369 }
1370
1371 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001372 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 }
1374
1375 // TODO: Switch to user app stacks here.
1376 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001377 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 .setCallingUid(targetUid)
1379 .setCallingPackage(targetPackage)
1380 .setResolvedType(resolvedType)
1381 .setResultTo(resultTo)
1382 .setResultWho(resultWho)
1383 .setRequestCode(requestCode)
1384 .setStartFlags(startFlags)
1385 .setActivityOptions(bOptions)
1386 .setMayWait(userId)
1387 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1388 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001389 // The target may well be in the background, which would normally prevent it
1390 // from starting an activity. Here we definitely want the start to succeed.
1391 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001392 .execute();
1393 } catch (SecurityException e) {
1394 // XXX need to figure out how to propagate to original app.
1395 // A SecurityException here is generally actually a fault of the original
1396 // calling activity (such as a fairly granting permissions), so propagate it
1397 // back to them.
1398 /*
1399 StringBuilder msg = new StringBuilder();
1400 msg.append("While launching");
1401 msg.append(intent.toString());
1402 msg.append(": ");
1403 msg.append(e.getMessage());
1404 */
1405 throw e;
1406 }
1407 }
1408
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1410 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1411 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1412 }
1413
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 @Override
1415 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1416 Intent intent, String resolvedType, IVoiceInteractionSession session,
1417 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1418 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001419 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 if (session == null || interactor == null) {
1421 throw new NullPointerException("null session or interactor");
1422 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001425 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .setCallingUid(callingUid)
1427 .setCallingPackage(callingPackage)
1428 .setResolvedType(resolvedType)
1429 .setVoiceSession(session)
1430 .setVoiceInteractor(interactor)
1431 .setStartFlags(startFlags)
1432 .setProfilerInfo(profilerInfo)
1433 .setActivityOptions(bOptions)
1434 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001435 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 .execute();
1437 }
1438
1439 @Override
1440 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1441 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001442 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1443 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001445 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .setCallingUid(callingUid)
1447 .setCallingPackage(callingPackage)
1448 .setResolvedType(resolvedType)
1449 .setActivityOptions(bOptions)
1450 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001451 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .execute();
1453 }
1454
1455 @Override
1456 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1457 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001458 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 final int callingPid = Binder.getCallingPid();
1460 final long origId = Binder.clearCallingIdentity();
1461 try {
1462 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001463 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1464 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465
1466 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001467 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1468 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1470 recentsUid, assistDataReceiver);
1471 }
1472 } finally {
1473 Binder.restoreCallingIdentity(origId);
1474 }
1475 }
1476
1477 @Override
1478 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001479 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 "startActivityFromRecents()");
1481
1482 final int callingPid = Binder.getCallingPid();
1483 final int callingUid = Binder.getCallingUid();
1484 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1485 final long origId = Binder.clearCallingIdentity();
1486 try {
1487 synchronized (mGlobalLock) {
1488 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1489 safeOptions);
1490 }
1491 } finally {
1492 Binder.restoreCallingIdentity(origId);
1493 }
1494 }
1495
1496 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001497 * Public API to check if the client is allowed to start an activity on specified display.
1498 *
1499 * If the target display is private or virtual, some restrictions will apply.
1500 *
1501 * @param displayId Target display id.
1502 * @param intent Intent used to launch the activity.
1503 * @param resolvedType The MIME type of the intent.
1504 * @param userId The id of the user for whom the call is made.
1505 * @return {@code true} if a call to start an activity on the target display should succeed and
1506 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1507 */
1508 @Override
1509 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1510 String resolvedType, int userId) {
1511 final int callingUid = Binder.getCallingUid();
1512 final int callingPid = Binder.getCallingPid();
1513 final long origId = Binder.clearCallingIdentity();
1514
1515 try {
1516 // Collect information about the target of the Intent.
1517 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1518 0 /* startFlags */, null /* profilerInfo */, userId,
1519 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1520 UserHandle.USER_NULL));
1521 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1522
1523 synchronized (mGlobalLock) {
1524 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1525 aInfo);
1526 }
1527 } finally {
1528 Binder.restoreCallingIdentity(origId);
1529 }
1530 }
1531
1532 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533 * This is the internal entry point for handling Activity.finish().
1534 *
1535 * @param token The Binder token referencing the Activity we want to finish.
1536 * @param resultCode Result code, if any, from this Activity.
1537 * @param resultData Result data (Intent), if any, from this Activity.
1538 * @param finishTask Whether to finish the task associated with this Activity.
1539 *
1540 * @return Returns true if the activity successfully finished, or false if it is still running.
1541 */
1542 @Override
1543 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1544 int finishTask) {
1545 // Refuse possible leaked file descriptors
1546 if (resultData != null && resultData.hasFileDescriptors()) {
1547 throw new IllegalArgumentException("File descriptors passed in Intent");
1548 }
1549
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001550 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001552 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 if (r == null) {
1554 return true;
1555 }
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001556 }
1557
1558 // Carefully collect grants without holding lock
1559 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
1560 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
1561
1562 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001564 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 ActivityRecord rootR = tr.getRootActivity();
1566 if (rootR == null) {
1567 Slog.w(TAG, "Finishing task with all activities already finished");
1568 }
1569 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1570 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001571 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 return false;
1573 }
1574
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001575 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1576 // We should consolidate.
1577 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001579 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 if (next != null) {
1581 // ask watcher if this is allowed
1582 boolean resumeOK = true;
1583 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001584 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001586 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001587 Watchdog.getInstance().setActivityController(null);
1588 }
1589
1590 if (!resumeOK) {
1591 Slog.i(TAG, "Not finishing activity because controller resumed");
1592 return false;
1593 }
1594 }
1595 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001596
1597 // note down that the process has finished an activity and is in background activity
1598 // starts grace period
1599 if (r.app != null) {
1600 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1601 }
1602
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 final long origId = Binder.clearCallingIdentity();
1604 try {
1605 boolean res;
1606 final boolean finishWithRootActivity =
1607 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1608 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1609 || (finishWithRootActivity && r == rootR)) {
1610 // If requested, remove the task that is associated to this activity only if it
1611 // was the root activity in the task. The result code and data is ignored
1612 // because we don't support returning them across task boundaries. Also, to
1613 // keep backwards compatibility we remove the task from recents when finishing
1614 // task with root activity.
1615 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1616 finishWithRootActivity, "finish-activity");
1617 if (!res) {
1618 Slog.i(TAG, "Removing task failed to finish activity");
1619 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001620 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001621 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 } else {
1623 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001624 resultData, resultGrants, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 if (!res) {
1626 Slog.i(TAG, "Failed to finish by app-request");
1627 }
1628 }
1629 return res;
1630 } finally {
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633 }
1634 }
1635
1636 @Override
1637 public boolean finishActivityAffinity(IBinder token) {
1638 synchronized (mGlobalLock) {
1639 final long origId = Binder.clearCallingIdentity();
1640 try {
1641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1642 if (r == null) {
1643 return false;
1644 }
1645
1646 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1647 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001648 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001649 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 return false;
1651 }
1652 return task.getStack().finishActivityAffinityLocked(r);
1653 } finally {
1654 Binder.restoreCallingIdentity(origId);
1655 }
1656 }
1657 }
1658
1659 @Override
1660 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1661 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001662 try {
1663 WindowProcessController proc = null;
1664 synchronized (mGlobalLock) {
1665 ActivityStack stack = ActivityRecord.getStackLocked(token);
1666 if (stack == null) {
1667 return;
1668 }
1669 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1670 false /* fromTimeout */, false /* processPausingActivities */, config);
1671 if (r != null) {
1672 proc = r.app;
1673 }
1674 if (stopProfiling && proc != null) {
1675 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001678 } finally {
1679 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001680 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 }
1682
1683 @Override
1684 public final void activityResumed(IBinder token) {
1685 final long origId = Binder.clearCallingIdentity();
1686 synchronized (mGlobalLock) {
1687 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001688 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001694 public final void activityTopResumedStateLost() {
1695 final long origId = Binder.clearCallingIdentity();
1696 synchronized (mGlobalLock) {
1697 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1698 }
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701
1702 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 public final void activityPaused(IBinder token) {
1704 final long origId = Binder.clearCallingIdentity();
1705 synchronized (mGlobalLock) {
1706 ActivityStack stack = ActivityRecord.getStackLocked(token);
1707 if (stack != null) {
1708 stack.activityPausedLocked(token, false);
1709 }
1710 }
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713
1714 @Override
1715 public final void activityStopped(IBinder token, Bundle icicle,
1716 PersistableBundle persistentState, CharSequence description) {
1717 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1718
1719 // Refuse possible leaked file descriptors
1720 if (icicle != null && icicle.hasFileDescriptors()) {
1721 throw new IllegalArgumentException("File descriptors passed in Bundle");
1722 }
1723
1724 final long origId = Binder.clearCallingIdentity();
1725
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001726 String restartingName = null;
1727 int restartingUid = 0;
1728 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001732 if (r.attachedToProcess()
1733 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1734 // The activity was requested to restart from
1735 // {@link #restartActivityProcessIfVisible}.
1736 restartingName = r.app.mName;
1737 restartingUid = r.app.mUid;
1738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 r.activityStoppedLocked(icicle, persistentState, description);
1740 }
1741 }
1742
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 if (restartingName != null) {
1744 // In order to let the foreground activity can be restarted with its saved state from
1745 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1746 // until the activity reports stopped with the state. And the activity record will be
1747 // kept because the record state is restarting, then the activity will be restarted
1748 // immediately if it is still the top one.
1749 mStackSupervisor.removeRestartTimeouts(r);
1750 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1751 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753
1754 Binder.restoreCallingIdentity(origId);
1755 }
1756
1757 @Override
1758 public final void activityDestroyed(IBinder token) {
1759 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1760 synchronized (mGlobalLock) {
1761 ActivityStack stack = ActivityRecord.getStackLocked(token);
1762 if (stack != null) {
1763 stack.activityDestroyedLocked(token, "activityDestroyed");
1764 }
1765 }
1766 }
1767
1768 @Override
1769 public final void activityRelaunched(IBinder token) {
1770 final long origId = Binder.clearCallingIdentity();
1771 synchronized (mGlobalLock) {
1772 mStackSupervisor.activityRelaunchedLocked(token);
1773 }
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776
1777 public final void activitySlept(IBinder token) {
1778 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1779
1780 final long origId = Binder.clearCallingIdentity();
1781
1782 synchronized (mGlobalLock) {
1783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1784 if (r != null) {
1785 mStackSupervisor.activitySleptLocked(r);
1786 }
1787 }
1788
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791
1792 @Override
1793 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1794 synchronized (mGlobalLock) {
1795 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1796 if (r == null) {
1797 return;
1798 }
1799 final long origId = Binder.clearCallingIdentity();
1800 try {
1801 r.setRequestedOrientation(requestedOrientation);
1802 } finally {
1803 Binder.restoreCallingIdentity(origId);
1804 }
1805 }
1806 }
1807
1808 @Override
1809 public int getRequestedOrientation(IBinder token) {
1810 synchronized (mGlobalLock) {
1811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1812 if (r == null) {
1813 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1814 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001815 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001816 }
1817 }
1818
1819 @Override
1820 public void setImmersive(IBinder token, boolean immersive) {
1821 synchronized (mGlobalLock) {
1822 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1823 if (r == null) {
1824 throw new IllegalArgumentException();
1825 }
1826 r.immersive = immersive;
1827
1828 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001829 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001831 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 }
1833 }
1834 }
1835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 void applyUpdateLockStateLocked(ActivityRecord r) {
1837 // Modifications to the UpdateLock state are done on our handler, outside
1838 // the activity manager's locks. The new state is determined based on the
1839 // state *now* of the relevant activity record. The object is passed to
1840 // the handler solely for logging detail, not to be consulted/modified.
1841 final boolean nextState = r != null && r.immersive;
1842 mH.post(() -> {
1843 if (mUpdateLock.isHeld() != nextState) {
1844 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1845 "Applying new update lock state '" + nextState + "' for " + r);
1846 if (nextState) {
1847 mUpdateLock.acquire();
1848 } else {
1849 mUpdateLock.release();
1850 }
1851 }
1852 });
1853 }
1854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 @Override
1856 public boolean isImmersive(IBinder token) {
1857 synchronized (mGlobalLock) {
1858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 throw new IllegalArgumentException();
1861 }
1862 return r.immersive;
1863 }
1864 }
1865
1866 @Override
1867 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001870 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 return (r != null) ? r.immersive : false;
1872 }
1873 }
1874
1875 @Override
1876 public void overridePendingTransition(IBinder token, String packageName,
1877 int enterAnim, int exitAnim) {
1878 synchronized (mGlobalLock) {
1879 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1880 if (self == null) {
1881 return;
1882 }
1883
1884 final long origId = Binder.clearCallingIdentity();
1885
1886 if (self.isState(
1887 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001888 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001889 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 }
1891
1892 Binder.restoreCallingIdentity(origId);
1893 }
1894 }
1895
1896 @Override
1897 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001900 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 if (r == null) {
1902 return ActivityManager.COMPAT_MODE_UNKNOWN;
1903 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001904 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 }
1906 }
1907
1908 @Override
1909 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001910 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001912 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001914 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 if (r == null) {
1916 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1917 return;
1918 }
1919 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001920 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 }
1922 }
1923
1924 @Override
1925 public int getLaunchedFromUid(IBinder activityToken) {
1926 ActivityRecord srec;
1927 synchronized (mGlobalLock) {
1928 srec = ActivityRecord.forTokenLocked(activityToken);
1929 }
1930 if (srec == null) {
1931 return -1;
1932 }
1933 return srec.launchedFromUid;
1934 }
1935
1936 @Override
1937 public String getLaunchedFromPackage(IBinder activityToken) {
1938 ActivityRecord srec;
1939 synchronized (mGlobalLock) {
1940 srec = ActivityRecord.forTokenLocked(activityToken);
1941 }
1942 if (srec == null) {
1943 return null;
1944 }
1945 return srec.launchedFromPackage;
1946 }
1947
1948 @Override
1949 public boolean convertFromTranslucent(IBinder token) {
1950 final long origId = Binder.clearCallingIdentity();
1951 try {
1952 synchronized (mGlobalLock) {
1953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1954 if (r == null) {
1955 return false;
1956 }
1957 final boolean translucentChanged = r.changeWindowTranslucency(true);
1958 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001959 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 return translucentChanged;
1963 }
1964 } finally {
1965 Binder.restoreCallingIdentity(origId);
1966 }
1967 }
1968
1969 @Override
1970 public boolean convertToTranslucent(IBinder token, Bundle options) {
1971 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1972 final long origId = Binder.clearCallingIdentity();
1973 try {
1974 synchronized (mGlobalLock) {
1975 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1976 if (r == null) {
1977 return false;
1978 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001979 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 int index = task.mActivities.lastIndexOf(r);
1981 if (index > 0) {
1982 ActivityRecord under = task.mActivities.get(index - 1);
1983 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1984 }
1985 final boolean translucentChanged = r.changeWindowTranslucency(false);
1986 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001987 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001989 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001990 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 return translucentChanged;
1992 }
1993 } finally {
1994 Binder.restoreCallingIdentity(origId);
1995 }
1996 }
1997
1998 @Override
1999 public void notifyActivityDrawn(IBinder token) {
2000 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2001 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002002 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002004 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 }
2007 }
2008
2009 @Override
2010 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2011 synchronized (mGlobalLock) {
2012 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2013 if (r == null) {
2014 return;
2015 }
2016 r.reportFullyDrawnLocked(restoredFromBundle);
2017 }
2018 }
2019
2020 @Override
2021 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2022 synchronized (mGlobalLock) {
2023 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2024 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2025 return stack.mDisplayId;
2026 }
2027 return DEFAULT_DISPLAY;
2028 }
2029 }
2030
2031 @Override
2032 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 long ident = Binder.clearCallingIdentity();
2035 try {
2036 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002037 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002039 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return null;
2042 }
2043 } finally {
2044 Binder.restoreCallingIdentity(ident);
2045 }
2046 }
2047
2048 @Override
2049 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002050 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2052 final long callingId = Binder.clearCallingIdentity();
2053 try {
2054 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002055 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 if (stack == null) {
2057 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2058 return;
2059 }
2060 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002061 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002062 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(callingId);
2067 }
2068 }
2069
2070 @Override
2071 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2074 final long callingId = Binder.clearCallingIdentity();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002078 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (task == null) {
2080 return;
2081 }
2082 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002083 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002084 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 }
2087 } finally {
2088 Binder.restoreCallingIdentity(callingId);
2089 }
2090 }
2091
2092 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002093 public void restartActivityProcessIfVisible(IBinder activityToken) {
2094 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2095 final long callingId = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (mGlobalLock) {
2098 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2099 if (r == null) {
2100 return;
2101 }
2102 r.restartProcessIfVisible();
2103 }
2104 } finally {
2105 Binder.restoreCallingIdentity(callingId);
2106 }
2107 }
2108
2109 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002111 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 synchronized (mGlobalLock) {
2113 final long ident = Binder.clearCallingIdentity();
2114 try {
2115 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2116 "remove-task");
2117 } finally {
2118 Binder.restoreCallingIdentity(ident);
2119 }
2120 }
2121 }
2122
2123 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002124 public void removeAllVisibleRecentTasks() {
2125 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2126 synchronized (mGlobalLock) {
2127 final long ident = Binder.clearCallingIdentity();
2128 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002129 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002130 } finally {
2131 Binder.restoreCallingIdentity(ident);
2132 }
2133 }
2134 }
2135
2136 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2138 synchronized (mGlobalLock) {
2139 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2140 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002141 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 }
2143 }
2144 return false;
2145 }
2146
2147 @Override
2148 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2149 Intent resultData) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002150 final ActivityRecord r;
2151 synchronized (mGlobalLock) {
2152 r = ActivityRecord.isInStackLocked(token);
2153 if (r == null) {
2154 return false;
2155 }
2156 }
2157
2158 // Carefully collect grants without holding lock
2159 final NeededUriGrants destGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
2160 Binder.getCallingUid(), destIntent, r.packageName, r.mUserId);
2161 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
2162 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163
2164 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002165 return r.getActivityStack().navigateUpToLocked(
2166 r, destIntent, destGrants, resultCode, resultData, resultGrants);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 }
2168 }
2169
2170 /**
2171 * Attempts to move a task backwards in z-order (the order of activities within the task is
2172 * unchanged).
2173 *
2174 * There are several possible results of this call:
2175 * - if the task is locked, then we will show the lock toast
2176 * - if there is a task behind the provided task, then that task is made visible and resumed as
2177 * this task is moved to the back
2178 * - otherwise, if there are no other tasks in the stack:
2179 * - if this task is in the pinned stack, then we remove the stack completely, which will
2180 * have the effect of moving the task to the top or bottom of the fullscreen stack
2181 * (depending on whether it is visible)
2182 * - otherwise, we simply return home and hide this task
2183 *
2184 * @param token A reference to the activity we wish to move
2185 * @param nonRoot If false then this only works if the activity is the root
2186 * of a task; if true it will work for any activity in a task.
2187 * @return Returns true if the move completed, false if not.
2188 */
2189 @Override
2190 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 synchronized (mGlobalLock) {
2193 final long origId = Binder.clearCallingIdentity();
2194 try {
2195 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 if (task != null) {
2198 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2199 }
2200 } finally {
2201 Binder.restoreCallingIdentity(origId);
2202 }
2203 }
2204 return false;
2205 }
2206
2207 @Override
2208 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002209 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 long ident = Binder.clearCallingIdentity();
2211 Rect rect = new Rect();
2212 try {
2213 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002214 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002215 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2216 if (task == null) {
2217 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2218 return rect;
2219 }
2220 if (task.getStack() != null) {
2221 // Return the bounds from window manager since it will be adjusted for various
2222 // things like the presense of a docked stack for tasks that aren't resizeable.
2223 task.getWindowContainerBounds(rect);
2224 } else {
2225 // Task isn't in window manager yet since it isn't associated with a stack.
2226 // Return the persist value from activity manager
2227 if (!task.matchParentBounds()) {
2228 rect.set(task.getBounds());
2229 } else if (task.mLastNonFullscreenBounds != null) {
2230 rect.set(task.mLastNonFullscreenBounds);
2231 }
2232 }
2233 }
2234 } finally {
2235 Binder.restoreCallingIdentity(ident);
2236 }
2237 return rect;
2238 }
2239
2240 @Override
2241 public ActivityManager.TaskDescription getTaskDescription(int id) {
2242 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002245 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2247 if (tr != null) {
2248 return tr.lastTaskDescription;
2249 }
2250 }
2251 return null;
2252 }
2253
2254 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002255 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2256 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2257 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2258 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2259 return;
2260 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002261 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 synchronized (mGlobalLock) {
2263 final long ident = Binder.clearCallingIdentity();
2264 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002265 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002266 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 if (task == null) {
2268 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2269 return;
2270 }
2271
2272 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2273 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2274
2275 if (!task.isActivityTypeStandardOrUndefined()) {
2276 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2277 + " non-standard task " + taskId + " to windowing mode="
2278 + windowingMode);
2279 }
2280
2281 final ActivityStack stack = task.getStack();
2282 if (toTop) {
2283 stack.moveToFront("setTaskWindowingMode", task);
2284 }
2285 stack.setWindowingMode(windowingMode);
2286 } finally {
2287 Binder.restoreCallingIdentity(ident);
2288 }
2289 }
2290 }
2291
2292 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002293 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002294 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 ActivityRecord r = getCallingRecordLocked(token);
2296 return r != null ? r.info.packageName : null;
2297 }
2298 }
2299
2300 @Override
2301 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002302 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002303 ActivityRecord r = getCallingRecordLocked(token);
2304 return r != null ? r.intent.getComponent() : null;
2305 }
2306 }
2307
2308 private ActivityRecord getCallingRecordLocked(IBinder token) {
2309 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2310 if (r == null) {
2311 return null;
2312 }
2313 return r.resultTo;
2314 }
2315
2316 @Override
2317 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319
2320 synchronized (mGlobalLock) {
2321 final long origId = Binder.clearCallingIdentity();
2322 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002323 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002324 } finally {
2325 Binder.restoreCallingIdentity(origId);
2326 }
2327 }
2328 }
2329
Mark Renouf446251d2019-04-26 10:22:41 -04002330 @Override
2331 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2332 synchronized (mGlobalLock) {
2333 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2334 if (r == null) {
2335 return;
2336 }
2337 ActivityStack stack = r.getActivityStack();
2338 if (stack != null && stack.isSingleTaskInstance()) {
2339 // Single-task stacks are used for activities which are presented in floating
2340 // windows above full screen activities. Instead of directly finishing the
2341 // task, a task change listener is used to notify SystemUI so the action can be
2342 // handled specially.
2343 final TaskRecord task = r.getTaskRecord();
2344 mTaskChangeNotificationController
2345 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2346 } else {
2347 try {
2348 callback.requestFinish();
2349 } catch (RemoteException e) {
2350 Slog.e(TAG, "Failed to invoke request finish callback", e);
2351 }
2352 }
2353 }
2354 }
2355
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 /**
2357 * TODO: Add mController hook
2358 */
2359 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2361 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002362 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363
2364 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2365 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2367 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 }
2369 }
2370
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2372 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 boolean fromRecents) {
2374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 final int callingPid = Binder.getCallingPid();
2376 final int callingUid = Binder.getCallingUid();
2377 if (!isSameApp(callingUid, callingPackage)) {
2378 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2379 + Binder.getCallingPid() + " as package " + callingPackage;
2380 Slog.w(TAG, msg);
2381 throw new SecurityException(msg);
2382 }
2383 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 SafeActivityOptions.abort(options);
2385 return;
2386 }
2387 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 WindowProcessController callerApp = null;
2389 if (appThread != null) {
2390 callerApp = getProcessController(appThread);
2391 }
2392 final ActivityStarter starter = getActivityStartController().obtainStarter(
2393 null /* intent */, "moveTaskToFront");
2394 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2395 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002396 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002397 return;
2398 }
2399 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002401 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 if (task == null) {
2403 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002404 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 return;
2406 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002407 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002408 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002409 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 return;
2411 }
2412 ActivityOptions realOptions = options != null
2413 ? options.getOptions(mStackSupervisor)
2414 : null;
2415 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2416 false /* forceNonResizable */);
2417
2418 final ActivityRecord topActivity = task.getTopActivity();
2419 if (topActivity != null) {
2420
2421 // We are reshowing a task, use a starting window to hide the initial draw delay
2422 // so the transition can start earlier.
2423 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2424 true /* taskSwitch */, fromRecents);
2425 }
2426 } finally {
2427 Binder.restoreCallingIdentity(origId);
2428 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002429 }
2430
Ricky Waiaca8a772019-04-04 16:01:06 +01002431 /**
2432 * Return true if callingUid is system, or packageName belongs to that callingUid.
2433 */
2434 boolean isSameApp(int callingUid, @Nullable String packageName) {
2435 try {
2436 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2437 if (packageName == null) {
2438 return false;
2439 }
2440 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2441 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2442 UserHandle.getUserId(callingUid));
2443 return UserHandle.isSameApp(callingUid, uid);
2444 }
2445 } catch (RemoteException e) {
2446 // Should not happen
2447 }
2448 return true;
2449 }
2450
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002451 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2452 int callingPid, int callingUid, String name) {
2453 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2454 return true;
2455 }
2456
2457 if (getRecentTasks().isCallerRecents(sourceUid)) {
2458 return true;
2459 }
2460
2461 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2462 if (perm == PackageManager.PERMISSION_GRANTED) {
2463 return true;
2464 }
2465 if (checkAllowAppSwitchUid(sourceUid)) {
2466 return true;
2467 }
2468
2469 // If the actual IPC caller is different from the logical source, then
2470 // also see if they are allowed to control app switches.
2471 if (callingUid != -1 && callingUid != sourceUid) {
2472 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2473 if (perm == PackageManager.PERMISSION_GRANTED) {
2474 return true;
2475 }
2476 if (checkAllowAppSwitchUid(callingUid)) {
2477 return true;
2478 }
2479 }
2480
2481 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2482 return false;
2483 }
2484
2485 private boolean checkAllowAppSwitchUid(int uid) {
2486 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2487 if (types != null) {
2488 for (int i = types.size() - 1; i >= 0; i--) {
2489 if (types.valueAt(i).intValue() == uid) {
2490 return true;
2491 }
2492 }
2493 }
2494 return false;
2495 }
2496
2497 @Override
2498 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2499 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2500 "setActivityController()");
2501 synchronized (mGlobalLock) {
2502 mController = controller;
2503 mControllerIsAMonkey = imAMonkey;
2504 Watchdog.getInstance().setActivityController(controller);
2505 }
2506 }
2507
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002508 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002509 synchronized (mGlobalLock) {
2510 return mController != null && mControllerIsAMonkey;
2511 }
2512 }
2513
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002514 @Override
2515 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2516 synchronized (mGlobalLock) {
2517 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2518 }
2519 }
2520
2521 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2523 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2524 }
2525
2526 @Override
2527 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2528 @WindowConfiguration.ActivityType int ignoreActivityType,
2529 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2530 final int callingUid = Binder.getCallingUid();
2531 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2532
2533 synchronized (mGlobalLock) {
2534 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2535
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002536 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002537 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002538 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 ignoreWindowingMode, callingUid, allowed);
2540 }
2541
2542 return list;
2543 }
2544
2545 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2547 synchronized (mGlobalLock) {
2548 final long origId = Binder.clearCallingIdentity();
2549 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2550 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002551 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002552 }
2553 Binder.restoreCallingIdentity(origId);
2554 }
2555 }
2556
2557 @Override
2558 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002559 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560 ActivityStack stack = ActivityRecord.getStackLocked(token);
2561 if (stack != null) {
2562 return stack.willActivityBeVisibleLocked(token);
2563 }
2564 return false;
2565 }
2566 }
2567
2568 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002569 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 synchronized (mGlobalLock) {
2572 final long ident = Binder.clearCallingIdentity();
2573 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002574 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002575 if (task == null) {
2576 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2577 return;
2578 }
2579
2580 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2581 + " to stackId=" + stackId + " toTop=" + toTop);
2582
Wale Ogunwaled32da472018-11-16 07:19:28 -08002583 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002584 if (stack == null) {
2585 throw new IllegalStateException(
2586 "moveTaskToStack: No stack for stackId=" + stackId);
2587 }
2588 if (!stack.isActivityTypeStandardOrUndefined()) {
2589 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2590 + taskId + " to stack " + stackId);
2591 }
2592 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2595 }
2596 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2597 "moveTaskToStack");
2598 } finally {
2599 Binder.restoreCallingIdentity(ident);
2600 }
2601 }
2602 }
2603
2604 @Override
2605 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2606 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002607 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608
2609 final long ident = Binder.clearCallingIdentity();
2610 try {
2611 synchronized (mGlobalLock) {
2612 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002613 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002614 if (stack == null) {
2615 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2616 return;
2617 }
2618 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2619 throw new IllegalArgumentException("Stack: " + stackId
2620 + " doesn't support animated resize.");
2621 }
2622 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2623 animationDuration, false /* fromFullscreen */);
2624 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002625 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626 if (stack == null) {
2627 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2628 return;
2629 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002630 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002631 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2632 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2633 }
2634 }
2635 } finally {
2636 Binder.restoreCallingIdentity(ident);
2637 }
2638 }
2639
wilsonshih5c4cf522019-01-25 09:03:47 +08002640 @Override
2641 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2642 int animationDuration) {
2643 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2644
2645 final long ident = Binder.clearCallingIdentity();
2646 try {
2647 synchronized (mGlobalLock) {
2648 if (xOffset == 0 && yOffset == 0) {
2649 return;
2650 }
2651 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2652 if (stack == null) {
2653 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2654 return;
2655 }
2656 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2657 throw new IllegalArgumentException("Stack: " + stackId
2658 + " doesn't support animated resize.");
2659 }
2660 final Rect destBounds = new Rect();
2661 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002662 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002663 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2664 return;
2665 }
2666 destBounds.offset(xOffset, yOffset);
2667 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2668 animationDuration, false /* fromFullscreen */);
2669 }
2670 } finally {
2671 Binder.restoreCallingIdentity(ident);
2672 }
2673 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 /**
2675 * Moves the specified task to the primary-split-screen stack.
2676 *
2677 * @param taskId Id of task to move.
2678 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2679 * exist already. See
2680 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2681 * and
2682 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2683 * @param toTop If the task and stack should be moved to the top.
2684 * @param animate Whether we should play an animation for the moving the task.
2685 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2686 * stack. Pass {@code null} to use default bounds.
2687 * @param showRecents If the recents activity should be shown on the other side of the task
2688 * going into split-screen mode.
2689 */
2690 @Override
2691 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2692 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002693 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002694 "setTaskWindowingModeSplitScreenPrimary()");
2695 synchronized (mGlobalLock) {
2696 final long ident = Binder.clearCallingIdentity();
2697 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002698 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002699 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 if (task == null) {
2701 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2702 return false;
2703 }
2704 if (DEBUG_STACK) Slog.d(TAG_STACK,
2705 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2706 + " to createMode=" + createMode + " toTop=" + toTop);
2707 if (!task.isActivityTypeStandardOrUndefined()) {
2708 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2709 + " non-standard task " + taskId + " to split-screen windowing mode");
2710 }
2711
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002712 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 final int windowingMode = task.getWindowingMode();
2714 final ActivityStack stack = task.getStack();
2715 if (toTop) {
2716 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2717 }
2718 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002719 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2720 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 return windowingMode != task.getWindowingMode();
2722 } finally {
2723 Binder.restoreCallingIdentity(ident);
2724 }
2725 }
2726 }
2727
2728 /**
2729 * Removes stacks in the input windowing modes from the system if they are of activity type
2730 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2731 */
2732 @Override
2733 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002734 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002735 "removeStacksInWindowingModes()");
2736
2737 synchronized (mGlobalLock) {
2738 final long ident = Binder.clearCallingIdentity();
2739 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002740 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002741 } finally {
2742 Binder.restoreCallingIdentity(ident);
2743 }
2744 }
2745 }
2746
2747 @Override
2748 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002750 "removeStacksWithActivityTypes()");
2751
2752 synchronized (mGlobalLock) {
2753 final long ident = Binder.clearCallingIdentity();
2754 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002755 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002756 } finally {
2757 Binder.restoreCallingIdentity(ident);
2758 }
2759 }
2760 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761
2762 @Override
2763 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2764 int userId) {
2765 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002766 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2767 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002769 final boolean detailed = checkGetTasksPermission(
2770 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2771 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772 == PackageManager.PERMISSION_GRANTED;
2773
2774 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002775 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 callingUid);
2777 }
2778 }
2779
2780 @Override
2781 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002782 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 long ident = Binder.clearCallingIdentity();
2784 try {
2785 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002786 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 }
2788 } finally {
2789 Binder.restoreCallingIdentity(ident);
2790 }
2791 }
2792
2793 @Override
2794 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002795 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002796 long ident = Binder.clearCallingIdentity();
2797 try {
2798 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002799 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002800 }
2801 } finally {
2802 Binder.restoreCallingIdentity(ident);
2803 }
2804 }
2805
2806 @Override
2807 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002808 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 final long callingUid = Binder.getCallingUid();
2810 final long origId = Binder.clearCallingIdentity();
2811 try {
2812 synchronized (mGlobalLock) {
2813 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2816 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2817 }
2818 } finally {
2819 Binder.restoreCallingIdentity(origId);
2820 }
2821 }
2822
2823 @Override
2824 public void startLockTaskModeByToken(IBinder token) {
2825 synchronized (mGlobalLock) {
2826 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2827 if (r == null) {
2828 return;
2829 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002830 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002831 }
2832 }
2833
2834 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002835 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002836 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 // This makes inner call to look as if it was initiated by system.
2838 long ident = Binder.clearCallingIdentity();
2839 try {
2840 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002841 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002842 MATCH_TASK_IN_STACKS_ONLY);
2843 if (task == null) {
2844 return;
2845 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846
2847 // When starting lock task mode the stack must be in front and focused
2848 task.getStack().moveToFront("startSystemLockTaskMode");
2849 startLockTaskModeLocked(task, true /* isSystemCaller */);
2850 }
2851 } finally {
2852 Binder.restoreCallingIdentity(ident);
2853 }
2854 }
2855
2856 @Override
2857 public void stopLockTaskModeByToken(IBinder token) {
2858 synchronized (mGlobalLock) {
2859 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2860 if (r == null) {
2861 return;
2862 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002863 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 }
2865 }
2866
2867 /**
2868 * This API should be called by SystemUI only when user perform certain action to dismiss
2869 * lock task mode. We should only dismiss pinned lock task mode in this case.
2870 */
2871 @Override
2872 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002873 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2875 }
2876
2877 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2878 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2879 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2880 return;
2881 }
2882
Wale Ogunwaled32da472018-11-16 07:19:28 -08002883 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 if (stack == null || task != stack.topTask()) {
2885 throw new IllegalArgumentException("Invalid task, not in foreground");
2886 }
2887
2888 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2889 // system or a specific app.
2890 // * System-initiated requests will only start the pinned mode (screen pinning)
2891 // * App-initiated requests
2892 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2893 // - will start the pinned mode, otherwise
2894 final int callingUid = Binder.getCallingUid();
2895 long ident = Binder.clearCallingIdentity();
2896 try {
2897 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002898 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002900 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 } finally {
2902 Binder.restoreCallingIdentity(ident);
2903 }
2904 }
2905
2906 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2907 final int callingUid = Binder.getCallingUid();
2908 long ident = Binder.clearCallingIdentity();
2909 try {
2910 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002911 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 }
2913 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2914 // task and jumping straight into a call in the case of emergency call back.
2915 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2916 if (tm != null) {
2917 tm.showInCallScreen(false);
2918 }
2919 } finally {
2920 Binder.restoreCallingIdentity(ident);
2921 }
2922 }
2923
2924 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002925 public void updateLockTaskPackages(int userId, String[] packages) {
2926 final int callingUid = Binder.getCallingUid();
2927 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2928 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2929 "updateLockTaskPackages()");
2930 }
2931 synchronized (this) {
2932 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2933 + Arrays.toString(packages));
2934 getLockTaskController().updateLockTaskPackages(userId, packages);
2935 }
2936 }
2937
2938 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 public boolean isInLockTaskMode() {
2940 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2941 }
2942
2943 @Override
2944 public int getLockTaskModeState() {
2945 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002946 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 }
2948 }
2949
2950 @Override
2951 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2952 synchronized (mGlobalLock) {
2953 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2954 if (r != null) {
2955 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002956 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002958 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002959 }
2960 }
2961 }
2962
2963 @Override
2964 public Bundle getActivityOptions(IBinder token) {
2965 final long origId = Binder.clearCallingIdentity();
2966 try {
2967 synchronized (mGlobalLock) {
2968 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2969 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002970 final ActivityOptions activityOptions = r.takeOptionsLocked(
2971 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 return activityOptions == null ? null : activityOptions.toBundle();
2973 }
2974 return null;
2975 }
2976 } finally {
2977 Binder.restoreCallingIdentity(origId);
2978 }
2979 }
2980
2981 @Override
2982 public List<IBinder> getAppTasks(String callingPackage) {
2983 int callingUid = Binder.getCallingUid();
2984 long ident = Binder.clearCallingIdentity();
2985 try {
2986 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002987 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 }
2989 } finally {
2990 Binder.restoreCallingIdentity(ident);
2991 }
2992 }
2993
2994 @Override
2995 public void finishVoiceTask(IVoiceInteractionSession session) {
2996 synchronized (mGlobalLock) {
2997 final long origId = Binder.clearCallingIdentity();
2998 try {
2999 // TODO: VI Consider treating local voice interactions and voice tasks
3000 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003001 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003002 } finally {
3003 Binder.restoreCallingIdentity(origId);
3004 }
3005 }
3006
3007 }
3008
3009 @Override
3010 public boolean isTopOfTask(IBinder token) {
3011 synchronized (mGlobalLock) {
3012 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003013 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 }
3015 }
3016
3017 @Override
3018 public void notifyLaunchTaskBehindComplete(IBinder token) {
3019 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3020 }
3021
3022 @Override
3023 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003024 mH.post(() -> {
3025 synchronized (mGlobalLock) {
3026 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003027 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003028 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003029 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003030 } catch (RemoteException e) {
3031 }
3032 }
3033 }
3034
3035 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 }
3037
3038 /** Called from an app when assist data is ready. */
3039 @Override
3040 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3041 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003042 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 synchronized (pae) {
3044 pae.result = extras;
3045 pae.structure = structure;
3046 pae.content = content;
3047 if (referrer != null) {
3048 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3049 }
3050 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003051 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003052 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3053 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 structure.setHomeActivity(pae.isHome);
3055 }
3056 pae.haveResult = true;
3057 pae.notifyAll();
3058 if (pae.intent == null && pae.receiver == null) {
3059 // Caller is just waiting for the result.
3060 return;
3061 }
3062 }
3063 // We are now ready to launch the assist activity.
3064 IAssistDataReceiver sendReceiver = null;
3065 Bundle sendBundle = null;
3066 synchronized (mGlobalLock) {
3067 buildAssistBundleLocked(pae, extras);
3068 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003069 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 if (!exists) {
3071 // Timed out.
3072 return;
3073 }
3074
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003075 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 // Caller wants result sent back to them.
3077 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003078 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3079 pae.activity.getTaskRecord().taskId);
3080 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3081 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003082 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3083 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3084 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3085 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3086 }
3087 }
3088 if (sendReceiver != null) {
3089 try {
3090 sendReceiver.onHandleAssistData(sendBundle);
3091 } catch (RemoteException e) {
3092 }
3093 return;
3094 }
3095
3096 final long ident = Binder.clearCallingIdentity();
3097 try {
3098 if (TextUtils.equals(pae.intent.getAction(),
3099 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3100 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003101
3102 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 } else {
3104 pae.intent.replaceExtras(pae.extras);
3105 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3106 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3107 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003108 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109
3110 try {
3111 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3112 } catch (ActivityNotFoundException e) {
3113 Slog.w(TAG, "No activity to handle assist action.", e);
3114 }
3115 }
3116 } finally {
3117 Binder.restoreCallingIdentity(ident);
3118 }
3119 }
3120
Marvin Ramin830d4e32019-03-12 13:16:58 +01003121 /**
3122 * Workaround for historical API which starts the Assist service with a non-foreground
3123 * {@code startService()} call.
3124 */
3125 private void startVoiceInteractionServiceAsUser(
3126 Intent intent, int userHandle, String reason) {
3127 // Resolve the intent to find out which package we need to whitelist.
3128 ResolveInfo resolveInfo =
3129 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3130 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3131 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3132 return;
3133 }
3134 intent.setPackage(resolveInfo.serviceInfo.packageName);
3135
3136 // Whitelist background services temporarily.
3137 LocalServices.getService(DeviceIdleController.LocalService.class)
3138 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3139 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3140
3141 // Finally, try to start the service.
3142 try {
3143 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3144 } catch (RuntimeException e) {
3145 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3146 }
3147 }
3148
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 @Override
3150 public int addAppTask(IBinder activityToken, Intent intent,
3151 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3152 final int callingUid = Binder.getCallingUid();
3153 final long callingIdent = Binder.clearCallingIdentity();
3154
3155 try {
3156 synchronized (mGlobalLock) {
3157 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3158 if (r == null) {
3159 throw new IllegalArgumentException("Activity does not exist; token="
3160 + activityToken);
3161 }
3162 ComponentName comp = intent.getComponent();
3163 if (comp == null) {
3164 throw new IllegalArgumentException("Intent " + intent
3165 + " must specify explicit component");
3166 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003167 if (thumbnail.getWidth() != mThumbnailWidth
3168 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 throw new IllegalArgumentException("Bad thumbnail size: got "
3170 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003171 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003172 }
3173 if (intent.getSelector() != null) {
3174 intent.setSelector(null);
3175 }
3176 if (intent.getSourceBounds() != null) {
3177 intent.setSourceBounds(null);
3178 }
3179 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3180 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3181 // The caller has added this as an auto-remove task... that makes no
3182 // sense, so turn off auto-remove.
3183 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3184 }
3185 }
3186 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3187 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3188 if (ainfo.applicationInfo.uid != callingUid) {
3189 throw new SecurityException(
3190 "Can't add task for another application: target uid="
3191 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3192 }
3193
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003194 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003196 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003198 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003199 // The app has too many tasks already and we can't add any more
3200 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3201 return INVALID_TASK_ID;
3202 }
3203 task.lastTaskDescription.copyFrom(description);
3204
3205 // TODO: Send the thumbnail to WM to store it.
3206
3207 return task.taskId;
3208 }
3209 } finally {
3210 Binder.restoreCallingIdentity(callingIdent);
3211 }
3212 }
3213
3214 @Override
3215 public Point getAppTaskThumbnailSize() {
3216 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003218 }
3219 }
3220
3221 @Override
3222 public void setTaskResizeable(int taskId, int resizeableMode) {
3223 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003224 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3226 if (task == null) {
3227 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3228 return;
3229 }
3230 task.setResizeMode(resizeableMode);
3231 }
3232 }
3233
3234 @Override
3235 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003236 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003237 long ident = Binder.clearCallingIdentity();
3238 try {
3239 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003240 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003241 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 if (task == null) {
3243 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3244 return;
3245 }
3246 // Place the task in the right stack if it isn't there already based on
3247 // the requested bounds.
3248 // The stack transition logic is:
3249 // - a null bounds on a freeform task moves that task to fullscreen
3250 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3251 // that task to freeform
3252 // - otherwise the task is not moved
3253 ActivityStack stack = task.getStack();
3254 if (!task.getWindowConfiguration().canResizeTask()) {
3255 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3256 }
3257 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3258 stack = stack.getDisplay().getOrCreateStack(
3259 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3260 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3261 stack = stack.getDisplay().getOrCreateStack(
3262 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3263 }
3264
3265 // Reparent the task to the right stack if necessary
3266 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3267 if (stack != task.getStack()) {
3268 // Defer resume until the task is resized below
3269 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3270 DEFER_RESUME, "resizeTask");
3271 preserveWindow = false;
3272 }
3273
3274 // After reparenting (which only resizes the task to the stack bounds), resize the
3275 // task to the actual bounds provided
3276 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3277 }
3278 } finally {
3279 Binder.restoreCallingIdentity(ident);
3280 }
3281 }
3282
3283 @Override
3284 public boolean releaseActivityInstance(IBinder token) {
3285 synchronized (mGlobalLock) {
3286 final long origId = Binder.clearCallingIdentity();
3287 try {
3288 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3289 if (r == null) {
3290 return false;
3291 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003292 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 } finally {
3294 Binder.restoreCallingIdentity(origId);
3295 }
3296 }
3297 }
3298
3299 @Override
3300 public void releaseSomeActivities(IApplicationThread appInt) {
3301 synchronized (mGlobalLock) {
3302 final long origId = Binder.clearCallingIdentity();
3303 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003304 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003305 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 } finally {
3307 Binder.restoreCallingIdentity(origId);
3308 }
3309 }
3310 }
3311
3312 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003313 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 != PackageManager.PERMISSION_GRANTED) {
3316 throw new SecurityException("Requires permission "
3317 + android.Manifest.permission.DEVICE_POWER);
3318 }
3319
3320 synchronized (mGlobalLock) {
3321 long ident = Binder.clearCallingIdentity();
3322 if (mKeyguardShown != keyguardShowing) {
3323 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003324 final Message msg = PooledLambda.obtainMessage(
3325 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3326 keyguardShowing);
3327 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 }
3329 try {
wilsonshih177261f2019-02-22 12:02:18 +08003330 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 } finally {
3332 Binder.restoreCallingIdentity(ident);
3333 }
3334 }
3335
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003336 mH.post(() -> {
3337 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3338 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3339 }
3340 });
3341 }
3342
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003343 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003344 mH.post(() -> {
3345 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3346 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3347 }
3348 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 }
3350
3351 @Override
3352 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3354 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355
3356 final File passedIconFile = new File(filePath);
3357 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3358 passedIconFile.getName());
3359 if (!legitIconFile.getPath().equals(filePath)
3360 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3361 throw new IllegalArgumentException("Bad file path: " + filePath
3362 + " passed for userId " + userId);
3363 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003364 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 }
3366
3367 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003368 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3370 final ActivityOptions activityOptions = safeOptions != null
3371 ? safeOptions.getOptions(mStackSupervisor)
3372 : null;
3373 if (activityOptions == null
3374 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3375 || activityOptions.getCustomInPlaceResId() == 0) {
3376 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3377 "with valid animation");
3378 }
lumark588a3e82018-07-20 18:53:54 +08003379 // Get top display of front most application.
3380 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3381 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003382 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3383 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3384 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003385 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003386 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003387 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 }
3389
3390 @Override
3391 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003392 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 synchronized (mGlobalLock) {
3394 final long ident = Binder.clearCallingIdentity();
3395 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003396 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 if (stack == null) {
3398 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3399 return;
3400 }
3401 if (!stack.isActivityTypeStandardOrUndefined()) {
3402 throw new IllegalArgumentException(
3403 "Removing non-standard stack is not allowed.");
3404 }
3405 mStackSupervisor.removeStack(stack);
3406 } finally {
3407 Binder.restoreCallingIdentity(ident);
3408 }
3409 }
3410 }
3411
3412 @Override
3413 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003414 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415
3416 synchronized (mGlobalLock) {
3417 final long ident = Binder.clearCallingIdentity();
3418 try {
3419 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3420 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003421 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 } finally {
3423 Binder.restoreCallingIdentity(ident);
3424 }
3425 }
3426 }
3427
3428 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003429 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 synchronized (mGlobalLock) {
3431 long ident = Binder.clearCallingIdentity();
3432 try {
3433 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3434 if (r == null) {
3435 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003436 "toggleFreeformWindowingMode: No activity record matching token="
3437 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 }
3439
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003440 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003441 if (stack == null) {
3442 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3443 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003444 }
3445
Yunfan Chend967af82019-01-17 18:30:18 +09003446 if (!stack.inFreeformWindowingMode()
3447 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3448 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3449 + "toggle between fullscreen and freeform.");
3450 }
3451
3452 if (stack.inFreeformWindowingMode()) {
3453 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003454 } else if (stack.getParent().inFreeformWindowingMode()) {
3455 // If the window is on a freeform display, set it to undefined. It will be
3456 // resolved to freeform and it can adjust windowing mode when the display mode
3457 // changes in runtime.
3458 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003459 } else {
3460 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3461 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 } finally {
3463 Binder.restoreCallingIdentity(ident);
3464 }
3465 }
3466 }
3467
3468 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3469 @Override
3470 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003471 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003473 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474 }
3475
3476 /** Unregister a task stack listener so that it stops receiving callbacks. */
3477 @Override
3478 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003479 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003480 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003481 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 }
3483
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 @Override
3485 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3486 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3487 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3488 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3489 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3490 }
3491
3492 @Override
3493 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3494 IBinder activityToken, int flags) {
3495 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3496 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3497 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3498 }
3499
3500 @Override
3501 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3502 Bundle args) {
3503 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3504 true /* focused */, true /* newSessionId */, userHandle, args,
3505 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3506 }
3507
3508 @Override
3509 public Bundle getAssistContextExtras(int requestType) {
3510 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3511 null, null, true /* focused */, true /* newSessionId */,
3512 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3513 if (pae == null) {
3514 return null;
3515 }
3516 synchronized (pae) {
3517 while (!pae.haveResult) {
3518 try {
3519 pae.wait();
3520 } catch (InterruptedException e) {
3521 }
3522 }
3523 }
3524 synchronized (mGlobalLock) {
3525 buildAssistBundleLocked(pae, pae.result);
3526 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 }
3529 return pae.extras;
3530 }
3531
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003532 /**
3533 * Binder IPC calls go through the public entry point.
3534 * This can be called with or without the global lock held.
3535 */
3536 private static int checkCallingPermission(String permission) {
3537 return checkPermission(
3538 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3539 }
3540
3541 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003542 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003543 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3544 mAmInternal.enforceCallingPermission(permission, func);
3545 }
3546 }
3547
3548 @VisibleForTesting
3549 int checkGetTasksPermission(String permission, int pid, int uid) {
3550 return checkPermission(permission, pid, uid);
3551 }
3552
3553 static int checkPermission(String permission, int pid, int uid) {
3554 if (permission == null) {
3555 return PackageManager.PERMISSION_DENIED;
3556 }
3557 return checkComponentPermission(permission, pid, uid, -1, true);
3558 }
3559
Wale Ogunwale214f3482018-10-04 11:00:47 -07003560 public static int checkComponentPermission(String permission, int pid, int uid,
3561 int owningUid, boolean exported) {
3562 return ActivityManagerService.checkComponentPermission(
3563 permission, pid, uid, owningUid, exported);
3564 }
3565
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003566 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3567 if (getRecentTasks().isCallerRecents(callingUid)) {
3568 // Always allow the recents component to get tasks
3569 return true;
3570 }
3571
3572 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3573 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3574 if (!allowed) {
3575 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3576 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3577 // Temporary compatibility: some existing apps on the system image may
3578 // still be requesting the old permission and not switched to the new
3579 // one; if so, we'll still allow them full access. This means we need
3580 // to see if they are holding the old permission and are a system app.
3581 try {
3582 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3583 allowed = true;
3584 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3585 + " is using old GET_TASKS but privileged; allowing");
3586 }
3587 } catch (RemoteException e) {
3588 }
3589 }
3590 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3591 + " does not hold REAL_GET_TASKS; limiting output");
3592 }
3593 return allowed;
3594 }
3595
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003596 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3597 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3598 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3599 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003600 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 "enqueueAssistContext()");
3602
3603 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003604 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 if (activity == null) {
3606 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3607 return null;
3608 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003609 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3611 return null;
3612 }
3613 if (focused) {
3614 if (activityToken != null) {
3615 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3616 if (activity != caller) {
3617 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3618 + " is not current top " + activity);
3619 return null;
3620 }
3621 }
3622 } else {
3623 activity = ActivityRecord.forTokenLocked(activityToken);
3624 if (activity == null) {
3625 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3626 + " couldn't be found");
3627 return null;
3628 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003629 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003630 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3631 return null;
3632 }
3633 }
3634
3635 PendingAssistExtras pae;
3636 Bundle extras = new Bundle();
3637 if (args != null) {
3638 extras.putAll(args);
3639 }
3640 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003641 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642
3643 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3644 userHandle);
3645 pae.isHome = activity.isActivityTypeHome();
3646
3647 // Increment the sessionId if necessary
3648 if (newSessionId) {
3649 mViSessionId++;
3650 }
3651 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003652 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3653 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003655 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 } catch (RemoteException e) {
3657 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3658 return null;
3659 }
3660 return pae;
3661 }
3662 }
3663
3664 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3665 if (result != null) {
3666 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3667 }
3668 if (pae.hint != null) {
3669 pae.extras.putBoolean(pae.hint, true);
3670 }
3671 }
3672
3673 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3674 IAssistDataReceiver receiver;
3675 synchronized (mGlobalLock) {
3676 mPendingAssistExtras.remove(pae);
3677 receiver = pae.receiver;
3678 }
3679 if (receiver != null) {
3680 // Caller wants result sent back to them.
3681 Bundle sendBundle = new Bundle();
3682 // At least return the receiver extras
3683 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3684 try {
3685 pae.receiver.onHandleAssistData(sendBundle);
3686 } catch (RemoteException e) {
3687 }
3688 }
3689 }
3690
3691 public class PendingAssistExtras extends Binder implements Runnable {
3692 public final ActivityRecord activity;
3693 public boolean isHome;
3694 public final Bundle extras;
3695 public final Intent intent;
3696 public final String hint;
3697 public final IAssistDataReceiver receiver;
3698 public final int userHandle;
3699 public boolean haveResult = false;
3700 public Bundle result = null;
3701 public AssistStructure structure = null;
3702 public AssistContent content = null;
3703 public Bundle receiverExtras;
3704
3705 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3706 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3707 int _userHandle) {
3708 activity = _activity;
3709 extras = _extras;
3710 intent = _intent;
3711 hint = _hint;
3712 receiver = _receiver;
3713 receiverExtras = _receiverExtras;
3714 userHandle = _userHandle;
3715 }
3716
3717 @Override
3718 public void run() {
3719 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3720 synchronized (this) {
3721 haveResult = true;
3722 notifyAll();
3723 }
3724 pendingAssistExtrasTimedOut(this);
3725 }
3726 }
3727
3728 @Override
3729 public boolean isAssistDataAllowedOnCurrentActivity() {
3730 int userId;
3731 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003732 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003733 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3734 return false;
3735 }
3736
3737 final ActivityRecord activity = focusedStack.getTopActivity();
3738 if (activity == null) {
3739 return false;
3740 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003741 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 }
3743 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3744 }
3745
3746 @Override
3747 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3748 long ident = Binder.clearCallingIdentity();
3749 try {
3750 synchronized (mGlobalLock) {
3751 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003752 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 if (top != caller) {
3754 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3755 + " is not current top " + top);
3756 return false;
3757 }
3758 if (!top.nowVisible) {
3759 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3760 + " is not visible");
3761 return false;
3762 }
3763 }
3764 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3765 token);
3766 } finally {
3767 Binder.restoreCallingIdentity(ident);
3768 }
3769 }
3770
3771 @Override
3772 public boolean isRootVoiceInteraction(IBinder token) {
3773 synchronized (mGlobalLock) {
3774 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3775 if (r == null) {
3776 return false;
3777 }
3778 return r.rootVoiceInteraction;
3779 }
3780 }
3781
Wale Ogunwalef6733932018-06-27 05:14:34 -07003782 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3783 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3784 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3785 if (activityToCallback == null) return;
3786 activityToCallback.setVoiceSessionLocked(voiceSession);
3787
3788 // Inform the activity
3789 try {
3790 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3791 voiceInteractor);
3792 long token = Binder.clearCallingIdentity();
3793 try {
3794 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3795 } finally {
3796 Binder.restoreCallingIdentity(token);
3797 }
3798 // TODO: VI Should we cache the activity so that it's easier to find later
3799 // rather than scan through all the stacks and activities?
3800 } catch (RemoteException re) {
3801 activityToCallback.clearVoiceSessionLocked();
3802 // TODO: VI Should this terminate the voice session?
3803 }
3804 }
3805
3806 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3807 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3808 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3809 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3810 boolean wasRunningVoice = mRunningVoice != null;
3811 mRunningVoice = session;
3812 if (!wasRunningVoice) {
3813 mVoiceWakeLock.acquire();
3814 updateSleepIfNeededLocked();
3815 }
3816 }
3817 }
3818
3819 void finishRunningVoiceLocked() {
3820 if (mRunningVoice != null) {
3821 mRunningVoice = null;
3822 mVoiceWakeLock.release();
3823 updateSleepIfNeededLocked();
3824 }
3825 }
3826
3827 @Override
3828 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3829 synchronized (mGlobalLock) {
3830 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3831 if (keepAwake) {
3832 mVoiceWakeLock.acquire();
3833 } else {
3834 mVoiceWakeLock.release();
3835 }
3836 }
3837 }
3838 }
3839
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 @Override
3841 public ComponentName getActivityClassForToken(IBinder token) {
3842 synchronized (mGlobalLock) {
3843 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3844 if (r == null) {
3845 return null;
3846 }
3847 return r.intent.getComponent();
3848 }
3849 }
3850
3851 @Override
3852 public String getPackageForToken(IBinder token) {
3853 synchronized (mGlobalLock) {
3854 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3855 if (r == null) {
3856 return null;
3857 }
3858 return r.packageName;
3859 }
3860 }
3861
3862 @Override
3863 public void showLockTaskEscapeMessage(IBinder token) {
3864 synchronized (mGlobalLock) {
3865 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3866 if (r == null) {
3867 return;
3868 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003869 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 }
3871 }
3872
3873 @Override
3874 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003875 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 final long token = Binder.clearCallingIdentity();
3877 try {
3878 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003879 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 }
3881 } finally {
3882 Binder.restoreCallingIdentity(token);
3883 }
3884 }
3885
3886 /**
3887 * Try to place task to provided position. The final position might be different depending on
3888 * current user and stacks state. The task will be moved to target stack if it's currently in
3889 * different stack.
3890 */
3891 @Override
3892 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003893 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894 synchronized (mGlobalLock) {
3895 long ident = Binder.clearCallingIdentity();
3896 try {
3897 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3898 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003899 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900 if (task == null) {
3901 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3902 + taskId);
3903 }
3904
Wale Ogunwaled32da472018-11-16 07:19:28 -08003905 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003906
3907 if (stack == null) {
3908 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3909 + stackId);
3910 }
3911 if (!stack.isActivityTypeStandardOrUndefined()) {
3912 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3913 + " the position of task " + taskId + " in/to non-standard stack");
3914 }
3915
3916 // TODO: Have the callers of this API call a separate reparent method if that is
3917 // what they intended to do vs. having this method also do reparenting.
3918 if (task.getStack() == stack) {
3919 // Change position in current stack.
3920 stack.positionChildAt(task, position);
3921 } else {
3922 // Reparent to new stack.
3923 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3924 !DEFER_RESUME, "positionTaskInStack");
3925 }
3926 } finally {
3927 Binder.restoreCallingIdentity(ident);
3928 }
3929 }
3930 }
3931
3932 @Override
3933 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3934 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3935 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3936 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3937 synchronized (mGlobalLock) {
3938 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3939 if (record == null) {
3940 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3941 + "found for: " + token);
3942 }
3943 record.setSizeConfigurations(horizontalSizeConfiguration,
3944 verticalSizeConfigurations, smallestSizeConfigurations);
3945 }
3946 }
3947
3948 /**
3949 * Dismisses split-screen multi-window mode.
3950 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3951 */
3952 @Override
3953 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003954 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3956 final long ident = Binder.clearCallingIdentity();
3957 try {
3958 synchronized (mGlobalLock) {
3959 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003960 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 if (stack == null) {
3962 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3963 return;
3964 }
3965
3966 if (toTop) {
3967 // Caller wants the current split-screen primary stack to be the top stack after
3968 // it goes fullscreen, so move it to the front.
3969 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003970 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 // In this case the current split-screen primary stack shouldn't be the top
3972 // stack after it goes fullscreen, but it current has focus, so we move the
3973 // focus to the top-most split-screen secondary stack next to it.
3974 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3975 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3976 if (otherStack != null) {
3977 otherStack.moveToFront("dismissSplitScreenMode_other");
3978 }
3979 }
3980
Evan Rosky10475742018-09-05 19:02:48 -07003981 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982 }
3983 } finally {
3984 Binder.restoreCallingIdentity(ident);
3985 }
3986 }
3987
3988 /**
3989 * Dismisses Pip
3990 * @param animate True if the dismissal should be animated.
3991 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3992 * default animation duration should be used.
3993 */
3994 @Override
3995 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003996 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 final long ident = Binder.clearCallingIdentity();
3998 try {
3999 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004000 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004001 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 if (stack == null) {
4003 Slog.w(TAG, "dismissPip: pinned stack not found.");
4004 return;
4005 }
4006 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4007 throw new IllegalArgumentException("Stack: " + stack
4008 + " doesn't support animated resize.");
4009 }
4010 if (animate) {
4011 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4012 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4013 } else {
4014 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4015 }
4016 }
4017 } finally {
4018 Binder.restoreCallingIdentity(ident);
4019 }
4020 }
4021
4022 @Override
4023 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 synchronized (mGlobalLock) {
4026 mSuppressResizeConfigChanges = suppress;
4027 }
4028 }
4029
4030 /**
4031 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4032 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4033 * activity and clearing the task at the same time.
4034 */
4035 @Override
4036 // TODO: API should just be about changing windowing modes...
4037 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004038 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004039 "moveTasksToFullscreenStack()");
4040 synchronized (mGlobalLock) {
4041 final long origId = Binder.clearCallingIdentity();
4042 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004043 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 if (stack != null){
4045 if (!stack.isActivityTypeStandardOrUndefined()) {
4046 throw new IllegalArgumentException(
4047 "You can't move tasks from non-standard stacks.");
4048 }
4049 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4050 }
4051 } finally {
4052 Binder.restoreCallingIdentity(origId);
4053 }
4054 }
4055 }
4056
4057 /**
4058 * Moves the top activity in the input stackId to the pinned stack.
4059 *
4060 * @param stackId Id of stack to move the top activity to pinned stack.
4061 * @param bounds Bounds to use for pinned stack.
4062 *
4063 * @return True if the top activity of the input stack was successfully moved to the pinned
4064 * stack.
4065 */
4066 @Override
4067 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004068 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 "moveTopActivityToPinnedStack()");
4070 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004071 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4073 + "Device doesn't support picture-in-picture mode");
4074 }
4075
4076 long ident = Binder.clearCallingIdentity();
4077 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004078 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 } finally {
4080 Binder.restoreCallingIdentity(ident);
4081 }
4082 }
4083 }
4084
4085 @Override
4086 public boolean isInMultiWindowMode(IBinder token) {
4087 final long origId = Binder.clearCallingIdentity();
4088 try {
4089 synchronized (mGlobalLock) {
4090 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4091 if (r == null) {
4092 return false;
4093 }
4094 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4095 return r.inMultiWindowMode();
4096 }
4097 } finally {
4098 Binder.restoreCallingIdentity(origId);
4099 }
4100 }
4101
4102 @Override
4103 public boolean isInPictureInPictureMode(IBinder token) {
4104 final long origId = Binder.clearCallingIdentity();
4105 try {
4106 synchronized (mGlobalLock) {
4107 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4108 }
4109 } finally {
4110 Binder.restoreCallingIdentity(origId);
4111 }
4112 }
4113
4114 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004115 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4116 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 return false;
4118 }
4119
4120 // If we are animating to fullscreen then we have already dispatched the PIP mode
4121 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004122 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4123 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 }
4125
4126 @Override
4127 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4128 final long origId = Binder.clearCallingIdentity();
4129 try {
4130 synchronized (mGlobalLock) {
4131 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4132 "enterPictureInPictureMode", token, params);
4133
4134 // If the activity is already in picture in picture mode, then just return early
4135 if (isInPictureInPictureMode(r)) {
4136 return true;
4137 }
4138
4139 // Activity supports picture-in-picture, now check that we can enter PiP at this
4140 // point, if it is
4141 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4142 false /* beforeStopping */)) {
4143 return false;
4144 }
4145
4146 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004147 synchronized (mGlobalLock) {
4148 // Only update the saved args from the args that are set
4149 r.pictureInPictureArgs.copyOnlySet(params);
4150 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4151 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4152 // Adjust the source bounds by the insets for the transition down
4153 final Rect sourceBounds = new Rect(
4154 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004155 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004156 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004157 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004158 stack.setPictureInPictureAspectRatio(aspectRatio);
4159 stack.setPictureInPictureActions(actions);
4160 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4161 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4162 logPictureInPictureArgs(params);
4163 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 };
4165
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004166 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 // If the keyguard is showing or occluded, then try and dismiss it before
4168 // entering picture-in-picture (this will prompt the user to authenticate if the
4169 // device is currently locked).
4170 dismissKeyguard(token, new KeyguardDismissCallback() {
4171 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004172 public void onDismissSucceeded() {
4173 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175 }, null /* message */);
4176 } else {
4177 // Enter picture in picture immediately otherwise
4178 enterPipRunnable.run();
4179 }
4180 return true;
4181 }
4182 } finally {
4183 Binder.restoreCallingIdentity(origId);
4184 }
4185 }
4186
4187 @Override
4188 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4189 final long origId = Binder.clearCallingIdentity();
4190 try {
4191 synchronized (mGlobalLock) {
4192 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4193 "setPictureInPictureParams", token, params);
4194
4195 // Only update the saved args from the args that are set
4196 r.pictureInPictureArgs.copyOnlySet(params);
4197 if (r.inPinnedWindowingMode()) {
4198 // If the activity is already in picture-in-picture, update the pinned stack now
4199 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4200 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004201 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 if (!stack.isAnimatingBoundsToFullscreen()) {
4203 stack.setPictureInPictureAspectRatio(
4204 r.pictureInPictureArgs.getAspectRatio());
4205 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4206 }
4207 }
4208 logPictureInPictureArgs(params);
4209 }
4210 } finally {
4211 Binder.restoreCallingIdentity(origId);
4212 }
4213 }
4214
4215 @Override
4216 public int getMaxNumPictureInPictureActions(IBinder token) {
4217 // Currently, this is a static constant, but later, we may change this to be dependent on
4218 // the context of the activity
4219 return 3;
4220 }
4221
4222 private void logPictureInPictureArgs(PictureInPictureParams params) {
4223 if (params.hasSetActions()) {
4224 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4225 params.getActions().size());
4226 }
4227 if (params.hasSetAspectRatio()) {
4228 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4229 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4230 MetricsLogger.action(lm);
4231 }
4232 }
4233
4234 /**
4235 * Checks the state of the system and the activity associated with the given {@param token} to
4236 * verify that picture-in-picture is supported for that activity.
4237 *
4238 * @return the activity record for the given {@param token} if all the checks pass.
4239 */
4240 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4241 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 throw new IllegalStateException(caller
4244 + ": Device doesn't support picture-in-picture mode.");
4245 }
4246
4247 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4248 if (r == null) {
4249 throw new IllegalStateException(caller
4250 + ": Can't find activity for token=" + token);
4251 }
4252
4253 if (!r.supportsPictureInPicture()) {
4254 throw new IllegalStateException(caller
4255 + ": Current activity does not support picture-in-picture.");
4256 }
4257
4258 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004259 && !mWindowManager.isValidPictureInPictureAspectRatio(
4260 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 final float minAspectRatio = mContext.getResources().getFloat(
4262 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4263 final float maxAspectRatio = mContext.getResources().getFloat(
4264 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4265 throw new IllegalArgumentException(String.format(caller
4266 + ": Aspect ratio is too extreme (must be between %f and %f).",
4267 minAspectRatio, maxAspectRatio));
4268 }
4269
4270 // Truncate the number of actions if necessary
4271 params.truncateActions(getMaxNumPictureInPictureActions(token));
4272
4273 return r;
4274 }
4275
4276 @Override
4277 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004278 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 synchronized (mGlobalLock) {
4280 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4281 if (r == null) {
4282 throw new IllegalArgumentException("Activity does not exist; token="
4283 + activityToken);
4284 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004285 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 }
4287 }
4288
4289 @Override
4290 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4291 Rect tempDockedTaskInsetBounds,
4292 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 long ident = Binder.clearCallingIdentity();
4295 try {
4296 synchronized (mGlobalLock) {
4297 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4298 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4299 PRESERVE_WINDOWS);
4300 }
4301 } finally {
4302 Binder.restoreCallingIdentity(ident);
4303 }
4304 }
4305
4306 @Override
4307 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 final long ident = Binder.clearCallingIdentity();
4310 try {
4311 synchronized (mGlobalLock) {
4312 mStackSupervisor.setSplitScreenResizing(resizing);
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004319 /**
4320 * Check that we have the features required for VR-related API calls, and throw an exception if
4321 * not.
4322 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004323 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004324 if (!mContext.getPackageManager().hasSystemFeature(
4325 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4326 throw new UnsupportedOperationException("VR mode not supported on this device!");
4327 }
4328 }
4329
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 @Override
4331 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333
4334 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4335
4336 ActivityRecord r;
4337 synchronized (mGlobalLock) {
4338 r = ActivityRecord.isInStackLocked(token);
4339 }
4340
4341 if (r == null) {
4342 throw new IllegalArgumentException();
4343 }
4344
4345 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004346 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 VrManagerInternal.NO_ERROR) {
4348 return err;
4349 }
4350
4351 // Clear the binder calling uid since this path may call moveToTask().
4352 final long callingId = Binder.clearCallingIdentity();
4353 try {
4354 synchronized (mGlobalLock) {
4355 r.requestedVrComponent = (enabled) ? packageName : null;
4356
4357 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004358 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004359 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 }
4361 return 0;
4362 }
4363 } finally {
4364 Binder.restoreCallingIdentity(callingId);
4365 }
4366 }
4367
4368 @Override
4369 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4370 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4371 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004372 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4374 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4375 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004376 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 || activity.voiceSession != null) {
4378 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4379 return;
4380 }
4381 if (activity.pendingVoiceInteractionStart) {
4382 Slog.w(TAG, "Pending start of voice interaction already.");
4383 return;
4384 }
4385 activity.pendingVoiceInteractionStart = true;
4386 }
4387 LocalServices.getService(VoiceInteractionManagerInternal.class)
4388 .startLocalVoiceInteraction(callingActivity, options);
4389 }
4390
4391 @Override
4392 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4393 LocalServices.getService(VoiceInteractionManagerInternal.class)
4394 .stopLocalVoiceInteraction(callingActivity);
4395 }
4396
4397 @Override
4398 public boolean supportsLocalVoiceInteraction() {
4399 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4400 .supportsLocalVoiceInteraction();
4401 }
4402
4403 /** Notifies all listeners when the pinned stack animation starts. */
4404 @Override
4405 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004406 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 }
4408
4409 /** Notifies all listeners when the pinned stack animation ends. */
4410 @Override
4411 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004412 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 }
4414
4415 @Override
4416 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004417 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 final long ident = Binder.clearCallingIdentity();
4419 try {
4420 synchronized (mGlobalLock) {
4421 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4422 }
4423 } finally {
4424 Binder.restoreCallingIdentity(ident);
4425 }
4426 }
4427
4428 @Override
4429 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431
4432 synchronized (mGlobalLock) {
4433 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004434 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 // Call might come when display is not yet added or has already been removed.
4436 if (DEBUG_CONFIGURATION) {
4437 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4438 + displayId);
4439 }
4440 return false;
4441 }
4442
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 }
4447
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004449 final Message msg = PooledLambda.obtainMessage(
4450 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4451 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 }
4453
4454 final long origId = Binder.clearCallingIdentity();
4455 try {
4456 if (values != null) {
4457 Settings.System.clearConfiguration(values);
4458 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4461 return mTmpUpdateConfigurationResult.changes != 0;
4462 } finally {
4463 Binder.restoreCallingIdentity(origId);
4464 }
4465 }
4466 }
4467
4468 @Override
4469 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004470 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004471
4472 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004475 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 }
4477
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004478 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004479 final Message msg = PooledLambda.obtainMessage(
4480 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4481 DEFAULT_DISPLAY);
4482 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 }
4484
4485 final long origId = Binder.clearCallingIdentity();
4486 try {
4487 if (values != null) {
4488 Settings.System.clearConfiguration(values);
4489 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004490 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 UserHandle.USER_NULL, false /* deferResume */,
4492 mTmpUpdateConfigurationResult);
4493 return mTmpUpdateConfigurationResult.changes != 0;
4494 } finally {
4495 Binder.restoreCallingIdentity(origId);
4496 }
4497 }
4498 }
4499
4500 @Override
4501 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4502 CharSequence message) {
4503 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004504 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4506 }
4507 final long callingId = Binder.clearCallingIdentity();
4508 try {
4509 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004510 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 }
4512 } finally {
4513 Binder.restoreCallingIdentity(callingId);
4514 }
4515 }
4516
4517 @Override
4518 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004519 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 "cancelTaskWindowTransition()");
4521 final long ident = Binder.clearCallingIdentity();
4522 try {
4523 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004524 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004525 MATCH_TASK_IN_STACKS_ONLY);
4526 if (task == null) {
4527 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4528 return;
4529 }
4530 task.cancelWindowTransition();
4531 }
4532 } finally {
4533 Binder.restoreCallingIdentity(ident);
4534 }
4535 }
4536
4537 @Override
4538 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004539 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 final long ident = Binder.clearCallingIdentity();
4541 try {
4542 final TaskRecord task;
4543 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004544 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004545 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4546 if (task == null) {
4547 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4548 return null;
4549 }
4550 }
4551 // Don't call this while holding the lock as this operation might hit the disk.
4552 return task.getSnapshot(reducedResolution);
4553 } finally {
4554 Binder.restoreCallingIdentity(ident);
4555 }
4556 }
4557
4558 @Override
4559 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4560 synchronized (mGlobalLock) {
4561 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4562 if (r == null) {
4563 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4564 + token);
4565 return;
4566 }
4567 final long origId = Binder.clearCallingIdentity();
4568 try {
4569 r.setDisablePreviewScreenshots(disable);
4570 } finally {
4571 Binder.restoreCallingIdentity(origId);
4572 }
4573 }
4574 }
4575
4576 /** Return the user id of the last resumed activity. */
4577 @Override
4578 public @UserIdInt
4579 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004580 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4582 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004583 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004584 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004586 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 }
4588 }
4589
4590 @Override
4591 public void updateLockTaskFeatures(int userId, int flags) {
4592 final int callingUid = Binder.getCallingUid();
4593 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004594 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 "updateLockTaskFeatures()");
4596 }
4597 synchronized (mGlobalLock) {
4598 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4599 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004600 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 }
4602 }
4603
4604 @Override
4605 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4606 synchronized (mGlobalLock) {
4607 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4608 if (r == null) {
4609 return;
4610 }
4611 final long origId = Binder.clearCallingIdentity();
4612 try {
4613 r.setShowWhenLocked(showWhenLocked);
4614 } finally {
4615 Binder.restoreCallingIdentity(origId);
4616 }
4617 }
4618 }
4619
4620 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004621 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4622 synchronized (mGlobalLock) {
4623 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4624 if (r == null) {
4625 return;
4626 }
4627 final long origId = Binder.clearCallingIdentity();
4628 try {
4629 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4630 } finally {
4631 Binder.restoreCallingIdentity(origId);
4632 }
4633 }
4634 }
4635
4636 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4638 synchronized (mGlobalLock) {
4639 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4640 if (r == null) {
4641 return;
4642 }
4643 final long origId = Binder.clearCallingIdentity();
4644 try {
4645 r.setTurnScreenOn(turnScreenOn);
4646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650 }
4651
4652 @Override
4653 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 "registerRemoteAnimations");
4656 definition.setCallingPid(Binder.getCallingPid());
4657 synchronized (mGlobalLock) {
4658 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4659 if (r == null) {
4660 return;
4661 }
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
4664 r.registerRemoteAnimations(definition);
4665 } finally {
4666 Binder.restoreCallingIdentity(origId);
4667 }
4668 }
4669 }
4670
4671 @Override
4672 public void registerRemoteAnimationForNextActivityStart(String packageName,
4673 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004674 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004675 "registerRemoteAnimationForNextActivityStart");
4676 adapter.setCallingPid(Binder.getCallingPid());
4677 synchronized (mGlobalLock) {
4678 final long origId = Binder.clearCallingIdentity();
4679 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004680 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004681 packageName, adapter);
4682 } finally {
4683 Binder.restoreCallingIdentity(origId);
4684 }
4685 }
4686 }
4687
Evan Rosky966759f2019-01-15 10:33:58 -08004688 @Override
4689 public void registerRemoteAnimationsForDisplay(int displayId,
4690 RemoteAnimationDefinition definition) {
4691 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4692 "registerRemoteAnimations");
4693 definition.setCallingPid(Binder.getCallingPid());
4694 synchronized (mGlobalLock) {
4695 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4696 if (display == null) {
4697 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4698 return;
4699 }
4700 final long origId = Binder.clearCallingIdentity();
4701 try {
4702 display.mDisplayContent.registerRemoteAnimations(definition);
4703 } finally {
4704 Binder.restoreCallingIdentity(origId);
4705 }
4706 }
4707 }
4708
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004709 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4710 @Override
4711 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4712 synchronized (mGlobalLock) {
4713 final long origId = Binder.clearCallingIdentity();
4714 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004715 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004716 } finally {
4717 Binder.restoreCallingIdentity(origId);
4718 }
4719 }
4720 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004721
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 @Override
4723 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004726 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004727 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004728 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004729 }
4730 }
4731
4732 @Override
4733 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004734 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 != PERMISSION_GRANTED) {
4736 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4737 + Binder.getCallingPid()
4738 + ", uid=" + Binder.getCallingUid()
4739 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4740 Slog.w(TAG, msg);
4741 throw new SecurityException(msg);
4742 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004743 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004745 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004746 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004747 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004748 }
4749 }
4750
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004751 @Override
4752 public void stopAppSwitches() {
4753 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4754 synchronized (mGlobalLock) {
4755 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004756 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 mDidAppSwitch = false;
4758 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4759 }
4760 }
4761
4762 @Override
4763 public void resumeAppSwitches() {
4764 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4765 synchronized (mGlobalLock) {
4766 // Note that we don't execute any pending app switches... we will
4767 // let those wait until either the timeout, or the next start
4768 // activity request.
4769 mAppSwitchesAllowedTime = 0;
4770 }
4771 }
4772
Ricky Wai906af482019-06-03 17:25:28 +01004773 long getLastStopAppSwitchesTime() {
4774 return mLastStopAppSwitchesTime;
4775 }
4776
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004777 void onStartActivitySetDidAppSwitch() {
4778 if (mDidAppSwitch) {
4779 // This is the second allowed switch since we stopped switches, so now just generally
4780 // allow switches. Use case:
4781 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4782 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4783 // anyone to switch again).
4784 mAppSwitchesAllowedTime = 0;
4785 } else {
4786 mDidAppSwitch = true;
4787 }
4788 }
4789
4790 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 boolean shouldDisableNonVrUiLocked() {
4792 return mVrController.shouldDisableNonVrUiLocked();
4793 }
4794
Wale Ogunwale53783742018-09-16 10:21:51 -07004795 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 // VR apps are expected to run in a main display. If an app is turning on VR for
4797 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4798 // fullscreen stack before enabling VR Mode.
4799 // TODO: The goal of this code is to keep the VR app on the main display. When the
4800 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4801 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4802 // option would be a better choice here.
4803 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4804 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4805 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004806 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004807 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004808 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 }
4810 mH.post(() -> {
4811 if (!mVrController.onVrModeChanged(r)) {
4812 return;
4813 }
4814 synchronized (mGlobalLock) {
4815 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4816 mWindowManager.disableNonVrUi(disableNonVrUi);
4817 if (disableNonVrUi) {
4818 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4819 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004820 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004821 }
4822 }
4823 });
4824 }
4825
Wale Ogunwale53783742018-09-16 10:21:51 -07004826 @Override
4827 public int getPackageScreenCompatMode(String packageName) {
4828 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4829 synchronized (mGlobalLock) {
4830 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4831 }
4832 }
4833
4834 @Override
4835 public void setPackageScreenCompatMode(String packageName, int mode) {
4836 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4837 "setPackageScreenCompatMode");
4838 synchronized (mGlobalLock) {
4839 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4840 }
4841 }
4842
4843 @Override
4844 public boolean getPackageAskScreenCompat(String packageName) {
4845 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4846 synchronized (mGlobalLock) {
4847 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4848 }
4849 }
4850
4851 @Override
4852 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4853 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4854 "setPackageAskScreenCompat");
4855 synchronized (mGlobalLock) {
4856 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4857 }
4858 }
4859
Wale Ogunwale64258362018-10-16 15:13:37 -07004860 public static String relaunchReasonToString(int relaunchReason) {
4861 switch (relaunchReason) {
4862 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4863 return "window_resize";
4864 case RELAUNCH_REASON_FREE_RESIZE:
4865 return "free_resize";
4866 default:
4867 return null;
4868 }
4869 }
4870
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004871 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004872 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004873 }
4874
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004875 /** Pokes the task persister. */
4876 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4877 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4878 }
4879
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004880 boolean isKeyguardLocked() {
4881 return mKeyguardController.isKeyguardLocked();
4882 }
4883
Garfield Tan01548632018-11-27 10:15:48 -08004884 /**
4885 * Clears launch params for the given package.
4886 * @param packageNames the names of the packages of which the launch params are to be cleared
4887 */
4888 @Override
4889 public void clearLaunchParamsForPackages(List<String> packageNames) {
4890 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4891 "clearLaunchParamsForPackages");
4892 synchronized (mGlobalLock) {
4893 for (int i = 0; i < packageNames.size(); ++i) {
4894 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4895 }
4896 }
4897 }
4898
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004899 /**
4900 * Makes the display with the given id a single task instance display. I.e the display can only
4901 * contain one task.
4902 */
4903 @Override
4904 public void setDisplayToSingleTaskInstance(int displayId) {
4905 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4906 "setDisplayToSingleTaskInstance");
4907 final long origId = Binder.clearCallingIdentity();
4908 try {
4909 final ActivityDisplay display =
4910 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4911 if (display != null) {
4912 display.setDisplayToSingleTaskInstance();
4913 }
4914 } finally {
4915 Binder.restoreCallingIdentity(origId);
4916 }
4917 }
4918
Wale Ogunwale31913b52018-10-13 08:29:31 -07004919 void dumpLastANRLocked(PrintWriter pw) {
4920 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4921 if (mLastANRState == null) {
4922 pw.println(" <no ANR has occurred since boot>");
4923 } else {
4924 pw.println(mLastANRState);
4925 }
4926 }
4927
4928 void dumpLastANRTracesLocked(PrintWriter pw) {
4929 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4930
4931 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4932 if (ArrayUtils.isEmpty(files)) {
4933 pw.println(" <no ANR has occurred since boot>");
4934 return;
4935 }
4936 // Find the latest file.
4937 File latest = null;
4938 for (File f : files) {
4939 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4940 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004941 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004942 }
4943 pw.print("File: ");
4944 pw.print(latest.getName());
4945 pw.println();
4946 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4947 String line;
4948 while ((line = in.readLine()) != null) {
4949 pw.println(line);
4950 }
4951 } catch (IOException e) {
4952 pw.print("Unable to read: ");
4953 pw.print(e);
4954 pw.println();
4955 }
4956 }
4957
4958 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4959 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4960 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4961 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4962 }
4963
4964 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4965 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4966 pw.println(header);
4967
Wale Ogunwaled32da472018-11-16 07:19:28 -08004968 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004969 dumpPackage);
4970 boolean needSep = printedAnything;
4971
4972 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004973 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004974 " ResumedActivity: ");
4975 if (printed) {
4976 printedAnything = true;
4977 needSep = false;
4978 }
4979
4980 if (dumpPackage == null) {
4981 if (needSep) {
4982 pw.println();
4983 }
4984 printedAnything = true;
4985 mStackSupervisor.dump(pw, " ");
4986 }
4987
4988 if (!printedAnything) {
4989 pw.println(" (nothing)");
4990 }
4991 }
4992
4993 void dumpActivityContainersLocked(PrintWriter pw) {
4994 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004995 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004996 pw.println(" ");
4997 }
4998
4999 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5000 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5001 getActivityStartController().dump(pw, "", dumpPackage);
5002 }
5003
5004 /**
5005 * There are three things that cmd can be:
5006 * - a flattened component name that matches an existing activity
5007 * - the cmd arg isn't the flattened component name of an existing activity:
5008 * dump all activity whose component contains the cmd as a substring
5009 * - A hex number of the ActivityRecord object instance.
5010 *
5011 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5012 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5013 */
5014 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5015 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5016 ArrayList<ActivityRecord> activities;
5017
5018 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005019 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005020 dumpFocusedStackOnly);
5021 }
5022
5023 if (activities.size() <= 0) {
5024 return false;
5025 }
5026
5027 String[] newArgs = new String[args.length - opti];
5028 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5029
5030 TaskRecord lastTask = null;
5031 boolean needSep = false;
5032 for (int i = activities.size() - 1; i >= 0; i--) {
5033 ActivityRecord r = activities.get(i);
5034 if (needSep) {
5035 pw.println();
5036 }
5037 needSep = true;
5038 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005039 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005040 if (lastTask != task) {
5041 lastTask = task;
5042 pw.print("TASK "); pw.print(lastTask.affinity);
5043 pw.print(" id="); pw.print(lastTask.taskId);
5044 pw.print(" userId="); pw.println(lastTask.userId);
5045 if (dumpAll) {
5046 lastTask.dump(pw, " ");
5047 }
5048 }
5049 }
5050 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5051 }
5052 return true;
5053 }
5054
5055 /**
5056 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5057 * there is a thread associated with the activity.
5058 */
5059 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5060 final ActivityRecord r, String[] args, boolean dumpAll) {
5061 String innerPrefix = prefix + " ";
5062 synchronized (mGlobalLock) {
5063 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5064 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5065 pw.print(" pid=");
5066 if (r.hasProcess()) pw.println(r.app.getPid());
5067 else pw.println("(not running)");
5068 if (dumpAll) {
5069 r.dump(pw, innerPrefix);
5070 }
5071 }
5072 if (r.attachedToProcess()) {
5073 // flush anything that is already in the PrintWriter since the thread is going
5074 // to write to the file descriptor directly
5075 pw.flush();
5076 try {
5077 TransferPipe tp = new TransferPipe();
5078 try {
5079 r.app.getThread().dumpActivity(tp.getWriteFd(),
5080 r.appToken, innerPrefix, args);
5081 tp.go(fd);
5082 } finally {
5083 tp.kill();
5084 }
5085 } catch (IOException e) {
5086 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5087 } catch (RemoteException e) {
5088 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5089 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005090 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005091 }
5092
sanryhuang498e77e2018-12-06 14:57:01 +08005093 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5094 boolean testPssMode) {
5095 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5096 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5097 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005098 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005099 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5100 st.toString());
5101 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005102 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5103 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5104 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005105 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5106 testPssMode);
5107 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005108 }
5109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005110 int getCurrentUserId() {
5111 return mAmInternal.getCurrentUserId();
5112 }
5113
5114 private void enforceNotIsolatedCaller(String caller) {
5115 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5116 throw new SecurityException("Isolated process not allowed to call " + caller);
5117 }
5118 }
5119
Wale Ogunwalef6733932018-06-27 05:14:34 -07005120 public Configuration getConfiguration() {
5121 Configuration ci;
5122 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005123 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005124 ci.userSetLocale = false;
5125 }
5126 return ci;
5127 }
5128
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 /**
5130 * Current global configuration information. Contains general settings for the entire system,
5131 * also corresponds to the merged configuration of the default display.
5132 */
5133 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005134 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135 }
5136
5137 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5138 boolean initLocale) {
5139 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5140 }
5141
5142 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5143 boolean initLocale, boolean deferResume) {
5144 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5145 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5146 UserHandle.USER_NULL, deferResume);
5147 }
5148
Wale Ogunwale59507092018-10-29 09:00:30 -07005149 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005150 final long origId = Binder.clearCallingIdentity();
5151 try {
5152 synchronized (mGlobalLock) {
5153 updateConfigurationLocked(values, null, false, true, userId,
5154 false /* deferResume */);
5155 }
5156 } finally {
5157 Binder.restoreCallingIdentity(origId);
5158 }
5159 }
5160
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005161 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5162 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5163 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5164 deferResume, null /* result */);
5165 }
5166
5167 /**
5168 * Do either or both things: (1) change the current configuration, and (2)
5169 * make sure the given activity is running with the (now) current
5170 * configuration. Returns true if the activity has been left running, or
5171 * false if <var>starting</var> is being destroyed to match the new
5172 * configuration.
5173 *
5174 * @param userId is only used when persistent parameter is set to true to persist configuration
5175 * for that particular user
5176 */
5177 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5178 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5179 ActivityTaskManagerService.UpdateConfigurationResult result) {
5180 int changes = 0;
5181 boolean kept = true;
5182
5183 if (mWindowManager != null) {
5184 mWindowManager.deferSurfaceLayout();
5185 }
5186 try {
5187 if (values != null) {
5188 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5189 deferResume);
5190 }
5191
5192 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5193 } finally {
5194 if (mWindowManager != null) {
5195 mWindowManager.continueSurfaceLayout();
5196 }
5197 }
5198
5199 if (result != null) {
5200 result.changes = changes;
5201 result.activityRelaunched = !kept;
5202 }
5203 return kept;
5204 }
5205
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005206 /** Update default (global) configuration and notify listeners about changes. */
5207 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5208 boolean persistent, int userId, boolean deferResume) {
5209 mTempConfig.setTo(getGlobalConfiguration());
5210 final int changes = mTempConfig.updateFrom(values);
5211 if (changes == 0) {
5212 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5213 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5214 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5215 // (even if there are no actual changes) to unfreeze the window.
5216 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5217 return 0;
5218 }
5219
5220 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5221 "Updating global configuration to: " + values);
5222
5223 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5224 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5225 values.colorMode,
5226 values.densityDpi,
5227 values.fontScale,
5228 values.hardKeyboardHidden,
5229 values.keyboard,
5230 values.keyboardHidden,
5231 values.mcc,
5232 values.mnc,
5233 values.navigation,
5234 values.navigationHidden,
5235 values.orientation,
5236 values.screenHeightDp,
5237 values.screenLayout,
5238 values.screenWidthDp,
5239 values.smallestScreenWidthDp,
5240 values.touchscreen,
5241 values.uiMode);
5242
5243
5244 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5245 final LocaleList locales = values.getLocales();
5246 int bestLocaleIndex = 0;
5247 if (locales.size() > 1) {
5248 if (mSupportedSystemLocales == null) {
5249 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5250 }
5251 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5252 }
5253 SystemProperties.set("persist.sys.locale",
5254 locales.get(bestLocaleIndex).toLanguageTag());
5255 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005256
5257 final Message m = PooledLambda.obtainMessage(
5258 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5259 locales.get(bestLocaleIndex));
5260 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005261 }
5262
Yunfan Chen75157d72018-07-27 14:47:21 +09005263 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005264
5265 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005266 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005267
5268 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5269 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005270 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271
5272 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274
5275 AttributeCache ac = AttributeCache.instance();
5276 if (ac != null) {
5277 ac.updateConfiguration(mTempConfig);
5278 }
5279
5280 // Make sure all resources in our process are updated right now, so that anyone who is going
5281 // to retrieve resource values after we return will be sure to get the new ones. This is
5282 // especially important during boot, where the first config change needs to guarantee all
5283 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005284 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285
5286 // We need another copy of global config because we're scheduling some calls instead of
5287 // running them in place. We need to be sure that object we send will be handled unchanged.
5288 final Configuration configCopy = new Configuration(mTempConfig);
5289 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005290 final Message msg = PooledLambda.obtainMessage(
5291 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5292 this, userId, configCopy);
5293 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 }
5295
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005296 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5297 for (int i = pidMap.size() - 1; i >= 0; i--) {
5298 final int pid = pidMap.keyAt(i);
5299 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005300 if (DEBUG_CONFIGURATION) {
5301 Slog.v(TAG_CONFIGURATION, "Update process config of "
5302 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005303 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005304 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005305 }
5306
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005307 final Message msg = PooledLambda.obtainMessage(
5308 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5309 mAmInternal, changes, initLocale);
5310 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311
5312 // Override configuration of the default display duplicates global config, so we need to
5313 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005314 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005315 DEFAULT_DISPLAY);
5316
5317 return changes;
5318 }
5319
5320 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5321 boolean deferResume, int displayId) {
5322 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5323 displayId, null /* result */);
5324 }
5325
5326 /**
5327 * Updates override configuration specific for the selected display. If no config is provided,
5328 * new one will be computed in WM based on current display info.
5329 */
5330 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5331 ActivityRecord starting, boolean deferResume, int displayId,
5332 ActivityTaskManagerService.UpdateConfigurationResult result) {
5333 int changes = 0;
5334 boolean kept = true;
5335
5336 if (mWindowManager != null) {
5337 mWindowManager.deferSurfaceLayout();
5338 }
5339 try {
5340 if (values != null) {
5341 if (displayId == DEFAULT_DISPLAY) {
5342 // Override configuration of the default display duplicates global config, so
5343 // we're calling global config update instead for default display. It will also
5344 // apply the correct override config.
5345 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5346 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5347 } else {
5348 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5349 }
5350 }
5351
5352 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5353 } finally {
5354 if (mWindowManager != null) {
5355 mWindowManager.continueSurfaceLayout();
5356 }
5357 }
5358
5359 if (result != null) {
5360 result.changes = changes;
5361 result.activityRelaunched = !kept;
5362 }
5363 return kept;
5364 }
5365
5366 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5367 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005368 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369 final int changes = mTempConfig.updateFrom(values);
5370 if (changes != 0) {
5371 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5372 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005373 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005374
5375 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5376 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005377 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005378
Wale Ogunwale5c918702018-10-18 11:06:33 -07005379 // Post message to start process to avoid possible deadlock of calling into AMS with
5380 // the ATMS lock held.
5381 final Message msg = PooledLambda.obtainMessage(
5382 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005383 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005384 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005385 }
5386 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005387 return changes;
5388 }
5389
Wale Ogunwalef6733932018-06-27 05:14:34 -07005390 private void updateEventDispatchingLocked(boolean booted) {
5391 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5392 }
5393
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005394 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5395 final ContentResolver resolver = mContext.getContentResolver();
5396 Settings.System.putConfigurationForUser(resolver, config, userId);
5397 }
5398
5399 private void sendLocaleToMountDaemonMsg(Locale l) {
5400 try {
5401 IBinder service = ServiceManager.getService("mount");
5402 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5403 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5404 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5405 } catch (RemoteException e) {
5406 Log.e(TAG, "Error storing locale for decryption UI", e);
5407 }
5408 }
5409
Alison Cichowlas3e340502018-08-07 17:15:01 -04005410 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5411 mStartActivitySources.remove(permissionToken);
5412 mExpiredStartAsCallerTokens.add(permissionToken);
5413 }
5414
5415 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5416 mExpiredStartAsCallerTokens.remove(permissionToken);
5417 }
5418
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005419 boolean isActivityStartsLoggingEnabled() {
5420 return mAmInternal.isActivityStartsLoggingEnabled();
5421 }
5422
Michal Karpinski8596ded2018-11-14 14:43:48 +00005423 boolean isBackgroundActivityStartsEnabled() {
5424 return mAmInternal.isBackgroundActivityStartsEnabled();
5425 }
5426
Wale Ogunwalef6733932018-06-27 05:14:34 -07005427 void enableScreenAfterBoot(boolean booted) {
5428 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5429 SystemClock.uptimeMillis());
5430 mWindowManager.enableScreenAfterBoot();
5431
5432 synchronized (mGlobalLock) {
5433 updateEventDispatchingLocked(booted);
5434 }
5435 }
5436
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005437 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5438 if (r == null || !r.hasProcess()) {
5439 return KEY_DISPATCHING_TIMEOUT_MS;
5440 }
5441 return getInputDispatchingTimeoutLocked(r.app);
5442 }
5443
5444 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005445 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005446 }
5447
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 /**
5449 * Decide based on the configuration whether we should show the ANR,
5450 * crash, etc dialogs. The idea is that if there is no affordance to
5451 * press the on-screen buttons, or the user experience would be more
5452 * greatly impacted than the crash itself, we shouldn't show the dialog.
5453 *
5454 * A thought: SystemUI might also want to get told about this, the Power
5455 * dialog / global actions also might want different behaviors.
5456 */
5457 private void updateShouldShowDialogsLocked(Configuration config) {
5458 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5459 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5460 && config.navigation == Configuration.NAVIGATION_NONAV);
5461 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5462 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5463 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5464 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5465 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5466 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5467 HIDE_ERROR_DIALOGS, 0) != 0;
5468 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5469 }
5470
5471 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5472 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5473 FONT_SCALE, 1.0f, userId);
5474
5475 synchronized (this) {
5476 if (getGlobalConfiguration().fontScale == scaleFactor) {
5477 return;
5478 }
5479
5480 final Configuration configuration
5481 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5482 configuration.fontScale = scaleFactor;
5483 updatePersistentConfiguration(configuration, userId);
5484 }
5485 }
5486
5487 // Actually is sleeping or shutting down or whatever else in the future
5488 // is an inactive state.
5489 boolean isSleepingOrShuttingDownLocked() {
5490 return isSleepingLocked() || mShuttingDown;
5491 }
5492
5493 boolean isSleepingLocked() {
5494 return mSleeping;
5495 }
5496
Riddle Hsu16567132018-08-16 21:37:47 +08005497 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005498 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005499 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 if (task.isActivityTypeStandard()) {
5501 if (mCurAppTimeTracker != r.appTimeTracker) {
5502 // We are switching app tracking. Complete the current one.
5503 if (mCurAppTimeTracker != null) {
5504 mCurAppTimeTracker.stop();
5505 mH.obtainMessage(
5506 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005507 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 mCurAppTimeTracker = null;
5509 }
5510 if (r.appTimeTracker != null) {
5511 mCurAppTimeTracker = r.appTimeTracker;
5512 startTimeTrackingFocusedActivityLocked();
5513 }
5514 } else {
5515 startTimeTrackingFocusedActivityLocked();
5516 }
5517 } else {
5518 r.appTimeTracker = null;
5519 }
5520 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5521 // TODO: Probably not, because we don't want to resume voice on switching
5522 // back to this activity
5523 if (task.voiceInteractor != null) {
5524 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5525 } else {
5526 finishRunningVoiceLocked();
5527
5528 if (mLastResumedActivity != null) {
5529 final IVoiceInteractionSession session;
5530
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005531 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005532 if (lastResumedActivityTask != null
5533 && lastResumedActivityTask.voiceSession != null) {
5534 session = lastResumedActivityTask.voiceSession;
5535 } else {
5536 session = mLastResumedActivity.voiceSession;
5537 }
5538
5539 if (session != null) {
5540 // We had been in a voice interaction session, but now focused has
5541 // move to something different. Just finish the session, we can't
5542 // return to it and retain the proper state and synchronization with
5543 // the voice interaction service.
5544 finishVoiceTask(session);
5545 }
5546 }
5547 }
5548
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005549 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5550 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 }
5552 updateResumedAppTrace(r);
5553 mLastResumedActivity = r;
5554
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005555 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556
5557 applyUpdateLockStateLocked(r);
5558 applyUpdateVrModeLocked(r);
5559
5560 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005561 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 r == null ? "NULL" : r.shortComponentName,
5563 reason);
5564 }
5565
5566 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5567 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005568 final ActivityTaskManagerInternal.SleepToken token =
5569 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 updateSleepIfNeededLocked();
5571 return token;
5572 }
5573 }
5574
5575 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005576 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005577 final boolean wasSleeping = mSleeping;
5578 boolean updateOomAdj = false;
5579
5580 if (!shouldSleep) {
5581 // If wasSleeping is true, we need to wake up activity manager state from when
5582 // we started sleeping. In either case, we need to apply the sleep tokens, which
5583 // will wake up stacks or put them to sleep as appropriate.
5584 if (wasSleeping) {
5585 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005586 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5587 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005588 startTimeTrackingFocusedActivityLocked();
5589 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005590 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5592 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005593 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005594 if (wasSleeping) {
5595 updateOomAdj = true;
5596 }
5597 } else if (!mSleeping && shouldSleep) {
5598 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005599 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5600 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601 if (mCurAppTimeTracker != null) {
5602 mCurAppTimeTracker.stop();
5603 }
5604 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005605 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 mStackSupervisor.goingToSleepLocked();
5607 updateResumedAppTrace(null /* resumed */);
5608 updateOomAdj = true;
5609 }
5610 if (updateOomAdj) {
5611 mH.post(mAmInternal::updateOomAdj);
5612 }
5613 }
5614
5615 void updateOomAdj() {
5616 mH.post(mAmInternal::updateOomAdj);
5617 }
5618
Wale Ogunwale53783742018-09-16 10:21:51 -07005619 void updateCpuStats() {
5620 mH.post(mAmInternal::updateCpuStats);
5621 }
5622
Hui Yu03d12402018-12-06 18:00:37 -08005623 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5624 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005625 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5626 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005627 mH.sendMessage(m);
5628 }
5629
Hui Yu03d12402018-12-06 18:00:37 -08005630 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005631 ComponentName taskRoot = null;
5632 final TaskRecord task = activity.getTaskRecord();
5633 if (task != null) {
5634 final ActivityRecord rootActivity = task.getRootActivity();
5635 if (rootActivity != null) {
5636 taskRoot = rootActivity.mActivityComponent;
5637 }
5638 }
5639
Hui Yu03d12402018-12-06 18:00:37 -08005640 final Message m = PooledLambda.obtainMessage(
5641 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005642 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005643 mH.sendMessage(m);
5644 }
5645
Wale Ogunwale53783742018-09-16 10:21:51 -07005646 void setBooting(boolean booting) {
5647 mAmInternal.setBooting(booting);
5648 }
5649
5650 boolean isBooting() {
5651 return mAmInternal.isBooting();
5652 }
5653
5654 void setBooted(boolean booted) {
5655 mAmInternal.setBooted(booted);
5656 }
5657
5658 boolean isBooted() {
5659 return mAmInternal.isBooted();
5660 }
5661
5662 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5663 mH.post(() -> {
5664 if (finishBooting) {
5665 mAmInternal.finishBooting();
5666 }
5667 if (enableScreen) {
5668 mInternal.enableScreenAfterBoot(isBooted());
5669 }
5670 });
5671 }
5672
5673 void setHeavyWeightProcess(ActivityRecord root) {
5674 mHeavyWeightProcess = root.app;
5675 final Message m = PooledLambda.obtainMessage(
5676 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005677 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005678 mH.sendMessage(m);
5679 }
5680
5681 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5682 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5683 return;
5684 }
5685
5686 mHeavyWeightProcess = null;
5687 final Message m = PooledLambda.obtainMessage(
5688 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5689 proc.mUserId);
5690 mH.sendMessage(m);
5691 }
5692
5693 private void cancelHeavyWeightProcessNotification(int userId) {
5694 final INotificationManager inm = NotificationManager.getService();
5695 if (inm == null) {
5696 return;
5697 }
5698 try {
5699 inm.cancelNotificationWithTag("android", null,
5700 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5701 } catch (RuntimeException e) {
5702 Slog.w(TAG, "Error canceling notification for service", e);
5703 } catch (RemoteException e) {
5704 }
5705
5706 }
5707
5708 private void postHeavyWeightProcessNotification(
5709 WindowProcessController proc, Intent intent, int userId) {
5710 if (proc == null) {
5711 return;
5712 }
5713
5714 final INotificationManager inm = NotificationManager.getService();
5715 if (inm == null) {
5716 return;
5717 }
5718
5719 try {
5720 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5721 String text = mContext.getString(R.string.heavy_weight_notification,
5722 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5723 Notification notification =
5724 new Notification.Builder(context,
5725 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5726 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5727 .setWhen(0)
5728 .setOngoing(true)
5729 .setTicker(text)
5730 .setColor(mContext.getColor(
5731 com.android.internal.R.color.system_notification_accent_color))
5732 .setContentTitle(text)
5733 .setContentText(
5734 mContext.getText(R.string.heavy_weight_notification_detail))
5735 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5736 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5737 new UserHandle(userId)))
5738 .build();
5739 try {
5740 inm.enqueueNotificationWithTag("android", "android", null,
5741 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5742 } catch (RuntimeException e) {
5743 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5744 } catch (RemoteException e) {
5745 }
5746 } catch (PackageManager.NameNotFoundException e) {
5747 Slog.w(TAG, "Unable to create context for heavy notification", e);
5748 }
5749
5750 }
5751
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005752 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5753 IBinder token, String resultWho, int requestCode, Intent[] intents,
5754 String[] resolvedTypes, int flags, Bundle bOptions) {
5755
5756 ActivityRecord activity = null;
5757 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5758 activity = ActivityRecord.isInStackLocked(token);
5759 if (activity == null) {
5760 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5761 return null;
5762 }
5763 if (activity.finishing) {
5764 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5765 return null;
5766 }
5767 }
5768
5769 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5770 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5771 bOptions);
5772 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5773 if (noCreate) {
5774 return rec;
5775 }
5776 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5777 if (activity.pendingResults == null) {
5778 activity.pendingResults = new HashSet<>();
5779 }
5780 activity.pendingResults.add(rec.ref);
5781 }
5782 return rec;
5783 }
5784
Andrii Kulian52d255c2018-07-13 11:32:19 -07005785 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005786 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005787 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005788 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5789 mCurAppTimeTracker.start(resumedActivity.packageName);
5790 }
5791 }
5792
5793 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5794 if (mTracedResumedActivity != null) {
5795 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5796 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5797 }
5798 if (resumed != null) {
5799 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5800 constructResumedTraceName(resumed.packageName), 0);
5801 }
5802 mTracedResumedActivity = resumed;
5803 }
5804
5805 private String constructResumedTraceName(String packageName) {
5806 return "focused app: " + packageName;
5807 }
5808
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005809 /** Applies latest configuration and/or visibility updates if needed. */
5810 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5811 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005812 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005813 // mainStack is null during startup.
5814 if (mainStack != null) {
5815 if (changes != 0 && starting == null) {
5816 // If the configuration changed, and the caller is not already
5817 // in the process of starting an activity, then find the top
5818 // activity to check if its configuration needs to change.
5819 starting = mainStack.topRunningActivityLocked();
5820 }
5821
5822 if (starting != null) {
5823 kept = starting.ensureActivityConfiguration(changes,
5824 false /* preserveWindow */);
5825 // And we need to make sure at this point that all other activities
5826 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005827 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005828 !PRESERVE_WINDOWS);
5829 }
5830 }
5831
5832 return kept;
5833 }
5834
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005835 void scheduleAppGcsLocked() {
5836 mH.post(() -> mAmInternal.scheduleAppGcs());
5837 }
5838
Wale Ogunwale53783742018-09-16 10:21:51 -07005839 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5840 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5841 }
5842
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005843 /**
5844 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5845 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5846 * on demand.
5847 */
5848 IPackageManager getPackageManager() {
5849 return AppGlobals.getPackageManager();
5850 }
5851
5852 PackageManagerInternal getPackageManagerInternalLocked() {
5853 if (mPmInternal == null) {
5854 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5855 }
5856 return mPmInternal;
5857 }
5858
Hai Zhangf4da9be2019-05-01 13:46:06 +08005859 PermissionPolicyInternal getPermissionPolicyInternal() {
5860 if (mPermissionPolicyInternal == null) {
5861 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5862 }
5863 return mPermissionPolicyInternal;
5864 }
5865
Wale Ogunwale008163e2018-07-23 23:11:08 -07005866 AppWarnings getAppWarningsLocked() {
5867 return mAppWarnings;
5868 }
5869
Wale Ogunwale214f3482018-10-04 11:00:47 -07005870 Intent getHomeIntent() {
5871 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5872 intent.setComponent(mTopComponent);
5873 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5874 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5875 intent.addCategory(Intent.CATEGORY_HOME);
5876 }
5877 return intent;
5878 }
5879
Chilun2ef71f72018-11-16 17:57:15 +08005880 /**
5881 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5882 * activities.
5883 *
5884 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5885 * component defined in config_secondaryHomeComponent.
5886 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5887 */
5888 Intent getSecondaryHomeIntent(String preferredPackage) {
5889 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005890 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5891 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5892 if (preferredPackage == null || useSystemProvidedLauncher) {
5893 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005894 final String secondaryHomeComponent = mContext.getResources().getString(
5895 com.android.internal.R.string.config_secondaryHomeComponent);
5896 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5897 } else {
5898 intent.setPackage(preferredPackage);
5899 }
5900 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5901 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5902 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5903 }
5904 return intent;
5905 }
5906
Wale Ogunwale214f3482018-10-04 11:00:47 -07005907 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5908 if (info == null) return null;
5909 ApplicationInfo newInfo = new ApplicationInfo(info);
5910 newInfo.initForUser(userId);
5911 return newInfo;
5912 }
5913
Wale Ogunwale9c103022018-10-18 07:44:54 -07005914 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005915 if (uid == SYSTEM_UID) {
5916 // The system gets to run in any process. If there are multiple processes with the same
5917 // uid, just pick the first (this should never happen).
5918 final SparseArray<WindowProcessController> procs =
5919 mProcessNames.getMap().get(processName);
5920 if (procs == null) return null;
5921 final int procCount = procs.size();
5922 for (int i = 0; i < procCount; i++) {
5923 final int procUid = procs.keyAt(i);
5924 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5925 // Don't use an app process or different user process for system component.
5926 continue;
5927 }
5928 return procs.valueAt(i);
5929 }
5930 }
5931
5932 return mProcessNames.get(processName, uid);
5933 }
5934
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005935 WindowProcessController getProcessController(IApplicationThread thread) {
5936 if (thread == null) {
5937 return null;
5938 }
5939
5940 final IBinder threadBinder = thread.asBinder();
5941 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5942 for (int i = pmap.size()-1; i >= 0; i--) {
5943 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5944 for (int j = procs.size() - 1; j >= 0; j--) {
5945 final WindowProcessController proc = procs.valueAt(j);
5946 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5947 return proc;
5948 }
5949 }
5950 }
5951
5952 return null;
5953 }
5954
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005955 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005956 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005957 if (proc == null) return null;
5958 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5959 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005960 }
5961 return null;
5962 }
5963
Riddle Hsua0536432019-02-16 00:38:59 +08005964 int getUidState(int uid) {
5965 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005966 }
5967
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005968 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005969 // A uid is considered to be foreground if it has a visible non-toast window.
5970 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005971 }
5972
Ricky Wai96f5c352019-04-10 18:40:17 +01005973 boolean isDeviceOwner(int uid) {
5974 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005975 }
5976
Ricky Wai96f5c352019-04-10 18:40:17 +01005977 void setDeviceOwnerUid(int uid) {
5978 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005979 }
5980
Wale Ogunwale9de19442018-10-18 19:05:03 -07005981 /**
5982 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5983 * the whitelist
5984 */
5985 String getPendingTempWhitelistTagForUidLocked(int uid) {
5986 return mPendingTempWhitelist.get(uid);
5987 }
5988
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005989 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5990 if (true || Build.IS_USER) {
5991 return;
5992 }
5993
5994 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5995 StrictMode.allowThreadDiskWrites();
5996 try {
5997 File tracesDir = new File("/data/anr");
5998 File tracesFile = null;
5999 try {
6000 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6001
6002 StringBuilder sb = new StringBuilder();
6003 Time tobj = new Time();
6004 tobj.set(System.currentTimeMillis());
6005 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
6006 sb.append(": ");
6007 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6008 sb.append(" since ");
6009 sb.append(msg);
6010 FileOutputStream fos = new FileOutputStream(tracesFile);
6011 fos.write(sb.toString().getBytes());
6012 if (app == null) {
6013 fos.write("\n*** No application process!".getBytes());
6014 }
6015 fos.close();
6016 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6017 } catch (IOException e) {
6018 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6019 return;
6020 }
6021
6022 if (app != null && app.getPid() > 0) {
6023 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6024 firstPids.add(app.getPid());
6025 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6026 }
6027
6028 File lastTracesFile = null;
6029 File curTracesFile = null;
6030 for (int i=9; i>=0; i--) {
6031 String name = String.format(Locale.US, "slow%02d.txt", i);
6032 curTracesFile = new File(tracesDir, name);
6033 if (curTracesFile.exists()) {
6034 if (lastTracesFile != null) {
6035 curTracesFile.renameTo(lastTracesFile);
6036 } else {
6037 curTracesFile.delete();
6038 }
6039 }
6040 lastTracesFile = curTracesFile;
6041 }
6042 tracesFile.renameTo(curTracesFile);
6043 } finally {
6044 StrictMode.setThreadPolicy(oldPolicy);
6045 }
6046 }
6047
Michal Karpinskida34cd42019-04-02 19:46:52 +01006048 boolean isAssociatedCompanionApp(int userId, int uid) {
6049 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6050 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006051 return false;
6052 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006053 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006054 }
6055
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006056 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006057 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006058
6059
Wale Ogunwale98875612018-10-12 07:53:02 -07006060 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6061 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006062
Riddle Hsud93a6c42018-11-29 21:50:06 +08006063 H(Looper looper) {
6064 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006065 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006066
6067 @Override
6068 public void handleMessage(Message msg) {
6069 switch (msg.what) {
6070 case REPORT_TIME_TRACKER_MSG: {
6071 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6072 tracker.deliverResult(mContext);
6073 } break;
6074 }
6075 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006076 }
6077
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006078 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006079 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006080
6081 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006082 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006083 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006084
6085 @Override
6086 public void handleMessage(Message msg) {
6087 switch (msg.what) {
6088 case DISMISS_DIALOG_UI_MSG: {
6089 final Dialog d = (Dialog) msg.obj;
6090 d.dismiss();
6091 break;
6092 }
6093 }
6094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006095 }
6096
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006097 final class LocalService extends ActivityTaskManagerInternal {
6098 @Override
6099 public SleepToken acquireSleepToken(String tag, int displayId) {
6100 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006101 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006102 }
6103
6104 @Override
6105 public ComponentName getHomeActivityForUser(int userId) {
6106 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006107 final ActivityRecord homeActivity =
6108 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006109 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 }
6111 }
6112
6113 @Override
6114 public void onLocalVoiceInteractionStarted(IBinder activity,
6115 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6116 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006117 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006118 }
6119 }
6120
6121 @Override
6122 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6123 synchronized (mGlobalLock) {
6124 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6125 reasons, timestamp);
6126 }
6127 }
6128
6129 @Override
6130 public void notifyAppTransitionFinished() {
6131 synchronized (mGlobalLock) {
6132 mStackSupervisor.notifyAppTransitionDone();
6133 }
6134 }
6135
6136 @Override
6137 public void notifyAppTransitionCancelled() {
6138 synchronized (mGlobalLock) {
6139 mStackSupervisor.notifyAppTransitionDone();
6140 }
6141 }
6142
6143 @Override
6144 public List<IBinder> getTopVisibleActivities() {
6145 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006146 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006147 }
6148 }
6149
6150 @Override
6151 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6152 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006153 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 }
6155 }
6156
6157 @Override
6158 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6159 Bundle bOptions) {
6160 Preconditions.checkNotNull(intents, "intents");
6161 final String[] resolvedTypes = new String[intents.length];
6162
6163 // UID of the package on user userId.
6164 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6165 // packageUid may not be initialized.
6166 int packageUid = 0;
6167 final long ident = Binder.clearCallingIdentity();
6168
6169 try {
6170 for (int i = 0; i < intents.length; i++) {
6171 resolvedTypes[i] =
6172 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6173 }
6174
6175 packageUid = AppGlobals.getPackageManager().getPackageUid(
6176 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6177 } catch (RemoteException e) {
6178 // Shouldn't happen.
6179 } finally {
6180 Binder.restoreCallingIdentity(ident);
6181 }
6182
Riddle Hsu591bf612019-02-14 17:55:31 +08006183 return getActivityStartController().startActivitiesInPackage(
6184 packageUid, packageName,
6185 intents, resolvedTypes, null /* resultTo */,
6186 SafeActivityOptions.fromBundle(bOptions), userId,
6187 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6188 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 }
6190
6191 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006192 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6193 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6194 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6195 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006196 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006197 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006198 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6199 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6200 userId, validateIncomingUser, originatingPendingIntent,
6201 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006202 }
6203 }
6204
6205 @Override
6206 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6207 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6208 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6209 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006210 PendingIntentRecord originatingPendingIntent,
6211 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006212 synchronized (mGlobalLock) {
6213 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6214 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6215 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006216 validateIncomingUser, originatingPendingIntent,
6217 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006218 }
6219 }
6220
6221 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6223 Intent intent, Bundle options, int userId) {
6224 return ActivityTaskManagerService.this.startActivityAsUser(
6225 caller, callerPacakge, intent,
6226 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6227 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6228 false /*validateIncomingUser*/);
6229 }
6230
6231 @Override
lumark588a3e82018-07-20 18:53:54 +08006232 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 synchronized (mGlobalLock) {
6234
6235 // We might change the visibilities here, so prepare an empty app transition which
6236 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006237 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006238 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006239 if (activityDisplay == null) {
6240 return;
6241 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006242 final DisplayContent dc = activityDisplay.mDisplayContent;
6243 final boolean wasTransitionSet =
6244 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006245 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006246 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006247 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006248 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249
6250 // If there was a transition set already we don't want to interfere with it as we
6251 // might be starting it too early.
6252 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006253 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 }
6255 }
6256 if (callback != null) {
6257 callback.run();
6258 }
6259 }
6260
6261 @Override
6262 public void notifyKeyguardTrustedChanged() {
6263 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006264 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006265 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 }
6267 }
6268 }
6269
6270 /**
6271 * Called after virtual display Id is updated by
6272 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6273 * {@param vrVr2dDisplayId}.
6274 */
6275 @Override
6276 public void setVr2dDisplayId(int vr2dDisplayId) {
6277 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6278 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006279 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006280 }
6281 }
6282
6283 @Override
6284 public void setFocusedActivity(IBinder token) {
6285 synchronized (mGlobalLock) {
6286 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6287 if (r == null) {
6288 throw new IllegalArgumentException(
6289 "setFocusedActivity: No activity record matching token=" + token);
6290 }
Louis Chang19443452018-10-09 12:10:21 +08006291 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006292 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 }
6294 }
6295 }
6296
6297 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006299 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006300 }
6301
6302 @Override
6303 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006304 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006305 }
6306
6307 @Override
6308 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006309 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310 }
6311
6312 @Override
6313 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6314 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6315 }
6316
6317 @Override
6318 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006319 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006320 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006321
6322 @Override
6323 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6324 synchronized (mGlobalLock) {
6325 mActiveVoiceInteractionServiceComponent = component;
6326 }
6327 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006328
6329 @Override
6330 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6331 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6332 return;
6333 }
6334 synchronized (mGlobalLock) {
6335 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6336 if (types == null) {
6337 if (uid < 0) {
6338 return;
6339 }
6340 types = new ArrayMap<>();
6341 mAllowAppSwitchUids.put(userId, types);
6342 }
6343 if (uid < 0) {
6344 types.remove(type);
6345 } else {
6346 types.put(type, uid);
6347 }
6348 }
6349 }
6350
6351 @Override
6352 public void onUserStopped(int userId) {
6353 synchronized (mGlobalLock) {
6354 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6355 mAllowAppSwitchUids.remove(userId);
6356 }
6357 }
6358
6359 @Override
6360 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6361 synchronized (mGlobalLock) {
6362 return ActivityTaskManagerService.this.isGetTasksAllowed(
6363 caller, callingPid, callingUid);
6364 }
6365 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006366
Riddle Hsua0536432019-02-16 00:38:59 +08006367 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006368 @Override
6369 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006370 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006371 mProcessNames.put(proc.mName, proc.mUid, proc);
6372 }
6373 }
6374
Riddle Hsua0536432019-02-16 00:38:59 +08006375 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006376 @Override
6377 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006378 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006379 mProcessNames.remove(name, uid);
6380 }
6381 }
6382
Riddle Hsua0536432019-02-16 00:38:59 +08006383 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006384 @Override
6385 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006386 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006387 if (proc == mHomeProcess) {
6388 mHomeProcess = null;
6389 }
6390 if (proc == mPreviousProcess) {
6391 mPreviousProcess = null;
6392 }
6393 }
6394 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006395
Riddle Hsua0536432019-02-16 00:38:59 +08006396 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006397 @Override
6398 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006399 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006400 return mTopProcessState;
6401 }
6402 }
6403
Riddle Hsua0536432019-02-16 00:38:59 +08006404 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006405 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006406 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006407 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006408 return proc == mHeavyWeightProcess;
6409 }
6410 }
6411
Riddle Hsua0536432019-02-16 00:38:59 +08006412 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006413 @Override
6414 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006415 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006416 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6417 }
6418 }
6419
6420 @Override
6421 public void finishHeavyWeightApp() {
6422 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006423 if (mHeavyWeightProcess != null) {
6424 mHeavyWeightProcess.finishActivities();
6425 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006426 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6427 mHeavyWeightProcess);
6428 }
6429 }
6430
Riddle Hsua0536432019-02-16 00:38:59 +08006431 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006432 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006433 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006434 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006435 return isSleepingLocked();
6436 }
6437 }
6438
6439 @Override
6440 public boolean isShuttingDown() {
6441 synchronized (mGlobalLock) {
6442 return mShuttingDown;
6443 }
6444 }
6445
6446 @Override
6447 public boolean shuttingDown(boolean booted, int timeout) {
6448 synchronized (mGlobalLock) {
6449 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006450 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006451 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006452 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006453 return mStackSupervisor.shutdownLocked(timeout);
6454 }
6455 }
6456
6457 @Override
6458 public void enableScreenAfterBoot(boolean booted) {
6459 synchronized (mGlobalLock) {
6460 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6461 SystemClock.uptimeMillis());
6462 mWindowManager.enableScreenAfterBoot();
6463 updateEventDispatchingLocked(booted);
6464 }
6465 }
6466
6467 @Override
6468 public boolean showStrictModeViolationDialog() {
6469 synchronized (mGlobalLock) {
6470 return mShowDialogs && !mSleeping && !mShuttingDown;
6471 }
6472 }
6473
6474 @Override
6475 public void showSystemReadyErrorDialogsIfNeeded() {
6476 synchronized (mGlobalLock) {
6477 try {
6478 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6479 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6480 + " data partition or your device will be unstable.");
6481 mUiHandler.post(() -> {
6482 if (mShowDialogs) {
6483 AlertDialog d = new BaseErrorDialog(mUiContext);
6484 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6485 d.setCancelable(false);
6486 d.setTitle(mUiContext.getText(R.string.android_system_label));
6487 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6488 d.setButton(DialogInterface.BUTTON_POSITIVE,
6489 mUiContext.getText(R.string.ok),
6490 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6491 d.show();
6492 }
6493 });
6494 }
6495 } catch (RemoteException e) {
6496 }
6497
6498 if (!Build.isBuildConsistent()) {
6499 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6500 mUiHandler.post(() -> {
6501 if (mShowDialogs) {
6502 AlertDialog d = new BaseErrorDialog(mUiContext);
6503 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6504 d.setCancelable(false);
6505 d.setTitle(mUiContext.getText(R.string.android_system_label));
6506 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6507 d.setButton(DialogInterface.BUTTON_POSITIVE,
6508 mUiContext.getText(R.string.ok),
6509 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6510 d.show();
6511 }
6512 });
6513 }
6514 }
6515 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006516
6517 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006518 public void onProcessMapped(int pid, WindowProcessController proc) {
6519 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006520 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006521 }
6522 }
6523
6524 @Override
6525 public void onProcessUnMapped(int pid) {
6526 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006527 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006528 }
6529 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006530
6531 @Override
6532 public void onPackageDataCleared(String name) {
6533 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006534 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006535 mAppWarnings.onPackageDataCleared(name);
6536 }
6537 }
6538
6539 @Override
6540 public void onPackageUninstalled(String name) {
6541 synchronized (mGlobalLock) {
6542 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006543 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006544 }
6545 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006546
6547 @Override
6548 public void onPackageAdded(String name, boolean replacing) {
6549 synchronized (mGlobalLock) {
6550 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6551 }
6552 }
6553
6554 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006555 public void onPackageReplaced(ApplicationInfo aInfo) {
6556 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006557 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006558 }
6559 }
6560
6561 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006562 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6563 synchronized (mGlobalLock) {
6564 return compatibilityInfoForPackageLocked(ai);
6565 }
6566 }
6567
Yunfan Chen75157d72018-07-27 14:47:21 +09006568 /**
6569 * Set the corresponding display information for the process global configuration. To be
6570 * called when we need to show IME on a different display.
6571 *
6572 * @param pid The process id associated with the IME window.
6573 * @param displayId The ID of the display showing the IME.
6574 */
6575 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006576 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006577 // Don't update process-level configuration for Multi-Client IME process since other
6578 // IMEs on other displays will also receive this configuration change due to IME
6579 // services use the same application config/context.
6580 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006581
Yunfan Chen75157d72018-07-27 14:47:21 +09006582 if (pid == MY_PID || pid < 0) {
6583 if (DEBUG_CONFIGURATION) {
6584 Slog.w(TAG,
6585 "Trying to update display configuration for system/invalid process.");
6586 }
6587 return;
6588 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006589 synchronized (mGlobalLock) {
6590 final ActivityDisplay activityDisplay =
6591 mRootActivityContainer.getActivityDisplay(displayId);
6592 if (activityDisplay == null) {
6593 // Call might come when display is not yet added or has been removed.
6594 if (DEBUG_CONFIGURATION) {
6595 Slog.w(TAG, "Trying to update display configuration for non-existing "
6596 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006597 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006598 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006599 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006600 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006601 if (process == null) {
6602 if (DEBUG_CONFIGURATION) {
6603 Slog.w(TAG, "Trying to update display configuration for invalid "
6604 + "process, pid=" + pid);
6605 }
6606 return;
6607 }
6608 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6609 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006610 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006611
6612 @Override
6613 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006614 int requestCode, int resultCode, Intent resultData) {
6615 final ActivityRecord r;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006616 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006617 r = ActivityRecord.isInStackLocked(activityToken);
6618 if (r == null || r.getActivityStack() == null) {
6619 return;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006620 }
6621 }
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006622
6623 // Carefully collect grants without holding lock
6624 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
6625 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
6626
6627 synchronized (mGlobalLock) {
6628 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6629 requestCode, resultCode, resultData, resultGrants);
6630 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006631 }
6632
6633 @Override
6634 public void clearPendingResultForActivity(IBinder activityToken,
6635 WeakReference<PendingIntentRecord> pir) {
6636 synchronized (mGlobalLock) {
6637 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6638 if (r != null && r.pendingResults != null) {
6639 r.pendingResults.remove(pir);
6640 }
6641 }
6642 }
6643
6644 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006645 public ActivityTokens getTopActivityForTask(int taskId) {
6646 synchronized (mGlobalLock) {
6647 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6648 if (taskRecord == null) {
6649 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6650 + " Requested task not found");
6651 return null;
6652 }
6653 final ActivityRecord activity = taskRecord.getTopActivity();
6654 if (activity == null) {
6655 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6656 + " Requested activity not found");
6657 return null;
6658 }
6659 if (!activity.attachedToProcess()) {
6660 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6661 + activity);
6662 return null;
6663 }
6664 return new ActivityTokens(activity.appToken, activity.assistToken,
6665 activity.app.getThread());
6666 }
6667 }
6668
6669 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006670 public IIntentSender getIntentSender(int type, String packageName,
6671 int callingUid, int userId, IBinder token, String resultWho,
6672 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6673 Bundle bOptions) {
6674 synchronized (mGlobalLock) {
6675 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6676 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6677 }
6678 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006679
6680 @Override
6681 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6682 synchronized (mGlobalLock) {
6683 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6684 if (r == null) {
6685 return null;
6686 }
6687 if (r.mServiceConnectionsHolder == null) {
6688 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6689 ActivityTaskManagerService.this, r);
6690 }
6691
6692 return r.mServiceConnectionsHolder;
6693 }
6694 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006695
6696 @Override
6697 public Intent getHomeIntent() {
6698 synchronized (mGlobalLock) {
6699 return ActivityTaskManagerService.this.getHomeIntent();
6700 }
6701 }
6702
6703 @Override
6704 public boolean startHomeActivity(int userId, String reason) {
6705 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006706 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006707 }
6708 }
6709
6710 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006711 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006712 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006713 synchronized (mGlobalLock) {
6714 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006715 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006716 }
Chilun8b1f1be2019-03-13 17:14:36 +08006717 }
6718
6719 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006720 public boolean startHomeOnAllDisplays(int userId, String reason) {
6721 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006722 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006723 }
6724 }
6725
Riddle Hsua0536432019-02-16 00:38:59 +08006726 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006727 @Override
6728 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006729 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006730 if (mFactoryTest == FACTORY_TEST_OFF) {
6731 return false;
6732 }
6733 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6734 && wpc.mName.equals(mTopComponent.getPackageName())) {
6735 return true;
6736 }
6737 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6738 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6739 }
6740 }
6741
6742 @Override
6743 public void updateTopComponentForFactoryTest() {
6744 synchronized (mGlobalLock) {
6745 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6746 return;
6747 }
6748 final ResolveInfo ri = mContext.getPackageManager()
6749 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6750 final CharSequence errorMsg;
6751 if (ri != null) {
6752 final ActivityInfo ai = ri.activityInfo;
6753 final ApplicationInfo app = ai.applicationInfo;
6754 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6755 mTopAction = Intent.ACTION_FACTORY_TEST;
6756 mTopData = null;
6757 mTopComponent = new ComponentName(app.packageName, ai.name);
6758 errorMsg = null;
6759 } else {
6760 errorMsg = mContext.getResources().getText(
6761 com.android.internal.R.string.factorytest_not_system);
6762 }
6763 } else {
6764 errorMsg = mContext.getResources().getText(
6765 com.android.internal.R.string.factorytest_no_action);
6766 }
6767 if (errorMsg == null) {
6768 return;
6769 }
6770
6771 mTopAction = null;
6772 mTopData = null;
6773 mTopComponent = null;
6774 mUiHandler.post(() -> {
6775 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6776 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006777 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006778 });
6779 }
6780 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781
Riddle Hsua0536432019-02-16 00:38:59 +08006782 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 @Override
6784 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6785 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006786 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006788 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789
6790 wpc.clearRecentTasks();
6791 wpc.clearActivities();
6792
6793 if (wpc.isInstrumenting()) {
6794 finishInstrumentationCallback.run();
6795 }
6796
Jorim Jaggid0752812018-10-16 16:07:20 +02006797 if (!restarting && hasVisibleActivities) {
6798 mWindowManager.deferSurfaceLayout();
6799 try {
6800 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6801 // If there was nothing to resume, and we are not already restarting
6802 // this process, but there is a visible activity that is hosted by the
6803 // process...then make sure all visible activities are running, taking
6804 // care of restarting this process.
6805 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6806 !PRESERVE_WINDOWS);
6807 }
6808 } finally {
6809 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006811 }
6812 }
6813 }
6814
6815 @Override
6816 public void closeSystemDialogs(String reason) {
6817 enforceNotIsolatedCaller("closeSystemDialogs");
6818
6819 final int pid = Binder.getCallingPid();
6820 final int uid = Binder.getCallingUid();
6821 final long origId = Binder.clearCallingIdentity();
6822 try {
6823 synchronized (mGlobalLock) {
6824 // Only allow this from foreground processes, so that background
6825 // applications can't abuse it to prevent system UI from being shown.
6826 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006827 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006828 if (!proc.isPerceptible()) {
6829 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6830 + " from background process " + proc);
6831 return;
6832 }
6833 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 mWindowManager.closeSystemDialogs(reason);
6835
Wale Ogunwaled32da472018-11-16 07:19:28 -08006836 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006838 // Call into AM outside the synchronized block.
6839 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 } finally {
6841 Binder.restoreCallingIdentity(origId);
6842 }
6843 }
6844
6845 @Override
6846 public void cleanupDisabledPackageComponents(
6847 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6848 synchronized (mGlobalLock) {
6849 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006850 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006852 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 mStackSupervisor.scheduleIdleLocked();
6854 }
6855
6856 // Clean-up disabled tasks
6857 getRecentTasks().cleanupDisabledPackageTasksLocked(
6858 packageName, disabledClasses, userId);
6859 }
6860 }
6861
6862 @Override
6863 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6864 int userId) {
6865 synchronized (mGlobalLock) {
6866
6867 boolean didSomething =
6868 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006869 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 null, doit, evenPersistent, userId);
6871 return didSomething;
6872 }
6873 }
6874
6875 @Override
6876 public void resumeTopActivities(boolean scheduleIdle) {
6877 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006878 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 if (scheduleIdle) {
6880 mStackSupervisor.scheduleIdleLocked();
6881 }
6882 }
6883 }
6884
Riddle Hsua0536432019-02-16 00:38:59 +08006885 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006886 @Override
6887 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006888 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6890 }
6891 }
6892
Riddle Hsua0536432019-02-16 00:38:59 +08006893 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 @Override
6895 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006896 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006897 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 }
6899 }
6900
6901 @Override
6902 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6903 try {
6904 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6905 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6906 }
6907 } catch (RemoteException ex) {
6908 throw new SecurityException("Fail to check is caller a privileged app", ex);
6909 }
6910
6911 synchronized (mGlobalLock) {
6912 final long ident = Binder.clearCallingIdentity();
6913 try {
6914 if (mAmInternal.shouldConfirmCredentials(userId)) {
6915 if (mKeyguardController.isKeyguardLocked()) {
6916 // Showing launcher to avoid user entering credential twice.
6917 startHomeActivity(currentUserId, "notifyLockedProfile");
6918 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006919 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 }
6921 } finally {
6922 Binder.restoreCallingIdentity(ident);
6923 }
6924 }
6925 }
6926
6927 @Override
6928 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6929 mAmInternal.enforceCallingPermission(
6930 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6931
6932 synchronized (mGlobalLock) {
6933 final long ident = Binder.clearCallingIdentity();
6934 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006935 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6936 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6939 UserHandle.CURRENT);
6940 } finally {
6941 Binder.restoreCallingIdentity(ident);
6942 }
6943 }
6944 }
6945
6946 @Override
6947 public void writeActivitiesToProto(ProtoOutputStream proto) {
6948 synchronized (mGlobalLock) {
6949 // The output proto of "activity --proto activities"
6950 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006951 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006952 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6953 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 }
6955 }
6956
6957 @Override
6958 public void saveANRState(String reason) {
6959 synchronized (mGlobalLock) {
6960 final StringWriter sw = new StringWriter();
6961 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6962 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6963 if (reason != null) {
6964 pw.println(" Reason: " + reason);
6965 }
6966 pw.println();
6967 getActivityStartController().dump(pw, " ", null);
6968 pw.println();
6969 pw.println("-------------------------------------------------------------------------------");
6970 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6971 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6972 "" /* header */);
6973 pw.println();
6974 pw.close();
6975
6976 mLastANRState = sw.toString();
6977 }
6978 }
6979
6980 @Override
6981 public void clearSavedANRState() {
6982 synchronized (mGlobalLock) {
6983 mLastANRState = null;
6984 }
6985 }
6986
6987 @Override
6988 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6989 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6990 synchronized (mGlobalLock) {
6991 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6992 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6993 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6994 dumpLastANRLocked(pw);
6995 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6996 dumpLastANRTracesLocked(pw);
6997 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6998 dumpActivityStarterLocked(pw, dumpPackage);
6999 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7000 dumpActivityContainersLocked(pw);
7001 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7002 if (getRecentTasks() != null) {
7003 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7004 }
7005 }
7006 }
7007 }
7008
7009 @Override
7010 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7011 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7012 int wakefulness) {
7013 synchronized (mGlobalLock) {
7014 if (mHomeProcess != null && (dumpPackage == null
7015 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7016 if (needSep) {
7017 pw.println();
7018 needSep = false;
7019 }
7020 pw.println(" mHomeProcess: " + mHomeProcess);
7021 }
7022 if (mPreviousProcess != null && (dumpPackage == null
7023 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7024 if (needSep) {
7025 pw.println();
7026 needSep = false;
7027 }
7028 pw.println(" mPreviousProcess: " + mPreviousProcess);
7029 }
7030 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7031 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7032 StringBuilder sb = new StringBuilder(128);
7033 sb.append(" mPreviousProcessVisibleTime: ");
7034 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7035 pw.println(sb);
7036 }
7037 if (mHeavyWeightProcess != null && (dumpPackage == null
7038 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7039 if (needSep) {
7040 pw.println();
7041 needSep = false;
7042 }
7043 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7044 }
7045 if (dumpPackage == null) {
7046 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007047 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 }
7049 if (dumpAll) {
7050 if (dumpPackage == null) {
7051 pw.println(" mConfigWillChange: "
7052 + getTopDisplayFocusedStack().mConfigWillChange);
7053 }
7054 if (mCompatModePackages.getPackages().size() > 0) {
7055 boolean printed = false;
7056 for (Map.Entry<String, Integer> entry
7057 : mCompatModePackages.getPackages().entrySet()) {
7058 String pkg = entry.getKey();
7059 int mode = entry.getValue();
7060 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7061 continue;
7062 }
7063 if (!printed) {
7064 pw.println(" mScreenCompatPackages:");
7065 printed = true;
7066 }
7067 pw.println(" " + pkg + ": " + mode);
7068 }
7069 }
7070 }
7071
7072 if (dumpPackage == null) {
7073 pw.println(" mWakefulness="
7074 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007075 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007076 if (mRunningVoice != null) {
7077 pw.println(" mRunningVoice=" + mRunningVoice);
7078 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7079 }
7080 pw.println(" mSleeping=" + mSleeping);
7081 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7082 pw.println(" mVrController=" + mVrController);
7083 }
7084 if (mCurAppTimeTracker != null) {
7085 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7086 }
7087 if (mAllowAppSwitchUids.size() > 0) {
7088 boolean printed = false;
7089 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7090 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7091 for (int j = 0; j < types.size(); j++) {
7092 if (dumpPackage == null ||
7093 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7094 if (needSep) {
7095 pw.println();
7096 needSep = false;
7097 }
7098 if (!printed) {
7099 pw.println(" mAllowAppSwitchUids:");
7100 printed = true;
7101 }
7102 pw.print(" User ");
7103 pw.print(mAllowAppSwitchUids.keyAt(i));
7104 pw.print(": Type ");
7105 pw.print(types.keyAt(j));
7106 pw.print(" = ");
7107 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7108 pw.println();
7109 }
7110 }
7111 }
7112 }
7113 if (dumpPackage == null) {
7114 if (mController != null) {
7115 pw.println(" mController=" + mController
7116 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7117 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007118 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7119 pw.println(" mLaunchingActivityWakeLock="
7120 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122
7123 return needSep;
7124 }
7125 }
7126
7127 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007128 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7129 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007130 synchronized (mGlobalLock) {
7131 if (dumpPackage == null) {
7132 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7133 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007134 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7135 if (mRunningVoice != null) {
7136 final long vrToken = proto.start(
7137 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7138 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7139 mRunningVoice.toString());
7140 mVoiceWakeLock.writeToProto(
7141 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7142 proto.end(vrToken);
7143 }
7144 mVrController.writeToProto(proto,
7145 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007146 if (mController != null) {
7147 final long token = proto.start(CONTROLLER);
7148 proto.write(CONTROLLER, mController.toString());
7149 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7150 proto.end(token);
7151 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007152 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7153 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7154 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 }
7156
7157 if (mHomeProcess != null && (dumpPackage == null
7158 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007159 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007160 }
7161
7162 if (mPreviousProcess != null && (dumpPackage == null
7163 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007164 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7166 }
7167
7168 if (mHeavyWeightProcess != null && (dumpPackage == null
7169 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007170 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007171 }
7172
7173 for (Map.Entry<String, Integer> entry
7174 : mCompatModePackages.getPackages().entrySet()) {
7175 String pkg = entry.getKey();
7176 int mode = entry.getValue();
7177 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7178 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7179 proto.write(PACKAGE, pkg);
7180 proto.write(MODE, mode);
7181 proto.end(compatToken);
7182 }
7183 }
7184
7185 if (mCurAppTimeTracker != null) {
7186 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7187 }
7188
7189 }
7190 }
7191
7192 @Override
7193 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7194 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7195 boolean dumpFocusedStackOnly) {
7196 synchronized (mGlobalLock) {
7197 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7198 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7199 }
7200 }
7201
7202 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007203 public void dumpForOom(PrintWriter pw) {
7204 synchronized (mGlobalLock) {
7205 pw.println(" mHomeProcess: " + mHomeProcess);
7206 pw.println(" mPreviousProcess: " + mPreviousProcess);
7207 if (mHeavyWeightProcess != null) {
7208 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7209 }
7210 }
7211 }
7212
7213 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007214 public boolean canGcNow() {
7215 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007216 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 }
7218 }
7219
Riddle Hsua0536432019-02-16 00:38:59 +08007220 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 @Override
7222 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007223 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007224 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007225 return top != null ? top.app : null;
7226 }
7227 }
7228
Riddle Hsua0536432019-02-16 00:38:59 +08007229 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007230 @Override
7231 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007232 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007233 if (mRootActivityContainer != null) {
7234 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007235 }
7236 }
7237 }
7238
7239 @Override
7240 public void scheduleDestroyAllActivities(String reason) {
7241 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007242 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007243 }
7244 }
7245
7246 @Override
7247 public void removeUser(int userId) {
7248 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007249 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007250 }
7251 }
7252
7253 @Override
7254 public boolean switchUser(int userId, UserState userState) {
7255 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007256 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 }
7258 }
7259
7260 @Override
7261 public void onHandleAppCrash(WindowProcessController wpc) {
7262 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007263 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007264 }
7265 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007266
7267 @Override
7268 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7269 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007270 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007271 }
7272 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007273
Riddle Hsua0536432019-02-16 00:38:59 +08007274 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007275 @Override
7276 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007277 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007278 }
7279
Riddle Hsua0536432019-02-16 00:38:59 +08007280 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007281 @Override
7282 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007283 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007284 }
7285
Riddle Hsua0536432019-02-16 00:38:59 +08007286 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007287 @Override
7288 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007289 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007290 }
7291
Riddle Hsua0536432019-02-16 00:38:59 +08007292 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007293 @Override
7294 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007295 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007296 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007297
7298 @Override
7299 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007300 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007301 mPendingTempWhitelist.put(uid, tag);
7302 }
7303 }
7304
7305 @Override
7306 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007308 mPendingTempWhitelist.remove(uid);
7309 }
7310 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007311
7312 @Override
7313 public boolean handleAppCrashInActivityController(String processName, int pid,
7314 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7315 Runnable killCrashingAppCallback) {
7316 synchronized (mGlobalLock) {
7317 if (mController == null) {
7318 return false;
7319 }
7320
7321 try {
7322 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7323 stackTrace)) {
7324 killCrashingAppCallback.run();
7325 return true;
7326 }
7327 } catch (RemoteException e) {
7328 mController = null;
7329 Watchdog.getInstance().setActivityController(null);
7330 }
7331 return false;
7332 }
7333 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007334
7335 @Override
7336 public void removeRecentTasksByPackageName(String packageName, int userId) {
7337 synchronized (mGlobalLock) {
7338 mRecentTasks.removeTasksByPackageName(packageName, userId);
7339 }
7340 }
7341
7342 @Override
7343 public void cleanupRecentTasksForUser(int userId) {
7344 synchronized (mGlobalLock) {
7345 mRecentTasks.cleanupLocked(userId);
7346 }
7347 }
7348
7349 @Override
7350 public void loadRecentTasksForUser(int userId) {
7351 synchronized (mGlobalLock) {
7352 mRecentTasks.loadUserRecentsLocked(userId);
7353 }
7354 }
7355
7356 @Override
7357 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7358 synchronized (mGlobalLock) {
7359 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7360 }
7361 }
7362
7363 @Override
7364 public void flushRecentTasks() {
7365 mRecentTasks.flush();
7366 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007367
7368 @Override
7369 public WindowProcessController getHomeProcess() {
7370 synchronized (mGlobalLock) {
7371 return mHomeProcess;
7372 }
7373 }
7374
7375 @Override
7376 public WindowProcessController getPreviousProcess() {
7377 synchronized (mGlobalLock) {
7378 return mPreviousProcess;
7379 }
7380 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007381
7382 @Override
7383 public void clearLockedTasks(String reason) {
7384 synchronized (mGlobalLock) {
7385 getLockTaskController().clearLockedTasks(reason);
7386 }
7387 }
7388
7389 @Override
7390 public void updateUserConfiguration() {
7391 synchronized (mGlobalLock) {
7392 final Configuration configuration = new Configuration(getGlobalConfiguration());
7393 final int currentUserId = mAmInternal.getCurrentUserId();
7394 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7395 configuration, currentUserId, Settings.System.canWrite(mContext));
7396 updateConfigurationLocked(configuration, null /* starting */,
7397 false /* initLocale */, false /* persistent */, currentUserId,
7398 false /* deferResume */);
7399 }
7400 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007401
7402 @Override
7403 public boolean canShowErrorDialogs() {
7404 synchronized (mGlobalLock) {
7405 return mShowDialogs && !mSleeping && !mShuttingDown
7406 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7407 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7408 mAmInternal.getCurrentUserId())
7409 && !(UserManager.isDeviceInDemoMode(mContext)
7410 && mAmInternal.getCurrentUser().isDemo());
7411 }
7412 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007413
7414 @Override
7415 public void setProfileApp(String profileApp) {
7416 synchronized (mGlobalLock) {
7417 mProfileApp = profileApp;
7418 }
7419 }
7420
7421 @Override
7422 public void setProfileProc(WindowProcessController wpc) {
7423 synchronized (mGlobalLock) {
7424 mProfileProc = wpc;
7425 }
7426 }
7427
7428 @Override
7429 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7430 synchronized (mGlobalLock) {
7431 mProfilerInfo = profilerInfo;
7432 }
7433 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007434
7435 @Override
7436 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7437 synchronized (mGlobalLock) {
7438 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7439 }
7440 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007441
7442 @Override
7443 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7444 synchronized (mGlobalLock) {
7445 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7446 }
7447 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007448
7449 @Override
7450 public boolean isUidForeground(int uid) {
7451 synchronized (mGlobalLock) {
7452 return ActivityTaskManagerService.this.isUidForeground(uid);
7453 }
7454 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007455
7456 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007457 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007458 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007459 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007460 }
7461 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007462
7463 @Override
7464 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007465 // Translate package names into UIDs
7466 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007467 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007468 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7469 if (uid >= 0) {
7470 result.add(uid);
7471 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007472 }
7473 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007474 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007475 }
7476 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007477 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007478}