blob: f8bfacbefc2c60c538e31f7132822f2117de780d [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
512 IActivityController mController = null;
513 boolean mControllerIsAMonkey = false;
514
Wale Ogunwale214f3482018-10-04 11:00:47 -0700515 final int mFactoryTest;
516
517 /** Used to control how we initialize the service. */
518 ComponentName mTopComponent;
519 String mTopAction = Intent.ACTION_MAIN;
520 String mTopData;
521
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800522 /** Profiling app information. */
523 String mProfileApp = null;
524 WindowProcessController mProfileProc = null;
525 ProfilerInfo mProfilerInfo = null;
526
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700528 * Dump of the activity state at the time of the last ANR. Cleared after
529 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
530 */
531 String mLastANRState;
532
533 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 * Used to retain an update lock when the foreground activity is in
535 * immersive mode.
536 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700537 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538
539 /**
540 * Packages that are being allowed to perform unrestricted app switches. Mapping is
541 * User -> Type -> uid.
542 */
543 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
544
545 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700546 private int mThumbnailWidth;
547 private int mThumbnailHeight;
548 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700549
550 /**
551 * Flag that indicates if multi-window is enabled.
552 *
553 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
554 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
555 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
556 * At least one of the forms of multi-window must be enabled in order for this flag to be
557 * initialized to 'true'.
558 *
559 * @see #mSupportsSplitScreenMultiWindow
560 * @see #mSupportsFreeformWindowManagement
561 * @see #mSupportsPictureInPicture
562 * @see #mSupportsMultiDisplay
563 */
564 boolean mSupportsMultiWindow;
565 boolean mSupportsSplitScreenMultiWindow;
566 boolean mSupportsFreeformWindowManagement;
567 boolean mSupportsPictureInPicture;
568 boolean mSupportsMultiDisplay;
569 boolean mForceResizableActivities;
570
571 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
572
573 // VR Vr2d Display Id.
574 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700575
Wale Ogunwalef6733932018-06-27 05:14:34 -0700576 /**
577 * Set while we are wanting to sleep, to prevent any
578 * activities from being started/resumed.
579 *
580 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
581 *
582 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
583 * while in the sleep state until there is a pending transition out of sleep, in which case
584 * mSleeping is set to false, and remains false while awake.
585 *
586 * Whether mSleeping can quickly toggled between true/false without the device actually
587 * display changing states is undefined.
588 */
589 private boolean mSleeping = false;
590
591 /**
592 * The process state used for processes that are running the top activities.
593 * This changes between TOP and TOP_SLEEPING to following mSleeping.
594 */
595 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
596
597 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
598 // automatically. Important for devices without direct input devices.
599 private boolean mShowDialogs = true;
600
601 /** Set if we are shutting down the system, similar to sleeping. */
602 boolean mShuttingDown = false;
603
604 /**
605 * We want to hold a wake lock while running a voice interaction session, since
606 * this may happen with the screen off and we need to keep the CPU running to
607 * be able to continue to interact with the user.
608 */
609 PowerManager.WakeLock mVoiceWakeLock;
610
611 /**
612 * Set while we are running a voice interaction. This overrides sleeping while it is active.
613 */
614 IVoiceInteractionSession mRunningVoice;
615
616 /**
617 * The last resumed activity. This is identical to the current resumed activity most
618 * of the time but could be different when we're pausing one activity before we resume
619 * another activity.
620 */
621 ActivityRecord mLastResumedActivity;
622
623 /**
624 * The activity that is currently being traced as the active resumed activity.
625 *
626 * @see #updateResumedAppTrace
627 */
628 private @Nullable ActivityRecord mTracedResumedActivity;
629
630 /** If non-null, we are tracking the time the user spends in the currently focused app. */
631 AppTimeTracker mCurAppTimeTracker;
632
Wale Ogunwale008163e2018-07-23 23:11:08 -0700633 private AppWarnings mAppWarnings;
634
Wale Ogunwale53783742018-09-16 10:21:51 -0700635 /**
636 * Packages that the user has asked to have run in screen size
637 * compatibility mode instead of filling the screen.
638 */
639 CompatModePackages mCompatModePackages;
640
Wale Ogunwalef6733932018-06-27 05:14:34 -0700641 private FontScaleSettingObserver mFontScaleSettingObserver;
642
Ricky Wai96f5c352019-04-10 18:40:17 +0100643 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000644
Wale Ogunwalef6733932018-06-27 05:14:34 -0700645 private final class FontScaleSettingObserver extends ContentObserver {
646 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
647 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
648
649 public FontScaleSettingObserver() {
650 super(mH);
651 final ContentResolver resolver = mContext.getContentResolver();
652 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
653 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
654 UserHandle.USER_ALL);
655 }
656
657 @Override
658 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
659 if (mFontScaleUri.equals(uri)) {
660 updateFontScaleIfNeeded(userId);
661 } else if (mHideErrorDialogsUri.equals(uri)) {
662 synchronized (mGlobalLock) {
663 updateShouldShowDialogsLocked(getGlobalConfiguration());
664 }
665 }
666 }
667 }
668
Riddle Hsua0536432019-02-16 00:38:59 +0800669 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
670 @Target(ElementType.METHOD)
671 @Retention(RetentionPolicy.SOURCE)
672 @interface HotPath {
673 int NONE = 0;
674 int OOM_ADJUSTMENT = 1;
675 int LRU_UPDATE = 2;
676 int PROCESS_CHANGE = 3;
677 int caller() default NONE;
678 }
679
Charles Chen8d98dd22018-12-26 17:36:54 +0800680 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
681 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700682 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700683 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700684 mSystemThread = ActivityThread.currentActivityThread();
685 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700686 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800687 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700688 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700689 }
690
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700691 public void onSystemReady() {
692 synchronized (mGlobalLock) {
693 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
694 PackageManager.FEATURE_CANT_SAVE_STATE);
695 mAssistUtils = new AssistUtils(mContext);
696 mVrController.onSystemReady();
697 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700698 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700699 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700700 }
701
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700702 public void onInitPowerManagement() {
703 synchronized (mGlobalLock) {
704 mStackSupervisor.initPowerManagement();
705 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
706 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
707 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
708 mVoiceWakeLock.setReferenceCounted(false);
709 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700710 }
711
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700712 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700713 mFontScaleSettingObserver = new FontScaleSettingObserver();
714 }
715
Wale Ogunwale59507092018-10-29 09:00:30 -0700716 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700717 final boolean freeformWindowManagement =
718 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
719 || Settings.Global.getInt(
720 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
721
722 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
723 final boolean supportsPictureInPicture = supportsMultiWindow &&
724 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
725 final boolean supportsSplitScreenMultiWindow =
726 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
727 final boolean supportsMultiDisplay = mContext.getPackageManager()
728 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
730 final boolean forceResizable = Settings.Global.getInt(
731 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700732 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700733
734 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900735 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700736
737 final Configuration configuration = new Configuration();
738 Settings.System.getConfiguration(resolver, configuration);
739 if (forceRtl) {
740 // This will take care of setting the correct layout direction flags
741 configuration.setLayoutDirection(configuration.locale);
742 }
743
744 synchronized (mGlobalLock) {
745 mForceResizableActivities = forceResizable;
746 final boolean multiWindowFormEnabled = freeformWindowManagement
747 || supportsSplitScreenMultiWindow
748 || supportsPictureInPicture
749 || supportsMultiDisplay;
750 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
751 mSupportsMultiWindow = true;
752 mSupportsFreeformWindowManagement = freeformWindowManagement;
753 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
754 mSupportsPictureInPicture = supportsPictureInPicture;
755 mSupportsMultiDisplay = supportsMultiDisplay;
756 } else {
757 mSupportsMultiWindow = false;
758 mSupportsFreeformWindowManagement = false;
759 mSupportsSplitScreenMultiWindow = false;
760 mSupportsPictureInPicture = false;
761 mSupportsMultiDisplay = false;
762 }
763 mWindowManager.setForceResizableTasks(mForceResizableActivities);
764 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700765 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
766 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700767 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 // This happens before any activities are started, so we can change global configuration
769 // in-place.
770 updateConfigurationLocked(configuration, null, true);
771 final Configuration globalConfig = getGlobalConfiguration();
772 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
773
774 // Load resources only after the current configuration has been set.
775 final Resources res = mContext.getResources();
776 mThumbnailWidth = res.getDimensionPixelSize(
777 com.android.internal.R.dimen.thumbnail_width);
778 mThumbnailHeight = res.getDimensionPixelSize(
779 com.android.internal.R.dimen.thumbnail_height);
780
781 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
782 mFullscreenThumbnailScale = (float) res
783 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
784 (float) globalConfig.screenWidthDp;
785 } else {
786 mFullscreenThumbnailScale = res.getFraction(
787 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
788 }
789 }
790 }
791
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800792 public WindowManagerGlobalLock getGlobalLock() {
793 return mGlobalLock;
794 }
795
Yunfan Chen585f2932019-01-29 16:04:45 +0900796 /** For test purpose only. */
797 @VisibleForTesting
798 public ActivityTaskManagerInternal getAtmInternal() {
799 return mInternal;
800 }
801
Riddle Hsud93a6c42018-11-29 21:50:06 +0800802 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
803 Looper looper) {
804 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700805 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700806 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700807 final File systemDir = SystemServiceManager.ensureSystemDir();
808 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
809 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700810 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700811
812 mTempConfig.setToDefaults();
813 mTempConfig.setLocales(LocaleList.getDefault());
814 mConfigurationSeq = mTempConfig.seq = 1;
815 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800816 mRootActivityContainer = new RootActivityContainer(this);
817 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700819 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700821 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700822 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700823 mRecentTasks = createRecentTasks();
824 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700826 mKeyguardController = mStackSupervisor.getKeyguardController();
827 }
828
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700829 public void onActivityManagerInternalAdded() {
830 synchronized (mGlobalLock) {
831 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
832 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
833 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700834 }
835
Yunfan Chen75157d72018-07-27 14:47:21 +0900836 int increaseConfigurationSeqLocked() {
837 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
838 return mConfigurationSeq;
839 }
840
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700841 protected ActivityStackSupervisor createStackSupervisor() {
842 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
843 supervisor.initialize();
844 return supervisor;
845 }
846
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700847 public void setWindowManager(WindowManagerService wm) {
848 synchronized (mGlobalLock) {
849 mWindowManager = wm;
850 mLockTaskController.setWindowManager(wm);
851 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800852 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700853 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700854 }
855
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700856 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
857 synchronized (mGlobalLock) {
858 mUsageStatsInternal = usageStatsManager;
859 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700860 }
861
Wale Ogunwalef6733932018-06-27 05:14:34 -0700862 UserManagerService getUserManager() {
863 if (mUserManager == null) {
864 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
865 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
866 }
867 return mUserManager;
868 }
869
870 AppOpsService getAppOpsService() {
871 if (mAppOpsService == null) {
872 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
873 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
874 }
875 return mAppOpsService;
876 }
877
878 boolean hasUserRestriction(String restriction, int userId) {
879 return getUserManager().hasUserRestriction(restriction, userId);
880 }
881
Michal Karpinski15486842019-04-25 17:33:42 +0100882 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
883 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
884 callingUid, callingPackage);
885 if (mode == AppOpsManager.MODE_DEFAULT) {
886 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
887 == PERMISSION_GRANTED;
888 }
889 return mode == AppOpsManager.MODE_ALLOWED;
890 }
891
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700892 protected RecentTasks createRecentTasks() {
893 return new RecentTasks(this, mStackSupervisor);
894 }
895
896 RecentTasks getRecentTasks() {
897 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700898 }
899
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700900 ClientLifecycleManager getLifecycleManager() {
901 return mLifecycleManager;
902 }
903
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700904 ActivityStartController getActivityStartController() {
905 return mActivityStartController;
906 }
907
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700908 TaskChangeNotificationController getTaskChangeNotificationController() {
909 return mTaskChangeNotificationController;
910 }
911
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700912 LockTaskController getLockTaskController() {
913 return mLockTaskController;
914 }
915
Yunfan Chen75157d72018-07-27 14:47:21 +0900916 /**
917 * Return the global configuration used by the process corresponding to the input pid. This is
918 * usually the global configuration with some overrides specific to that process.
919 */
920 Configuration getGlobalConfigurationForCallingPid() {
921 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800922 return getGlobalConfigurationForPid(pid);
923 }
924
925 /**
926 * Return the global configuration used by the process corresponding to the given pid.
927 */
928 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 if (pid == MY_PID || pid < 0) {
930 return getGlobalConfiguration();
931 }
932 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100933 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900934 return app != null ? app.getConfiguration() : getGlobalConfiguration();
935 }
936 }
937
938 /**
939 * Return the device configuration info used by the process corresponding to the input pid.
940 * The value is consistent with the global configuration for the process.
941 */
942 @Override
943 public ConfigurationInfo getDeviceConfigurationInfo() {
944 ConfigurationInfo config = new ConfigurationInfo();
945 synchronized (mGlobalLock) {
946 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
947 config.reqTouchScreen = globalConfig.touchscreen;
948 config.reqKeyboardType = globalConfig.keyboard;
949 config.reqNavigation = globalConfig.navigation;
950 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
951 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
952 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
953 }
954 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
955 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
956 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
957 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700958 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900959 }
960 return config;
961 }
962
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700963 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700964 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700965 }
966
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700967 public static final class Lifecycle extends SystemService {
968 private final ActivityTaskManagerService mService;
969
970 public Lifecycle(Context context) {
971 super(context);
972 mService = new ActivityTaskManagerService(context);
973 }
974
975 @Override
976 public void onStart() {
977 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700978 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700979 }
980
Garfield Tan891146c2018-10-09 12:14:00 -0700981 @Override
982 public void onUnlockUser(int userId) {
983 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800984 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700985 }
986 }
987
988 @Override
989 public void onCleanupUser(int userId) {
990 synchronized (mService.getGlobalLock()) {
991 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
992 }
993 }
994
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700995 public ActivityTaskManagerService getService() {
996 return mService;
997 }
998 }
999
1000 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001001 public final int startActivity(IApplicationThread caller, String callingPackage,
1002 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1003 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1004 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1005 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1006 UserHandle.getCallingUserId());
1007 }
1008
1009 @Override
1010 public final int startActivities(IApplicationThread caller, String callingPackage,
1011 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1012 int userId) {
1013 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001014 enforceNotIsolatedCaller(reason);
1015 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001017 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1018 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1019 reason, null /* originatingPendingIntent */,
1020 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 }
1022
1023 @Override
1024 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1025 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1026 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1027 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1028 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1029 true /*validateIncomingUser*/);
1030 }
1031
1032 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1033 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1034 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1035 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001036 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001038 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1040
1041 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001042 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 .setCaller(caller)
1044 .setCallingPackage(callingPackage)
1045 .setResolvedType(resolvedType)
1046 .setResultTo(resultTo)
1047 .setResultWho(resultWho)
1048 .setRequestCode(requestCode)
1049 .setStartFlags(startFlags)
1050 .setProfilerInfo(profilerInfo)
1051 .setActivityOptions(bOptions)
1052 .setMayWait(userId)
1053 .execute();
1054
1055 }
1056
1057 @Override
1058 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1059 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001060 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1061 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 // Refuse possible leaked file descriptors
1063 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1064 throw new IllegalArgumentException("File descriptors passed in Intent");
1065 }
1066
1067 if (!(target instanceof PendingIntentRecord)) {
1068 throw new IllegalArgumentException("Bad PendingIntent object");
1069 }
1070
1071 PendingIntentRecord pir = (PendingIntentRecord)target;
1072
1073 synchronized (mGlobalLock) {
1074 // If this is coming from the currently resumed activity, it is
1075 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001076 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001077 if (stack.mResumedActivity != null &&
1078 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001079 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 }
1081 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 }
1085
1086 @Override
1087 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1088 Bundle bOptions) {
1089 // Refuse possible leaked file descriptors
1090 if (intent != null && intent.hasFileDescriptors()) {
1091 throw new IllegalArgumentException("File descriptors passed in Intent");
1092 }
1093 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1094
1095 synchronized (mGlobalLock) {
1096 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1097 if (r == null) {
1098 SafeActivityOptions.abort(options);
1099 return false;
1100 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001101 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001102 // The caller is not running... d'oh!
1103 SafeActivityOptions.abort(options);
1104 return false;
1105 }
1106 intent = new Intent(intent);
1107 // The caller is not allowed to change the data.
1108 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1109 // And we are resetting to find the next component...
1110 intent.setComponent(null);
1111
1112 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1113
1114 ActivityInfo aInfo = null;
1115 try {
1116 List<ResolveInfo> resolves =
1117 AppGlobals.getPackageManager().queryIntentActivities(
1118 intent, r.resolvedType,
1119 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1120 UserHandle.getCallingUserId()).getList();
1121
1122 // Look for the original activity in the list...
1123 final int N = resolves != null ? resolves.size() : 0;
1124 for (int i=0; i<N; i++) {
1125 ResolveInfo rInfo = resolves.get(i);
1126 if (rInfo.activityInfo.packageName.equals(r.packageName)
1127 && rInfo.activityInfo.name.equals(r.info.name)) {
1128 // We found the current one... the next matching is
1129 // after it.
1130 i++;
1131 if (i<N) {
1132 aInfo = resolves.get(i).activityInfo;
1133 }
1134 if (debug) {
1135 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1136 + "/" + r.info.name);
1137 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1138 ? "null" : aInfo.packageName + "/" + aInfo.name));
1139 }
1140 break;
1141 }
1142 }
1143 } catch (RemoteException e) {
1144 }
1145
1146 if (aInfo == null) {
1147 // Nobody who is next!
1148 SafeActivityOptions.abort(options);
1149 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1150 return false;
1151 }
1152
1153 intent.setComponent(new ComponentName(
1154 aInfo.applicationInfo.packageName, aInfo.name));
1155 intent.setFlags(intent.getFlags()&~(
1156 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1157 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1158 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1159 FLAG_ACTIVITY_NEW_TASK));
1160
1161 // Okay now we need to start the new activity, replacing the currently running activity.
1162 // This is a little tricky because we want to start the new one as if the current one is
1163 // finished, but not finish the current one first so that there is no flicker.
1164 // And thus...
1165 final boolean wasFinishing = r.finishing;
1166 r.finishing = true;
1167
1168 // Propagate reply information over to the new activity.
1169 final ActivityRecord resultTo = r.resultTo;
1170 final String resultWho = r.resultWho;
1171 final int requestCode = r.requestCode;
1172 r.resultTo = null;
1173 if (resultTo != null) {
1174 resultTo.removeResultsLocked(r, resultWho, requestCode);
1175 }
1176
1177 final long origId = Binder.clearCallingIdentity();
1178 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001179 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001180 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001181 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 .setResolvedType(r.resolvedType)
1183 .setActivityInfo(aInfo)
1184 .setResultTo(resultTo != null ? resultTo.appToken : null)
1185 .setResultWho(resultWho)
1186 .setRequestCode(requestCode)
1187 .setCallingPid(-1)
1188 .setCallingUid(r.launchedFromUid)
1189 .setCallingPackage(r.launchedFromPackage)
1190 .setRealCallingPid(-1)
1191 .setRealCallingUid(r.launchedFromUid)
1192 .setActivityOptions(options)
1193 .execute();
1194 Binder.restoreCallingIdentity(origId);
1195
1196 r.finishing = wasFinishing;
1197 if (res != ActivityManager.START_SUCCESS) {
1198 return false;
1199 }
1200 return true;
1201 }
1202 }
1203
1204 @Override
1205 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1206 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1207 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1208 final WaitResult res = new WaitResult();
1209 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001210 enforceNotIsolatedCaller("startActivityAndWait");
1211 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1212 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001213 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001214 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 .setCaller(caller)
1216 .setCallingPackage(callingPackage)
1217 .setResolvedType(resolvedType)
1218 .setResultTo(resultTo)
1219 .setResultWho(resultWho)
1220 .setRequestCode(requestCode)
1221 .setStartFlags(startFlags)
1222 .setActivityOptions(bOptions)
1223 .setMayWait(userId)
1224 .setProfilerInfo(profilerInfo)
1225 .setWaitResult(res)
1226 .execute();
1227 }
1228 return res;
1229 }
1230
1231 @Override
1232 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1233 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1234 int startFlags, Configuration config, Bundle bOptions, int userId) {
1235 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001236 enforceNotIsolatedCaller("startActivityWithConfig");
1237 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1238 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001240 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001241 .setCaller(caller)
1242 .setCallingPackage(callingPackage)
1243 .setResolvedType(resolvedType)
1244 .setResultTo(resultTo)
1245 .setResultWho(resultWho)
1246 .setRequestCode(requestCode)
1247 .setStartFlags(startFlags)
1248 .setGlobalConfiguration(config)
1249 .setActivityOptions(bOptions)
1250 .setMayWait(userId)
1251 .execute();
1252 }
1253 }
1254
Alison Cichowlas3e340502018-08-07 17:15:01 -04001255
1256 @Override
1257 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1258 int callingUid = Binder.getCallingUid();
1259 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1260 throw new SecurityException("Only the system process can request a permission token, "
1261 + "received request from uid: " + callingUid);
1262 }
1263 IBinder permissionToken = new Binder();
1264 synchronized (mGlobalLock) {
1265 mStartActivitySources.put(permissionToken, delegatorToken);
1266 }
1267
1268 Message expireMsg = PooledLambda.obtainMessage(
1269 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1270 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1271
1272 Message forgetMsg = PooledLambda.obtainMessage(
1273 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1274 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1275
1276 return permissionToken;
1277 }
1278
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 @Override
1280 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1281 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1283 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285 // permission grants) as any app that may launch one of your own activities. So we only
1286 // allow this in two cases:
1287 // 1) The caller is an activity that is part of the core framework, and then only when it
1288 // is running as the system.
1289 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1290 // can only be requested by a system activity, which may then delegate this call to
1291 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 final ActivityRecord sourceRecord;
1293 final int targetUid;
1294 final String targetPackage;
1295 final boolean isResolver;
1296 synchronized (mGlobalLock) {
1297 if (resultTo == null) {
1298 throw new SecurityException("Must be called from an activity");
1299 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001300 final IBinder sourceToken;
1301 if (permissionToken != null) {
1302 // To even attempt to use a permissionToken, an app must also have this signature
1303 // permission.
1304 mAmInternal.enforceCallingPermission(
1305 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1306 "startActivityAsCaller");
1307 // If called with a permissionToken, we want the sourceRecord from the delegator
1308 // activity that requested this token.
1309 sourceToken = mStartActivitySources.remove(permissionToken);
1310 if (sourceToken == null) {
1311 // Invalid permissionToken, check if it recently expired.
1312 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1313 throw new SecurityException("Called with expired permission token: "
1314 + permissionToken);
1315 } else {
1316 throw new SecurityException("Called with invalid permission token: "
1317 + permissionToken);
1318 }
1319 }
1320 } else {
1321 // This method was called directly by the source.
1322 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001324
Wale Ogunwaled32da472018-11-16 07:19:28 -08001325 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001326 if (sourceRecord == null) {
1327 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001328 }
1329 if (sourceRecord.app == null) {
1330 throw new SecurityException("Called without a process attached to activity");
1331 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001332
1333 // Whether called directly or from a delegate, the source activity must be from the
1334 // android package.
1335 if (!sourceRecord.info.packageName.equals("android")) {
1336 throw new SecurityException("Must be called from an activity that is "
1337 + "declared in the android package");
1338 }
1339
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 // This is still okay, as long as this activity is running under the
1342 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001343 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001345 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 + " must be system uid or original calling uid "
1347 + sourceRecord.launchedFromUid);
1348 }
1349 }
1350 if (ignoreTargetSecurity) {
1351 if (intent.getComponent() == null) {
1352 throw new SecurityException(
1353 "Component must be specified with ignoreTargetSecurity");
1354 }
1355 if (intent.getSelector() != null) {
1356 throw new SecurityException(
1357 "Selector not allowed with ignoreTargetSecurity");
1358 }
1359 }
1360 targetUid = sourceRecord.launchedFromUid;
1361 targetPackage = sourceRecord.launchedFromPackage;
1362 isResolver = sourceRecord.isResolverOrChildActivity();
1363 }
1364
1365 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001366 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367 }
1368
1369 // TODO: Switch to user app stacks here.
1370 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001371 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 .setCallingUid(targetUid)
1373 .setCallingPackage(targetPackage)
1374 .setResolvedType(resolvedType)
1375 .setResultTo(resultTo)
1376 .setResultWho(resultWho)
1377 .setRequestCode(requestCode)
1378 .setStartFlags(startFlags)
1379 .setActivityOptions(bOptions)
1380 .setMayWait(userId)
1381 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1382 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001383 // The target may well be in the background, which would normally prevent it
1384 // from starting an activity. Here we definitely want the start to succeed.
1385 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 .execute();
1387 } catch (SecurityException e) {
1388 // XXX need to figure out how to propagate to original app.
1389 // A SecurityException here is generally actually a fault of the original
1390 // calling activity (such as a fairly granting permissions), so propagate it
1391 // back to them.
1392 /*
1393 StringBuilder msg = new StringBuilder();
1394 msg.append("While launching");
1395 msg.append(intent.toString());
1396 msg.append(": ");
1397 msg.append(e.getMessage());
1398 */
1399 throw e;
1400 }
1401 }
1402
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001403 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1404 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1405 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1406 }
1407
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001408 @Override
1409 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1410 Intent intent, String resolvedType, IVoiceInteractionSession session,
1411 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1412 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 if (session == null || interactor == null) {
1415 throw new NullPointerException("null session or interactor");
1416 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001417 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001419 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 .setCallingUid(callingUid)
1421 .setCallingPackage(callingPackage)
1422 .setResolvedType(resolvedType)
1423 .setVoiceSession(session)
1424 .setVoiceInteractor(interactor)
1425 .setStartFlags(startFlags)
1426 .setProfilerInfo(profilerInfo)
1427 .setActivityOptions(bOptions)
1428 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001429 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 .execute();
1431 }
1432
1433 @Override
1434 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1435 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1437 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001439 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 .setCallingUid(callingUid)
1441 .setCallingPackage(callingPackage)
1442 .setResolvedType(resolvedType)
1443 .setActivityOptions(bOptions)
1444 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001445 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .execute();
1447 }
1448
1449 @Override
1450 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1451 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001452 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 final int callingPid = Binder.getCallingPid();
1454 final long origId = Binder.clearCallingIdentity();
1455 try {
1456 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001457 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1458 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459
1460 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001461 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1462 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1464 recentsUid, assistDataReceiver);
1465 }
1466 } finally {
1467 Binder.restoreCallingIdentity(origId);
1468 }
1469 }
1470
1471 @Override
1472 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001473 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 "startActivityFromRecents()");
1475
1476 final int callingPid = Binder.getCallingPid();
1477 final int callingUid = Binder.getCallingUid();
1478 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1479 final long origId = Binder.clearCallingIdentity();
1480 try {
1481 synchronized (mGlobalLock) {
1482 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1483 safeOptions);
1484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(origId);
1487 }
1488 }
1489
1490 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001491 * Public API to check if the client is allowed to start an activity on specified display.
1492 *
1493 * If the target display is private or virtual, some restrictions will apply.
1494 *
1495 * @param displayId Target display id.
1496 * @param intent Intent used to launch the activity.
1497 * @param resolvedType The MIME type of the intent.
1498 * @param userId The id of the user for whom the call is made.
1499 * @return {@code true} if a call to start an activity on the target display should succeed and
1500 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1501 */
1502 @Override
1503 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1504 String resolvedType, int userId) {
1505 final int callingUid = Binder.getCallingUid();
1506 final int callingPid = Binder.getCallingPid();
1507 final long origId = Binder.clearCallingIdentity();
1508
1509 try {
1510 // Collect information about the target of the Intent.
1511 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1512 0 /* startFlags */, null /* profilerInfo */, userId,
1513 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1514 UserHandle.USER_NULL));
1515 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1516
1517 synchronized (mGlobalLock) {
1518 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1519 aInfo);
1520 }
1521 } finally {
1522 Binder.restoreCallingIdentity(origId);
1523 }
1524 }
1525
1526 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001527 * This is the internal entry point for handling Activity.finish().
1528 *
1529 * @param token The Binder token referencing the Activity we want to finish.
1530 * @param resultCode Result code, if any, from this Activity.
1531 * @param resultData Result data (Intent), if any, from this Activity.
1532 * @param finishTask Whether to finish the task associated with this Activity.
1533 *
1534 * @return Returns true if the activity successfully finished, or false if it is still running.
1535 */
1536 @Override
1537 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1538 int finishTask) {
1539 // Refuse possible leaked file descriptors
1540 if (resultData != null && resultData.hasFileDescriptors()) {
1541 throw new IllegalArgumentException("File descriptors passed in Intent");
1542 }
1543
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001544 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001545 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001546 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 if (r == null) {
1548 return true;
1549 }
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001550 }
1551
1552 // Carefully collect grants without holding lock
1553 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
1554 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
1555
1556 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001558 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001559 ActivityRecord rootR = tr.getRootActivity();
1560 if (rootR == null) {
1561 Slog.w(TAG, "Finishing task with all activities already finished");
1562 }
1563 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1564 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001565 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 return false;
1567 }
1568
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001569 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1570 // We should consolidate.
1571 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001573 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 if (next != null) {
1575 // ask watcher if this is allowed
1576 boolean resumeOK = true;
1577 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001578 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 Watchdog.getInstance().setActivityController(null);
1582 }
1583
1584 if (!resumeOK) {
1585 Slog.i(TAG, "Not finishing activity because controller resumed");
1586 return false;
1587 }
1588 }
1589 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001590
1591 // note down that the process has finished an activity and is in background activity
1592 // starts grace period
1593 if (r.app != null) {
1594 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1595 }
1596
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 final long origId = Binder.clearCallingIdentity();
1598 try {
1599 boolean res;
1600 final boolean finishWithRootActivity =
1601 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1602 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1603 || (finishWithRootActivity && r == rootR)) {
1604 // If requested, remove the task that is associated to this activity only if it
1605 // was the root activity in the task. The result code and data is ignored
1606 // because we don't support returning them across task boundaries. Also, to
1607 // keep backwards compatibility we remove the task from recents when finishing
1608 // task with root activity.
1609 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1610 finishWithRootActivity, "finish-activity");
1611 if (!res) {
1612 Slog.i(TAG, "Removing task failed to finish activity");
1613 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001614 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001615 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 } else {
1617 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001618 resultData, resultGrants, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 if (!res) {
1620 Slog.i(TAG, "Failed to finish by app-request");
1621 }
1622 }
1623 return res;
1624 } finally {
1625 Binder.restoreCallingIdentity(origId);
1626 }
1627 }
1628 }
1629
1630 @Override
1631 public boolean finishActivityAffinity(IBinder token) {
1632 synchronized (mGlobalLock) {
1633 final long origId = Binder.clearCallingIdentity();
1634 try {
1635 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1636 if (r == null) {
1637 return false;
1638 }
1639
1640 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1641 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001642 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001643 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 return false;
1645 }
1646 return task.getStack().finishActivityAffinityLocked(r);
1647 } finally {
1648 Binder.restoreCallingIdentity(origId);
1649 }
1650 }
1651 }
1652
1653 @Override
1654 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1655 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001656 try {
1657 WindowProcessController proc = null;
1658 synchronized (mGlobalLock) {
1659 ActivityStack stack = ActivityRecord.getStackLocked(token);
1660 if (stack == null) {
1661 return;
1662 }
1663 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1664 false /* fromTimeout */, false /* processPausingActivities */, config);
1665 if (r != null) {
1666 proc = r.app;
1667 }
1668 if (stopProfiling && proc != null) {
1669 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001670 }
1671 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001672 } finally {
1673 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 }
1676
1677 @Override
1678 public final void activityResumed(IBinder token) {
1679 final long origId = Binder.clearCallingIdentity();
1680 synchronized (mGlobalLock) {
1681 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001682 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001683 }
1684 Binder.restoreCallingIdentity(origId);
1685 }
1686
1687 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001688 public final void activityTopResumedStateLost() {
1689 final long origId = Binder.clearCallingIdentity();
1690 synchronized (mGlobalLock) {
1691 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1692 }
1693 Binder.restoreCallingIdentity(origId);
1694 }
1695
1696 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 public final void activityPaused(IBinder token) {
1698 final long origId = Binder.clearCallingIdentity();
1699 synchronized (mGlobalLock) {
1700 ActivityStack stack = ActivityRecord.getStackLocked(token);
1701 if (stack != null) {
1702 stack.activityPausedLocked(token, false);
1703 }
1704 }
1705 Binder.restoreCallingIdentity(origId);
1706 }
1707
1708 @Override
1709 public final void activityStopped(IBinder token, Bundle icicle,
1710 PersistableBundle persistentState, CharSequence description) {
1711 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1712
1713 // Refuse possible leaked file descriptors
1714 if (icicle != null && icicle.hasFileDescriptors()) {
1715 throw new IllegalArgumentException("File descriptors passed in Bundle");
1716 }
1717
1718 final long origId = Binder.clearCallingIdentity();
1719
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001720 String restartingName = null;
1721 int restartingUid = 0;
1722 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001724 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001725 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001726 if (r.attachedToProcess()
1727 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1728 // The activity was requested to restart from
1729 // {@link #restartActivityProcessIfVisible}.
1730 restartingName = r.app.mName;
1731 restartingUid = r.app.mUid;
1732 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 r.activityStoppedLocked(icicle, persistentState, description);
1734 }
1735 }
1736
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001737 if (restartingName != null) {
1738 // In order to let the foreground activity can be restarted with its saved state from
1739 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1740 // until the activity reports stopped with the state. And the activity record will be
1741 // kept because the record state is restarting, then the activity will be restarted
1742 // immediately if it is still the top one.
1743 mStackSupervisor.removeRestartTimeouts(r);
1744 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1745 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001746 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747
1748 Binder.restoreCallingIdentity(origId);
1749 }
1750
1751 @Override
1752 public final void activityDestroyed(IBinder token) {
1753 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1754 synchronized (mGlobalLock) {
1755 ActivityStack stack = ActivityRecord.getStackLocked(token);
1756 if (stack != null) {
1757 stack.activityDestroyedLocked(token, "activityDestroyed");
1758 }
1759 }
1760 }
1761
1762 @Override
1763 public final void activityRelaunched(IBinder token) {
1764 final long origId = Binder.clearCallingIdentity();
1765 synchronized (mGlobalLock) {
1766 mStackSupervisor.activityRelaunchedLocked(token);
1767 }
1768 Binder.restoreCallingIdentity(origId);
1769 }
1770
1771 public final void activitySlept(IBinder token) {
1772 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1773
1774 final long origId = Binder.clearCallingIdentity();
1775
1776 synchronized (mGlobalLock) {
1777 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1778 if (r != null) {
1779 mStackSupervisor.activitySleptLocked(r);
1780 }
1781 }
1782
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785
1786 @Override
1787 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1788 synchronized (mGlobalLock) {
1789 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1790 if (r == null) {
1791 return;
1792 }
1793 final long origId = Binder.clearCallingIdentity();
1794 try {
1795 r.setRequestedOrientation(requestedOrientation);
1796 } finally {
1797 Binder.restoreCallingIdentity(origId);
1798 }
1799 }
1800 }
1801
1802 @Override
1803 public int getRequestedOrientation(IBinder token) {
1804 synchronized (mGlobalLock) {
1805 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1806 if (r == null) {
1807 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1808 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001809 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 }
1811 }
1812
1813 @Override
1814 public void setImmersive(IBinder token, boolean immersive) {
1815 synchronized (mGlobalLock) {
1816 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1817 if (r == null) {
1818 throw new IllegalArgumentException();
1819 }
1820 r.immersive = immersive;
1821
1822 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001823 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001825 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 }
1827 }
1828 }
1829
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001830 void applyUpdateLockStateLocked(ActivityRecord r) {
1831 // Modifications to the UpdateLock state are done on our handler, outside
1832 // the activity manager's locks. The new state is determined based on the
1833 // state *now* of the relevant activity record. The object is passed to
1834 // the handler solely for logging detail, not to be consulted/modified.
1835 final boolean nextState = r != null && r.immersive;
1836 mH.post(() -> {
1837 if (mUpdateLock.isHeld() != nextState) {
1838 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1839 "Applying new update lock state '" + nextState + "' for " + r);
1840 if (nextState) {
1841 mUpdateLock.acquire();
1842 } else {
1843 mUpdateLock.release();
1844 }
1845 }
1846 });
1847 }
1848
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 @Override
1850 public boolean isImmersive(IBinder token) {
1851 synchronized (mGlobalLock) {
1852 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1853 if (r == null) {
1854 throw new IllegalArgumentException();
1855 }
1856 return r.immersive;
1857 }
1858 }
1859
1860 @Override
1861 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001864 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 return (r != null) ? r.immersive : false;
1866 }
1867 }
1868
1869 @Override
1870 public void overridePendingTransition(IBinder token, String packageName,
1871 int enterAnim, int exitAnim) {
1872 synchronized (mGlobalLock) {
1873 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1874 if (self == null) {
1875 return;
1876 }
1877
1878 final long origId = Binder.clearCallingIdentity();
1879
1880 if (self.isState(
1881 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001882 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001883 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 }
1885
1886 Binder.restoreCallingIdentity(origId);
1887 }
1888 }
1889
1890 @Override
1891 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001894 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001895 if (r == null) {
1896 return ActivityManager.COMPAT_MODE_UNKNOWN;
1897 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001898 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 }
1900 }
1901
1902 @Override
1903 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001908 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001909 if (r == null) {
1910 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1911 return;
1912 }
1913 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001914 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 }
1916 }
1917
1918 @Override
1919 public int getLaunchedFromUid(IBinder activityToken) {
1920 ActivityRecord srec;
1921 synchronized (mGlobalLock) {
1922 srec = ActivityRecord.forTokenLocked(activityToken);
1923 }
1924 if (srec == null) {
1925 return -1;
1926 }
1927 return srec.launchedFromUid;
1928 }
1929
1930 @Override
1931 public String getLaunchedFromPackage(IBinder activityToken) {
1932 ActivityRecord srec;
1933 synchronized (mGlobalLock) {
1934 srec = ActivityRecord.forTokenLocked(activityToken);
1935 }
1936 if (srec == null) {
1937 return null;
1938 }
1939 return srec.launchedFromPackage;
1940 }
1941
1942 @Override
1943 public boolean convertFromTranslucent(IBinder token) {
1944 final long origId = Binder.clearCallingIdentity();
1945 try {
1946 synchronized (mGlobalLock) {
1947 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1948 if (r == null) {
1949 return false;
1950 }
1951 final boolean translucentChanged = r.changeWindowTranslucency(true);
1952 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001953 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001955 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 return translucentChanged;
1957 }
1958 } finally {
1959 Binder.restoreCallingIdentity(origId);
1960 }
1961 }
1962
1963 @Override
1964 public boolean convertToTranslucent(IBinder token, Bundle options) {
1965 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1966 final long origId = Binder.clearCallingIdentity();
1967 try {
1968 synchronized (mGlobalLock) {
1969 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1970 if (r == null) {
1971 return false;
1972 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001973 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 int index = task.mActivities.lastIndexOf(r);
1975 if (index > 0) {
1976 ActivityRecord under = task.mActivities.get(index - 1);
1977 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1978 }
1979 final boolean translucentChanged = r.changeWindowTranslucency(false);
1980 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001981 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001983 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001984 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 return translucentChanged;
1986 }
1987 } finally {
1988 Binder.restoreCallingIdentity(origId);
1989 }
1990 }
1991
1992 @Override
1993 public void notifyActivityDrawn(IBinder token) {
1994 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1995 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001996 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001998 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 }
2000 }
2001 }
2002
2003 @Override
2004 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2005 synchronized (mGlobalLock) {
2006 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2007 if (r == null) {
2008 return;
2009 }
2010 r.reportFullyDrawnLocked(restoredFromBundle);
2011 }
2012 }
2013
2014 @Override
2015 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2016 synchronized (mGlobalLock) {
2017 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2018 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2019 return stack.mDisplayId;
2020 }
2021 return DEFAULT_DISPLAY;
2022 }
2023 }
2024
2025 @Override
2026 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002027 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 long ident = Binder.clearCallingIdentity();
2029 try {
2030 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002031 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002033 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 }
2035 return null;
2036 }
2037 } finally {
2038 Binder.restoreCallingIdentity(ident);
2039 }
2040 }
2041
2042 @Override
2043 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002044 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2046 final long callingId = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002049 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (stack == null) {
2051 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2052 return;
2053 }
2054 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002055 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002056 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 }
2058 }
2059 } finally {
2060 Binder.restoreCallingIdentity(callingId);
2061 }
2062 }
2063
2064 @Override
2065 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2068 final long callingId = Binder.clearCallingIdentity();
2069 try {
2070 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002072 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (task == null) {
2074 return;
2075 }
2076 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002077 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002078 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 }
2080 }
2081 } finally {
2082 Binder.restoreCallingIdentity(callingId);
2083 }
2084 }
2085
2086 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002087 public void restartActivityProcessIfVisible(IBinder activityToken) {
2088 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2089 final long callingId = Binder.clearCallingIdentity();
2090 try {
2091 synchronized (mGlobalLock) {
2092 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2093 if (r == null) {
2094 return;
2095 }
2096 r.restartProcessIfVisible();
2097 }
2098 } finally {
2099 Binder.restoreCallingIdentity(callingId);
2100 }
2101 }
2102
2103 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002105 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 synchronized (mGlobalLock) {
2107 final long ident = Binder.clearCallingIdentity();
2108 try {
2109 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2110 "remove-task");
2111 } finally {
2112 Binder.restoreCallingIdentity(ident);
2113 }
2114 }
2115 }
2116
2117 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002118 public void removeAllVisibleRecentTasks() {
2119 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2120 synchronized (mGlobalLock) {
2121 final long ident = Binder.clearCallingIdentity();
2122 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002123 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002124 } finally {
2125 Binder.restoreCallingIdentity(ident);
2126 }
2127 }
2128 }
2129
2130 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2132 synchronized (mGlobalLock) {
2133 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2134 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002135 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 }
2137 }
2138 return false;
2139 }
2140
2141 @Override
2142 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2143 Intent resultData) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002144 final ActivityRecord r;
2145 synchronized (mGlobalLock) {
2146 r = ActivityRecord.isInStackLocked(token);
2147 if (r == null) {
2148 return false;
2149 }
2150 }
2151
2152 // Carefully collect grants without holding lock
2153 final NeededUriGrants destGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
2154 Binder.getCallingUid(), destIntent, r.packageName, r.mUserId);
2155 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
2156 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157
2158 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002159 return r.getActivityStack().navigateUpToLocked(
2160 r, destIntent, destGrants, resultCode, resultData, resultGrants);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 }
2162 }
2163
2164 /**
2165 * Attempts to move a task backwards in z-order (the order of activities within the task is
2166 * unchanged).
2167 *
2168 * There are several possible results of this call:
2169 * - if the task is locked, then we will show the lock toast
2170 * - if there is a task behind the provided task, then that task is made visible and resumed as
2171 * this task is moved to the back
2172 * - otherwise, if there are no other tasks in the stack:
2173 * - if this task is in the pinned stack, then we remove the stack completely, which will
2174 * have the effect of moving the task to the top or bottom of the fullscreen stack
2175 * (depending on whether it is visible)
2176 * - otherwise, we simply return home and hide this task
2177 *
2178 * @param token A reference to the activity we wish to move
2179 * @param nonRoot If false then this only works if the activity is the root
2180 * of a task; if true it will work for any activity in a task.
2181 * @return Returns true if the move completed, false if not.
2182 */
2183 @Override
2184 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002185 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 synchronized (mGlobalLock) {
2187 final long origId = Binder.clearCallingIdentity();
2188 try {
2189 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002190 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 if (task != null) {
2192 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(origId);
2196 }
2197 }
2198 return false;
2199 }
2200
2201 @Override
2202 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002203 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 long ident = Binder.clearCallingIdentity();
2205 Rect rect = new Rect();
2206 try {
2207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002208 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2210 if (task == null) {
2211 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2212 return rect;
2213 }
2214 if (task.getStack() != null) {
2215 // Return the bounds from window manager since it will be adjusted for various
2216 // things like the presense of a docked stack for tasks that aren't resizeable.
2217 task.getWindowContainerBounds(rect);
2218 } else {
2219 // Task isn't in window manager yet since it isn't associated with a stack.
2220 // Return the persist value from activity manager
2221 if (!task.matchParentBounds()) {
2222 rect.set(task.getBounds());
2223 } else if (task.mLastNonFullscreenBounds != null) {
2224 rect.set(task.mLastNonFullscreenBounds);
2225 }
2226 }
2227 }
2228 } finally {
2229 Binder.restoreCallingIdentity(ident);
2230 }
2231 return rect;
2232 }
2233
2234 @Override
2235 public ActivityManager.TaskDescription getTaskDescription(int id) {
2236 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002237 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002239 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2241 if (tr != null) {
2242 return tr.lastTaskDescription;
2243 }
2244 }
2245 return null;
2246 }
2247
2248 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2250 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2251 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2252 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2253 return;
2254 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002255 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002256 synchronized (mGlobalLock) {
2257 final long ident = Binder.clearCallingIdentity();
2258 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002259 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002260 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002261 if (task == null) {
2262 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2263 return;
2264 }
2265
2266 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2267 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2268
2269 if (!task.isActivityTypeStandardOrUndefined()) {
2270 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2271 + " non-standard task " + taskId + " to windowing mode="
2272 + windowingMode);
2273 }
2274
2275 final ActivityStack stack = task.getStack();
2276 if (toTop) {
2277 stack.moveToFront("setTaskWindowingMode", task);
2278 }
2279 stack.setWindowingMode(windowingMode);
2280 } finally {
2281 Binder.restoreCallingIdentity(ident);
2282 }
2283 }
2284 }
2285
2286 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002287 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002288 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 ActivityRecord r = getCallingRecordLocked(token);
2290 return r != null ? r.info.packageName : null;
2291 }
2292 }
2293
2294 @Override
2295 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002296 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 ActivityRecord r = getCallingRecordLocked(token);
2298 return r != null ? r.intent.getComponent() : null;
2299 }
2300 }
2301
2302 private ActivityRecord getCallingRecordLocked(IBinder token) {
2303 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2304 if (r == null) {
2305 return null;
2306 }
2307 return r.resultTo;
2308 }
2309
2310 @Override
2311 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002312 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313
2314 synchronized (mGlobalLock) {
2315 final long origId = Binder.clearCallingIdentity();
2316 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002317 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 } finally {
2319 Binder.restoreCallingIdentity(origId);
2320 }
2321 }
2322 }
2323
Mark Renouf446251d2019-04-26 10:22:41 -04002324 @Override
2325 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2326 synchronized (mGlobalLock) {
2327 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2328 if (r == null) {
2329 return;
2330 }
2331 ActivityStack stack = r.getActivityStack();
2332 if (stack != null && stack.isSingleTaskInstance()) {
2333 // Single-task stacks are used for activities which are presented in floating
2334 // windows above full screen activities. Instead of directly finishing the
2335 // task, a task change listener is used to notify SystemUI so the action can be
2336 // handled specially.
2337 final TaskRecord task = r.getTaskRecord();
2338 mTaskChangeNotificationController
2339 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2340 } else {
2341 try {
2342 callback.requestFinish();
2343 } catch (RemoteException e) {
2344 Slog.e(TAG, "Failed to invoke request finish callback", e);
2345 }
2346 }
2347 }
2348 }
2349
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 /**
2351 * TODO: Add mController hook
2352 */
2353 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002354 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2355 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002356 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357
2358 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2359 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2361 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002362 }
2363 }
2364
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2366 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 boolean fromRecents) {
2368
Ricky Waiaca8a772019-04-04 16:01:06 +01002369 final int callingPid = Binder.getCallingPid();
2370 final int callingUid = Binder.getCallingUid();
2371 if (!isSameApp(callingUid, callingPackage)) {
2372 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2373 + Binder.getCallingPid() + " as package " + callingPackage;
2374 Slog.w(TAG, msg);
2375 throw new SecurityException(msg);
2376 }
2377 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 SafeActivityOptions.abort(options);
2379 return;
2380 }
2381 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002382 WindowProcessController callerApp = null;
2383 if (appThread != null) {
2384 callerApp = getProcessController(appThread);
2385 }
2386 final ActivityStarter starter = getActivityStartController().obtainStarter(
2387 null /* intent */, "moveTaskToFront");
2388 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2389 -1, callerApp, null, false, null)) {
2390 boolean abort = !isBackgroundActivityStartsEnabled();
2391 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2392 if (abort) {
2393 return;
2394 }
2395 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002397 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 if (task == null) {
2399 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002400 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002401 return;
2402 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002403 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002405 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 return;
2407 }
2408 ActivityOptions realOptions = options != null
2409 ? options.getOptions(mStackSupervisor)
2410 : null;
2411 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2412 false /* forceNonResizable */);
2413
2414 final ActivityRecord topActivity = task.getTopActivity();
2415 if (topActivity != null) {
2416
2417 // We are reshowing a task, use a starting window to hide the initial draw delay
2418 // so the transition can start earlier.
2419 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2420 true /* taskSwitch */, fromRecents);
2421 }
2422 } finally {
2423 Binder.restoreCallingIdentity(origId);
2424 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002425 }
2426
Ricky Waiaca8a772019-04-04 16:01:06 +01002427 /**
2428 * Return true if callingUid is system, or packageName belongs to that callingUid.
2429 */
2430 boolean isSameApp(int callingUid, @Nullable String packageName) {
2431 try {
2432 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2433 if (packageName == null) {
2434 return false;
2435 }
2436 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2437 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2438 UserHandle.getUserId(callingUid));
2439 return UserHandle.isSameApp(callingUid, uid);
2440 }
2441 } catch (RemoteException e) {
2442 // Should not happen
2443 }
2444 return true;
2445 }
2446
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002447 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2448 int callingPid, int callingUid, String name) {
2449 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2450 return true;
2451 }
2452
2453 if (getRecentTasks().isCallerRecents(sourceUid)) {
2454 return true;
2455 }
2456
2457 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2458 if (perm == PackageManager.PERMISSION_GRANTED) {
2459 return true;
2460 }
2461 if (checkAllowAppSwitchUid(sourceUid)) {
2462 return true;
2463 }
2464
2465 // If the actual IPC caller is different from the logical source, then
2466 // also see if they are allowed to control app switches.
2467 if (callingUid != -1 && callingUid != sourceUid) {
2468 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2469 if (perm == PackageManager.PERMISSION_GRANTED) {
2470 return true;
2471 }
2472 if (checkAllowAppSwitchUid(callingUid)) {
2473 return true;
2474 }
2475 }
2476
2477 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2478 return false;
2479 }
2480
2481 private boolean checkAllowAppSwitchUid(int uid) {
2482 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2483 if (types != null) {
2484 for (int i = types.size() - 1; i >= 0; i--) {
2485 if (types.valueAt(i).intValue() == uid) {
2486 return true;
2487 }
2488 }
2489 }
2490 return false;
2491 }
2492
2493 @Override
2494 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2495 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2496 "setActivityController()");
2497 synchronized (mGlobalLock) {
2498 mController = controller;
2499 mControllerIsAMonkey = imAMonkey;
2500 Watchdog.getInstance().setActivityController(controller);
2501 }
2502 }
2503
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002504 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002505 synchronized (mGlobalLock) {
2506 return mController != null && mControllerIsAMonkey;
2507 }
2508 }
2509
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 @Override
2511 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2512 synchronized (mGlobalLock) {
2513 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2514 }
2515 }
2516
2517 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002518 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2519 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2520 }
2521
2522 @Override
2523 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2524 @WindowConfiguration.ActivityType int ignoreActivityType,
2525 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2526 final int callingUid = Binder.getCallingUid();
2527 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2528
2529 synchronized (mGlobalLock) {
2530 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2531
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002532 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002533 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002534 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 ignoreWindowingMode, callingUid, allowed);
2536 }
2537
2538 return list;
2539 }
2540
2541 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2543 synchronized (mGlobalLock) {
2544 final long origId = Binder.clearCallingIdentity();
2545 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2546 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002547 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 }
2549 Binder.restoreCallingIdentity(origId);
2550 }
2551 }
2552
2553 @Override
2554 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002555 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 ActivityStack stack = ActivityRecord.getStackLocked(token);
2557 if (stack != null) {
2558 return stack.willActivityBeVisibleLocked(token);
2559 }
2560 return false;
2561 }
2562 }
2563
2564 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002566 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 synchronized (mGlobalLock) {
2568 final long ident = Binder.clearCallingIdentity();
2569 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002570 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 if (task == null) {
2572 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2573 return;
2574 }
2575
2576 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2577 + " to stackId=" + stackId + " toTop=" + toTop);
2578
Wale Ogunwaled32da472018-11-16 07:19:28 -08002579 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002580 if (stack == null) {
2581 throw new IllegalStateException(
2582 "moveTaskToStack: No stack for stackId=" + stackId);
2583 }
2584 if (!stack.isActivityTypeStandardOrUndefined()) {
2585 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2586 + taskId + " to stack " + stackId);
2587 }
2588 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002589 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2591 }
2592 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2593 "moveTaskToStack");
2594 } finally {
2595 Binder.restoreCallingIdentity(ident);
2596 }
2597 }
2598 }
2599
2600 @Override
2601 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2602 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002604
2605 final long ident = Binder.clearCallingIdentity();
2606 try {
2607 synchronized (mGlobalLock) {
2608 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002609 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002610 if (stack == null) {
2611 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2612 return;
2613 }
2614 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2615 throw new IllegalArgumentException("Stack: " + stackId
2616 + " doesn't support animated resize.");
2617 }
2618 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2619 animationDuration, false /* fromFullscreen */);
2620 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002621 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002622 if (stack == null) {
2623 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2624 return;
2625 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002626 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002627 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2628 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2629 }
2630 }
2631 } finally {
2632 Binder.restoreCallingIdentity(ident);
2633 }
2634 }
2635
wilsonshih5c4cf522019-01-25 09:03:47 +08002636 @Override
2637 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2638 int animationDuration) {
2639 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2640
2641 final long ident = Binder.clearCallingIdentity();
2642 try {
2643 synchronized (mGlobalLock) {
2644 if (xOffset == 0 && yOffset == 0) {
2645 return;
2646 }
2647 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2648 if (stack == null) {
2649 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2650 return;
2651 }
2652 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2653 throw new IllegalArgumentException("Stack: " + stackId
2654 + " doesn't support animated resize.");
2655 }
2656 final Rect destBounds = new Rect();
2657 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002658 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002659 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2660 return;
2661 }
2662 destBounds.offset(xOffset, yOffset);
2663 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2664 animationDuration, false /* fromFullscreen */);
2665 }
2666 } finally {
2667 Binder.restoreCallingIdentity(ident);
2668 }
2669 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002670 /**
2671 * Moves the specified task to the primary-split-screen stack.
2672 *
2673 * @param taskId Id of task to move.
2674 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2675 * exist already. See
2676 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2677 * and
2678 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2679 * @param toTop If the task and stack should be moved to the top.
2680 * @param animate Whether we should play an animation for the moving the task.
2681 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2682 * stack. Pass {@code null} to use default bounds.
2683 * @param showRecents If the recents activity should be shown on the other side of the task
2684 * going into split-screen mode.
2685 */
2686 @Override
2687 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2688 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002689 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 "setTaskWindowingModeSplitScreenPrimary()");
2691 synchronized (mGlobalLock) {
2692 final long ident = Binder.clearCallingIdentity();
2693 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002694 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002695 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 if (task == null) {
2697 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2698 return false;
2699 }
2700 if (DEBUG_STACK) Slog.d(TAG_STACK,
2701 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2702 + " to createMode=" + createMode + " toTop=" + toTop);
2703 if (!task.isActivityTypeStandardOrUndefined()) {
2704 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2705 + " non-standard task " + taskId + " to split-screen windowing mode");
2706 }
2707
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002708 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002709 final int windowingMode = task.getWindowingMode();
2710 final ActivityStack stack = task.getStack();
2711 if (toTop) {
2712 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2713 }
2714 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002715 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2716 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 return windowingMode != task.getWindowingMode();
2718 } finally {
2719 Binder.restoreCallingIdentity(ident);
2720 }
2721 }
2722 }
2723
2724 /**
2725 * Removes stacks in the input windowing modes from the system if they are of activity type
2726 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2727 */
2728 @Override
2729 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002730 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 "removeStacksInWindowingModes()");
2732
2733 synchronized (mGlobalLock) {
2734 final long ident = Binder.clearCallingIdentity();
2735 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002736 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002737 } finally {
2738 Binder.restoreCallingIdentity(ident);
2739 }
2740 }
2741 }
2742
2743 @Override
2744 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002745 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 "removeStacksWithActivityTypes()");
2747
2748 synchronized (mGlobalLock) {
2749 final long ident = Binder.clearCallingIdentity();
2750 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002751 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757
2758 @Override
2759 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2760 int userId) {
2761 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2763 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002765 final boolean detailed = checkGetTasksPermission(
2766 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2767 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 == PackageManager.PERMISSION_GRANTED;
2769
2770 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002771 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772 callingUid);
2773 }
2774 }
2775
2776 @Override
2777 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002778 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 long ident = Binder.clearCallingIdentity();
2780 try {
2781 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002782 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 }
2784 } finally {
2785 Binder.restoreCallingIdentity(ident);
2786 }
2787 }
2788
2789 @Override
2790 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002791 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 long ident = Binder.clearCallingIdentity();
2793 try {
2794 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002795 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002796 }
2797 } finally {
2798 Binder.restoreCallingIdentity(ident);
2799 }
2800 }
2801
2802 @Override
2803 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 final long callingUid = Binder.getCallingUid();
2806 final long origId = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
2809 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2812 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2813 }
2814 } finally {
2815 Binder.restoreCallingIdentity(origId);
2816 }
2817 }
2818
2819 @Override
2820 public void startLockTaskModeByToken(IBinder token) {
2821 synchronized (mGlobalLock) {
2822 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2823 if (r == null) {
2824 return;
2825 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002826 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 }
2828 }
2829
2830 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002831 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002832 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 // This makes inner call to look as if it was initiated by system.
2834 long ident = Binder.clearCallingIdentity();
2835 try {
2836 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002837 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002838 MATCH_TASK_IN_STACKS_ONLY);
2839 if (task == null) {
2840 return;
2841 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842
2843 // When starting lock task mode the stack must be in front and focused
2844 task.getStack().moveToFront("startSystemLockTaskMode");
2845 startLockTaskModeLocked(task, true /* isSystemCaller */);
2846 }
2847 } finally {
2848 Binder.restoreCallingIdentity(ident);
2849 }
2850 }
2851
2852 @Override
2853 public void stopLockTaskModeByToken(IBinder token) {
2854 synchronized (mGlobalLock) {
2855 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2856 if (r == null) {
2857 return;
2858 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002859 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 }
2861 }
2862
2863 /**
2864 * This API should be called by SystemUI only when user perform certain action to dismiss
2865 * lock task mode. We should only dismiss pinned lock task mode in this case.
2866 */
2867 @Override
2868 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002869 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2871 }
2872
2873 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2874 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2875 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2876 return;
2877 }
2878
Wale Ogunwaled32da472018-11-16 07:19:28 -08002879 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 if (stack == null || task != stack.topTask()) {
2881 throw new IllegalArgumentException("Invalid task, not in foreground");
2882 }
2883
2884 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2885 // system or a specific app.
2886 // * System-initiated requests will only start the pinned mode (screen pinning)
2887 // * App-initiated requests
2888 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2889 // - will start the pinned mode, otherwise
2890 final int callingUid = Binder.getCallingUid();
2891 long ident = Binder.clearCallingIdentity();
2892 try {
2893 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002894 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002896 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 } finally {
2898 Binder.restoreCallingIdentity(ident);
2899 }
2900 }
2901
2902 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2903 final int callingUid = Binder.getCallingUid();
2904 long ident = Binder.clearCallingIdentity();
2905 try {
2906 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002907 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002908 }
2909 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2910 // task and jumping straight into a call in the case of emergency call back.
2911 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2912 if (tm != null) {
2913 tm.showInCallScreen(false);
2914 }
2915 } finally {
2916 Binder.restoreCallingIdentity(ident);
2917 }
2918 }
2919
2920 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002921 public void updateLockTaskPackages(int userId, String[] packages) {
2922 final int callingUid = Binder.getCallingUid();
2923 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2924 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2925 "updateLockTaskPackages()");
2926 }
2927 synchronized (this) {
2928 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2929 + Arrays.toString(packages));
2930 getLockTaskController().updateLockTaskPackages(userId, packages);
2931 }
2932 }
2933
2934 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 public boolean isInLockTaskMode() {
2936 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2937 }
2938
2939 @Override
2940 public int getLockTaskModeState() {
2941 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002942 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 }
2944 }
2945
2946 @Override
2947 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2948 synchronized (mGlobalLock) {
2949 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2950 if (r != null) {
2951 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002952 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002954 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 }
2956 }
2957 }
2958
2959 @Override
2960 public Bundle getActivityOptions(IBinder token) {
2961 final long origId = Binder.clearCallingIdentity();
2962 try {
2963 synchronized (mGlobalLock) {
2964 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2965 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002966 final ActivityOptions activityOptions = r.takeOptionsLocked(
2967 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 return activityOptions == null ? null : activityOptions.toBundle();
2969 }
2970 return null;
2971 }
2972 } finally {
2973 Binder.restoreCallingIdentity(origId);
2974 }
2975 }
2976
2977 @Override
2978 public List<IBinder> getAppTasks(String callingPackage) {
2979 int callingUid = Binder.getCallingUid();
2980 long ident = Binder.clearCallingIdentity();
2981 try {
2982 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002983 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 }
2985 } finally {
2986 Binder.restoreCallingIdentity(ident);
2987 }
2988 }
2989
2990 @Override
2991 public void finishVoiceTask(IVoiceInteractionSession session) {
2992 synchronized (mGlobalLock) {
2993 final long origId = Binder.clearCallingIdentity();
2994 try {
2995 // TODO: VI Consider treating local voice interactions and voice tasks
2996 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002997 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002998 } finally {
2999 Binder.restoreCallingIdentity(origId);
3000 }
3001 }
3002
3003 }
3004
3005 @Override
3006 public boolean isTopOfTask(IBinder token) {
3007 synchronized (mGlobalLock) {
3008 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003009 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 }
3011 }
3012
3013 @Override
3014 public void notifyLaunchTaskBehindComplete(IBinder token) {
3015 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3016 }
3017
3018 @Override
3019 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003020 mH.post(() -> {
3021 synchronized (mGlobalLock) {
3022 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003023 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003024 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003025 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003026 } catch (RemoteException e) {
3027 }
3028 }
3029 }
3030
3031 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 }
3033
3034 /** Called from an app when assist data is ready. */
3035 @Override
3036 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3037 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003038 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 synchronized (pae) {
3040 pae.result = extras;
3041 pae.structure = structure;
3042 pae.content = content;
3043 if (referrer != null) {
3044 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3045 }
3046 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003047 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003048 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3049 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 structure.setHomeActivity(pae.isHome);
3051 }
3052 pae.haveResult = true;
3053 pae.notifyAll();
3054 if (pae.intent == null && pae.receiver == null) {
3055 // Caller is just waiting for the result.
3056 return;
3057 }
3058 }
3059 // We are now ready to launch the assist activity.
3060 IAssistDataReceiver sendReceiver = null;
3061 Bundle sendBundle = null;
3062 synchronized (mGlobalLock) {
3063 buildAssistBundleLocked(pae, extras);
3064 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003065 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 if (!exists) {
3067 // Timed out.
3068 return;
3069 }
3070
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003071 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 // Caller wants result sent back to them.
3073 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003074 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3075 pae.activity.getTaskRecord().taskId);
3076 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3077 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3079 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3080 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3081 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3082 }
3083 }
3084 if (sendReceiver != null) {
3085 try {
3086 sendReceiver.onHandleAssistData(sendBundle);
3087 } catch (RemoteException e) {
3088 }
3089 return;
3090 }
3091
3092 final long ident = Binder.clearCallingIdentity();
3093 try {
3094 if (TextUtils.equals(pae.intent.getAction(),
3095 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3096 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003097
3098 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 } else {
3100 pae.intent.replaceExtras(pae.extras);
3101 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3102 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3103 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003104 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003105
3106 try {
3107 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3108 } catch (ActivityNotFoundException e) {
3109 Slog.w(TAG, "No activity to handle assist action.", e);
3110 }
3111 }
3112 } finally {
3113 Binder.restoreCallingIdentity(ident);
3114 }
3115 }
3116
Marvin Ramin830d4e32019-03-12 13:16:58 +01003117 /**
3118 * Workaround for historical API which starts the Assist service with a non-foreground
3119 * {@code startService()} call.
3120 */
3121 private void startVoiceInteractionServiceAsUser(
3122 Intent intent, int userHandle, String reason) {
3123 // Resolve the intent to find out which package we need to whitelist.
3124 ResolveInfo resolveInfo =
3125 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3126 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3127 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3128 return;
3129 }
3130 intent.setPackage(resolveInfo.serviceInfo.packageName);
3131
3132 // Whitelist background services temporarily.
3133 LocalServices.getService(DeviceIdleController.LocalService.class)
3134 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3135 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3136
3137 // Finally, try to start the service.
3138 try {
3139 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3140 } catch (RuntimeException e) {
3141 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3142 }
3143 }
3144
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 @Override
3146 public int addAppTask(IBinder activityToken, Intent intent,
3147 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3148 final int callingUid = Binder.getCallingUid();
3149 final long callingIdent = Binder.clearCallingIdentity();
3150
3151 try {
3152 synchronized (mGlobalLock) {
3153 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3154 if (r == null) {
3155 throw new IllegalArgumentException("Activity does not exist; token="
3156 + activityToken);
3157 }
3158 ComponentName comp = intent.getComponent();
3159 if (comp == null) {
3160 throw new IllegalArgumentException("Intent " + intent
3161 + " must specify explicit component");
3162 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003163 if (thumbnail.getWidth() != mThumbnailWidth
3164 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 throw new IllegalArgumentException("Bad thumbnail size: got "
3166 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003167 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 }
3169 if (intent.getSelector() != null) {
3170 intent.setSelector(null);
3171 }
3172 if (intent.getSourceBounds() != null) {
3173 intent.setSourceBounds(null);
3174 }
3175 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3176 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3177 // The caller has added this as an auto-remove task... that makes no
3178 // sense, so turn off auto-remove.
3179 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3180 }
3181 }
3182 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3183 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3184 if (ainfo.applicationInfo.uid != callingUid) {
3185 throw new SecurityException(
3186 "Can't add task for another application: target uid="
3187 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3188 }
3189
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003190 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003192 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003194 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 // The app has too many tasks already and we can't add any more
3196 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3197 return INVALID_TASK_ID;
3198 }
3199 task.lastTaskDescription.copyFrom(description);
3200
3201 // TODO: Send the thumbnail to WM to store it.
3202
3203 return task.taskId;
3204 }
3205 } finally {
3206 Binder.restoreCallingIdentity(callingIdent);
3207 }
3208 }
3209
3210 @Override
3211 public Point getAppTaskThumbnailSize() {
3212 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003213 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 }
3215 }
3216
3217 @Override
3218 public void setTaskResizeable(int taskId, int resizeableMode) {
3219 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003220 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003221 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3222 if (task == null) {
3223 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3224 return;
3225 }
3226 task.setResizeMode(resizeableMode);
3227 }
3228 }
3229
3230 @Override
3231 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003232 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 long ident = Binder.clearCallingIdentity();
3234 try {
3235 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003236 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003237 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 if (task == null) {
3239 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3240 return;
3241 }
3242 // Place the task in the right stack if it isn't there already based on
3243 // the requested bounds.
3244 // The stack transition logic is:
3245 // - a null bounds on a freeform task moves that task to fullscreen
3246 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3247 // that task to freeform
3248 // - otherwise the task is not moved
3249 ActivityStack stack = task.getStack();
3250 if (!task.getWindowConfiguration().canResizeTask()) {
3251 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3252 }
3253 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3254 stack = stack.getDisplay().getOrCreateStack(
3255 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3256 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3257 stack = stack.getDisplay().getOrCreateStack(
3258 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3259 }
3260
3261 // Reparent the task to the right stack if necessary
3262 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3263 if (stack != task.getStack()) {
3264 // Defer resume until the task is resized below
3265 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3266 DEFER_RESUME, "resizeTask");
3267 preserveWindow = false;
3268 }
3269
3270 // After reparenting (which only resizes the task to the stack bounds), resize the
3271 // task to the actual bounds provided
3272 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3273 }
3274 } finally {
3275 Binder.restoreCallingIdentity(ident);
3276 }
3277 }
3278
3279 @Override
3280 public boolean releaseActivityInstance(IBinder token) {
3281 synchronized (mGlobalLock) {
3282 final long origId = Binder.clearCallingIdentity();
3283 try {
3284 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3285 if (r == null) {
3286 return false;
3287 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003288 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 } finally {
3290 Binder.restoreCallingIdentity(origId);
3291 }
3292 }
3293 }
3294
3295 @Override
3296 public void releaseSomeActivities(IApplicationThread appInt) {
3297 synchronized (mGlobalLock) {
3298 final long origId = Binder.clearCallingIdentity();
3299 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003300 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003301 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 } finally {
3303 Binder.restoreCallingIdentity(origId);
3304 }
3305 }
3306 }
3307
3308 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003309 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003310 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311 != PackageManager.PERMISSION_GRANTED) {
3312 throw new SecurityException("Requires permission "
3313 + android.Manifest.permission.DEVICE_POWER);
3314 }
3315
3316 synchronized (mGlobalLock) {
3317 long ident = Binder.clearCallingIdentity();
3318 if (mKeyguardShown != keyguardShowing) {
3319 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003320 final Message msg = PooledLambda.obtainMessage(
3321 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3322 keyguardShowing);
3323 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 }
3325 try {
wilsonshih177261f2019-02-22 12:02:18 +08003326 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 } finally {
3328 Binder.restoreCallingIdentity(ident);
3329 }
3330 }
3331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003332 mH.post(() -> {
3333 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3334 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3335 }
3336 });
3337 }
3338
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003339 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003340 mH.post(() -> {
3341 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3342 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3343 }
3344 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 }
3346
3347 @Override
3348 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003349 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3350 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351
3352 final File passedIconFile = new File(filePath);
3353 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3354 passedIconFile.getName());
3355 if (!legitIconFile.getPath().equals(filePath)
3356 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3357 throw new IllegalArgumentException("Bad file path: " + filePath
3358 + " passed for userId " + userId);
3359 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003360 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 }
3362
3363 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003364 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3366 final ActivityOptions activityOptions = safeOptions != null
3367 ? safeOptions.getOptions(mStackSupervisor)
3368 : null;
3369 if (activityOptions == null
3370 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3371 || activityOptions.getCustomInPlaceResId() == 0) {
3372 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3373 "with valid animation");
3374 }
lumark588a3e82018-07-20 18:53:54 +08003375 // Get top display of front most application.
3376 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3377 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003378 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3379 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3380 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003381 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003382 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003383 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 }
3385
3386 @Override
3387 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003388 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 synchronized (mGlobalLock) {
3390 final long ident = Binder.clearCallingIdentity();
3391 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003392 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 if (stack == null) {
3394 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3395 return;
3396 }
3397 if (!stack.isActivityTypeStandardOrUndefined()) {
3398 throw new IllegalArgumentException(
3399 "Removing non-standard stack is not allowed.");
3400 }
3401 mStackSupervisor.removeStack(stack);
3402 } finally {
3403 Binder.restoreCallingIdentity(ident);
3404 }
3405 }
3406 }
3407
3408 @Override
3409 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003410 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411
3412 synchronized (mGlobalLock) {
3413 final long ident = Binder.clearCallingIdentity();
3414 try {
3415 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3416 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003417 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 } finally {
3419 Binder.restoreCallingIdentity(ident);
3420 }
3421 }
3422 }
3423
3424 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003425 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 synchronized (mGlobalLock) {
3427 long ident = Binder.clearCallingIdentity();
3428 try {
3429 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3430 if (r == null) {
3431 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003432 "toggleFreeformWindowingMode: No activity record matching token="
3433 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 }
3435
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003436 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003437 if (stack == null) {
3438 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3439 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 }
3441
Yunfan Chend967af82019-01-17 18:30:18 +09003442 if (!stack.inFreeformWindowingMode()
3443 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3444 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3445 + "toggle between fullscreen and freeform.");
3446 }
3447
3448 if (stack.inFreeformWindowingMode()) {
3449 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003450 } else if (stack.getParent().inFreeformWindowingMode()) {
3451 // If the window is on a freeform display, set it to undefined. It will be
3452 // resolved to freeform and it can adjust windowing mode when the display mode
3453 // changes in runtime.
3454 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003455 } else {
3456 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3457 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 } finally {
3459 Binder.restoreCallingIdentity(ident);
3460 }
3461 }
3462 }
3463
3464 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3465 @Override
3466 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003469 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 }
3471
3472 /** Unregister a task stack listener so that it stops receiving callbacks. */
3473 @Override
3474 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003475 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003477 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 }
3479
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003480 @Override
3481 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3482 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3483 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3484 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3485 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3486 }
3487
3488 @Override
3489 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3490 IBinder activityToken, int flags) {
3491 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3492 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3493 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3494 }
3495
3496 @Override
3497 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3498 Bundle args) {
3499 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3500 true /* focused */, true /* newSessionId */, userHandle, args,
3501 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3502 }
3503
3504 @Override
3505 public Bundle getAssistContextExtras(int requestType) {
3506 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3507 null, null, true /* focused */, true /* newSessionId */,
3508 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3509 if (pae == null) {
3510 return null;
3511 }
3512 synchronized (pae) {
3513 while (!pae.haveResult) {
3514 try {
3515 pae.wait();
3516 } catch (InterruptedException e) {
3517 }
3518 }
3519 }
3520 synchronized (mGlobalLock) {
3521 buildAssistBundleLocked(pae, pae.result);
3522 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003523 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003524 }
3525 return pae.extras;
3526 }
3527
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003528 /**
3529 * Binder IPC calls go through the public entry point.
3530 * This can be called with or without the global lock held.
3531 */
3532 private static int checkCallingPermission(String permission) {
3533 return checkPermission(
3534 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3535 }
3536
3537 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003538 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003539 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3540 mAmInternal.enforceCallingPermission(permission, func);
3541 }
3542 }
3543
3544 @VisibleForTesting
3545 int checkGetTasksPermission(String permission, int pid, int uid) {
3546 return checkPermission(permission, pid, uid);
3547 }
3548
3549 static int checkPermission(String permission, int pid, int uid) {
3550 if (permission == null) {
3551 return PackageManager.PERMISSION_DENIED;
3552 }
3553 return checkComponentPermission(permission, pid, uid, -1, true);
3554 }
3555
Wale Ogunwale214f3482018-10-04 11:00:47 -07003556 public static int checkComponentPermission(String permission, int pid, int uid,
3557 int owningUid, boolean exported) {
3558 return ActivityManagerService.checkComponentPermission(
3559 permission, pid, uid, owningUid, exported);
3560 }
3561
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003562 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3563 if (getRecentTasks().isCallerRecents(callingUid)) {
3564 // Always allow the recents component to get tasks
3565 return true;
3566 }
3567
3568 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3569 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3570 if (!allowed) {
3571 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3572 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3573 // Temporary compatibility: some existing apps on the system image may
3574 // still be requesting the old permission and not switched to the new
3575 // one; if so, we'll still allow them full access. This means we need
3576 // to see if they are holding the old permission and are a system app.
3577 try {
3578 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3579 allowed = true;
3580 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3581 + " is using old GET_TASKS but privileged; allowing");
3582 }
3583 } catch (RemoteException e) {
3584 }
3585 }
3586 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3587 + " does not hold REAL_GET_TASKS; limiting output");
3588 }
3589 return allowed;
3590 }
3591
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3593 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3594 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3595 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003596 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003597 "enqueueAssistContext()");
3598
3599 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003600 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 if (activity == null) {
3602 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3603 return null;
3604 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003605 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3607 return null;
3608 }
3609 if (focused) {
3610 if (activityToken != null) {
3611 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3612 if (activity != caller) {
3613 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3614 + " is not current top " + activity);
3615 return null;
3616 }
3617 }
3618 } else {
3619 activity = ActivityRecord.forTokenLocked(activityToken);
3620 if (activity == null) {
3621 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3622 + " couldn't be found");
3623 return null;
3624 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003625 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3627 return null;
3628 }
3629 }
3630
3631 PendingAssistExtras pae;
3632 Bundle extras = new Bundle();
3633 if (args != null) {
3634 extras.putAll(args);
3635 }
3636 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003637 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638
3639 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3640 userHandle);
3641 pae.isHome = activity.isActivityTypeHome();
3642
3643 // Increment the sessionId if necessary
3644 if (newSessionId) {
3645 mViSessionId++;
3646 }
3647 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003648 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3649 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003651 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003652 } catch (RemoteException e) {
3653 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3654 return null;
3655 }
3656 return pae;
3657 }
3658 }
3659
3660 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3661 if (result != null) {
3662 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3663 }
3664 if (pae.hint != null) {
3665 pae.extras.putBoolean(pae.hint, true);
3666 }
3667 }
3668
3669 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3670 IAssistDataReceiver receiver;
3671 synchronized (mGlobalLock) {
3672 mPendingAssistExtras.remove(pae);
3673 receiver = pae.receiver;
3674 }
3675 if (receiver != null) {
3676 // Caller wants result sent back to them.
3677 Bundle sendBundle = new Bundle();
3678 // At least return the receiver extras
3679 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3680 try {
3681 pae.receiver.onHandleAssistData(sendBundle);
3682 } catch (RemoteException e) {
3683 }
3684 }
3685 }
3686
3687 public class PendingAssistExtras extends Binder implements Runnable {
3688 public final ActivityRecord activity;
3689 public boolean isHome;
3690 public final Bundle extras;
3691 public final Intent intent;
3692 public final String hint;
3693 public final IAssistDataReceiver receiver;
3694 public final int userHandle;
3695 public boolean haveResult = false;
3696 public Bundle result = null;
3697 public AssistStructure structure = null;
3698 public AssistContent content = null;
3699 public Bundle receiverExtras;
3700
3701 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3702 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3703 int _userHandle) {
3704 activity = _activity;
3705 extras = _extras;
3706 intent = _intent;
3707 hint = _hint;
3708 receiver = _receiver;
3709 receiverExtras = _receiverExtras;
3710 userHandle = _userHandle;
3711 }
3712
3713 @Override
3714 public void run() {
3715 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3716 synchronized (this) {
3717 haveResult = true;
3718 notifyAll();
3719 }
3720 pendingAssistExtrasTimedOut(this);
3721 }
3722 }
3723
3724 @Override
3725 public boolean isAssistDataAllowedOnCurrentActivity() {
3726 int userId;
3727 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003728 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3730 return false;
3731 }
3732
3733 final ActivityRecord activity = focusedStack.getTopActivity();
3734 if (activity == null) {
3735 return false;
3736 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003737 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 }
3739 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3740 }
3741
3742 @Override
3743 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3744 long ident = Binder.clearCallingIdentity();
3745 try {
3746 synchronized (mGlobalLock) {
3747 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003748 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 if (top != caller) {
3750 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3751 + " is not current top " + top);
3752 return false;
3753 }
3754 if (!top.nowVisible) {
3755 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3756 + " is not visible");
3757 return false;
3758 }
3759 }
3760 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3761 token);
3762 } finally {
3763 Binder.restoreCallingIdentity(ident);
3764 }
3765 }
3766
3767 @Override
3768 public boolean isRootVoiceInteraction(IBinder token) {
3769 synchronized (mGlobalLock) {
3770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3771 if (r == null) {
3772 return false;
3773 }
3774 return r.rootVoiceInteraction;
3775 }
3776 }
3777
Wale Ogunwalef6733932018-06-27 05:14:34 -07003778 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3779 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3780 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3781 if (activityToCallback == null) return;
3782 activityToCallback.setVoiceSessionLocked(voiceSession);
3783
3784 // Inform the activity
3785 try {
3786 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3787 voiceInteractor);
3788 long token = Binder.clearCallingIdentity();
3789 try {
3790 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3791 } finally {
3792 Binder.restoreCallingIdentity(token);
3793 }
3794 // TODO: VI Should we cache the activity so that it's easier to find later
3795 // rather than scan through all the stacks and activities?
3796 } catch (RemoteException re) {
3797 activityToCallback.clearVoiceSessionLocked();
3798 // TODO: VI Should this terminate the voice session?
3799 }
3800 }
3801
3802 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3803 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3804 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3805 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3806 boolean wasRunningVoice = mRunningVoice != null;
3807 mRunningVoice = session;
3808 if (!wasRunningVoice) {
3809 mVoiceWakeLock.acquire();
3810 updateSleepIfNeededLocked();
3811 }
3812 }
3813 }
3814
3815 void finishRunningVoiceLocked() {
3816 if (mRunningVoice != null) {
3817 mRunningVoice = null;
3818 mVoiceWakeLock.release();
3819 updateSleepIfNeededLocked();
3820 }
3821 }
3822
3823 @Override
3824 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3825 synchronized (mGlobalLock) {
3826 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3827 if (keepAwake) {
3828 mVoiceWakeLock.acquire();
3829 } else {
3830 mVoiceWakeLock.release();
3831 }
3832 }
3833 }
3834 }
3835
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 @Override
3837 public ComponentName getActivityClassForToken(IBinder token) {
3838 synchronized (mGlobalLock) {
3839 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3840 if (r == null) {
3841 return null;
3842 }
3843 return r.intent.getComponent();
3844 }
3845 }
3846
3847 @Override
3848 public String getPackageForToken(IBinder token) {
3849 synchronized (mGlobalLock) {
3850 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3851 if (r == null) {
3852 return null;
3853 }
3854 return r.packageName;
3855 }
3856 }
3857
3858 @Override
3859 public void showLockTaskEscapeMessage(IBinder token) {
3860 synchronized (mGlobalLock) {
3861 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3862 if (r == null) {
3863 return;
3864 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003865 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003866 }
3867 }
3868
3869 @Override
3870 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003871 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 final long token = Binder.clearCallingIdentity();
3873 try {
3874 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003875 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 }
3877 } finally {
3878 Binder.restoreCallingIdentity(token);
3879 }
3880 }
3881
3882 /**
3883 * Try to place task to provided position. The final position might be different depending on
3884 * current user and stacks state. The task will be moved to target stack if it's currently in
3885 * different stack.
3886 */
3887 @Override
3888 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003889 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890 synchronized (mGlobalLock) {
3891 long ident = Binder.clearCallingIdentity();
3892 try {
3893 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3894 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003895 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 if (task == null) {
3897 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3898 + taskId);
3899 }
3900
Wale Ogunwaled32da472018-11-16 07:19:28 -08003901 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003902
3903 if (stack == null) {
3904 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3905 + stackId);
3906 }
3907 if (!stack.isActivityTypeStandardOrUndefined()) {
3908 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3909 + " the position of task " + taskId + " in/to non-standard stack");
3910 }
3911
3912 // TODO: Have the callers of this API call a separate reparent method if that is
3913 // what they intended to do vs. having this method also do reparenting.
3914 if (task.getStack() == stack) {
3915 // Change position in current stack.
3916 stack.positionChildAt(task, position);
3917 } else {
3918 // Reparent to new stack.
3919 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3920 !DEFER_RESUME, "positionTaskInStack");
3921 }
3922 } finally {
3923 Binder.restoreCallingIdentity(ident);
3924 }
3925 }
3926 }
3927
3928 @Override
3929 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3930 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3931 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3932 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3933 synchronized (mGlobalLock) {
3934 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3935 if (record == null) {
3936 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3937 + "found for: " + token);
3938 }
3939 record.setSizeConfigurations(horizontalSizeConfiguration,
3940 verticalSizeConfigurations, smallestSizeConfigurations);
3941 }
3942 }
3943
3944 /**
3945 * Dismisses split-screen multi-window mode.
3946 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3947 */
3948 @Override
3949 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003950 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3952 final long ident = Binder.clearCallingIdentity();
3953 try {
3954 synchronized (mGlobalLock) {
3955 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003956 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003957 if (stack == null) {
3958 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3959 return;
3960 }
3961
3962 if (toTop) {
3963 // Caller wants the current split-screen primary stack to be the top stack after
3964 // it goes fullscreen, so move it to the front.
3965 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003966 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003967 // In this case the current split-screen primary stack shouldn't be the top
3968 // stack after it goes fullscreen, but it current has focus, so we move the
3969 // focus to the top-most split-screen secondary stack next to it.
3970 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3971 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3972 if (otherStack != null) {
3973 otherStack.moveToFront("dismissSplitScreenMode_other");
3974 }
3975 }
3976
Evan Rosky10475742018-09-05 19:02:48 -07003977 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(ident);
3981 }
3982 }
3983
3984 /**
3985 * Dismisses Pip
3986 * @param animate True if the dismissal should be animated.
3987 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3988 * default animation duration should be used.
3989 */
3990 @Override
3991 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 final long ident = Binder.clearCallingIdentity();
3994 try {
3995 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003996 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003997 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 if (stack == null) {
3999 Slog.w(TAG, "dismissPip: pinned stack not found.");
4000 return;
4001 }
4002 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4003 throw new IllegalArgumentException("Stack: " + stack
4004 + " doesn't support animated resize.");
4005 }
4006 if (animate) {
4007 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4008 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4009 } else {
4010 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4011 }
4012 }
4013 } finally {
4014 Binder.restoreCallingIdentity(ident);
4015 }
4016 }
4017
4018 @Override
4019 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004020 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 synchronized (mGlobalLock) {
4022 mSuppressResizeConfigChanges = suppress;
4023 }
4024 }
4025
4026 /**
4027 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4028 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4029 * activity and clearing the task at the same time.
4030 */
4031 @Override
4032 // TODO: API should just be about changing windowing modes...
4033 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 "moveTasksToFullscreenStack()");
4036 synchronized (mGlobalLock) {
4037 final long origId = Binder.clearCallingIdentity();
4038 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004039 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 if (stack != null){
4041 if (!stack.isActivityTypeStandardOrUndefined()) {
4042 throw new IllegalArgumentException(
4043 "You can't move tasks from non-standard stacks.");
4044 }
4045 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4046 }
4047 } finally {
4048 Binder.restoreCallingIdentity(origId);
4049 }
4050 }
4051 }
4052
4053 /**
4054 * Moves the top activity in the input stackId to the pinned stack.
4055 *
4056 * @param stackId Id of stack to move the top activity to pinned stack.
4057 * @param bounds Bounds to use for pinned stack.
4058 *
4059 * @return True if the top activity of the input stack was successfully moved to the pinned
4060 * stack.
4061 */
4062 @Override
4063 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004064 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 "moveTopActivityToPinnedStack()");
4066 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004067 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4069 + "Device doesn't support picture-in-picture mode");
4070 }
4071
4072 long ident = Binder.clearCallingIdentity();
4073 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004074 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 } finally {
4076 Binder.restoreCallingIdentity(ident);
4077 }
4078 }
4079 }
4080
4081 @Override
4082 public boolean isInMultiWindowMode(IBinder token) {
4083 final long origId = Binder.clearCallingIdentity();
4084 try {
4085 synchronized (mGlobalLock) {
4086 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4087 if (r == null) {
4088 return false;
4089 }
4090 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4091 return r.inMultiWindowMode();
4092 }
4093 } finally {
4094 Binder.restoreCallingIdentity(origId);
4095 }
4096 }
4097
4098 @Override
4099 public boolean isInPictureInPictureMode(IBinder token) {
4100 final long origId = Binder.clearCallingIdentity();
4101 try {
4102 synchronized (mGlobalLock) {
4103 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4104 }
4105 } finally {
4106 Binder.restoreCallingIdentity(origId);
4107 }
4108 }
4109
4110 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004111 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4112 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 return false;
4114 }
4115
4116 // If we are animating to fullscreen then we have already dispatched the PIP mode
4117 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004118 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4119 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 }
4121
4122 @Override
4123 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4124 final long origId = Binder.clearCallingIdentity();
4125 try {
4126 synchronized (mGlobalLock) {
4127 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4128 "enterPictureInPictureMode", token, params);
4129
4130 // If the activity is already in picture in picture mode, then just return early
4131 if (isInPictureInPictureMode(r)) {
4132 return true;
4133 }
4134
4135 // Activity supports picture-in-picture, now check that we can enter PiP at this
4136 // point, if it is
4137 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4138 false /* beforeStopping */)) {
4139 return false;
4140 }
4141
4142 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004143 synchronized (mGlobalLock) {
4144 // Only update the saved args from the args that are set
4145 r.pictureInPictureArgs.copyOnlySet(params);
4146 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4147 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4148 // Adjust the source bounds by the insets for the transition down
4149 final Rect sourceBounds = new Rect(
4150 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004151 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004152 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004153 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004154 stack.setPictureInPictureAspectRatio(aspectRatio);
4155 stack.setPictureInPictureActions(actions);
4156 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4157 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4158 logPictureInPictureArgs(params);
4159 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 };
4161
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004162 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 // If the keyguard is showing or occluded, then try and dismiss it before
4164 // entering picture-in-picture (this will prompt the user to authenticate if the
4165 // device is currently locked).
4166 dismissKeyguard(token, new KeyguardDismissCallback() {
4167 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004168 public void onDismissSucceeded() {
4169 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 }
4171 }, null /* message */);
4172 } else {
4173 // Enter picture in picture immediately otherwise
4174 enterPipRunnable.run();
4175 }
4176 return true;
4177 }
4178 } finally {
4179 Binder.restoreCallingIdentity(origId);
4180 }
4181 }
4182
4183 @Override
4184 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4185 final long origId = Binder.clearCallingIdentity();
4186 try {
4187 synchronized (mGlobalLock) {
4188 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4189 "setPictureInPictureParams", token, params);
4190
4191 // Only update the saved args from the args that are set
4192 r.pictureInPictureArgs.copyOnlySet(params);
4193 if (r.inPinnedWindowingMode()) {
4194 // If the activity is already in picture-in-picture, update the pinned stack now
4195 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4196 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004197 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198 if (!stack.isAnimatingBoundsToFullscreen()) {
4199 stack.setPictureInPictureAspectRatio(
4200 r.pictureInPictureArgs.getAspectRatio());
4201 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4202 }
4203 }
4204 logPictureInPictureArgs(params);
4205 }
4206 } finally {
4207 Binder.restoreCallingIdentity(origId);
4208 }
4209 }
4210
4211 @Override
4212 public int getMaxNumPictureInPictureActions(IBinder token) {
4213 // Currently, this is a static constant, but later, we may change this to be dependent on
4214 // the context of the activity
4215 return 3;
4216 }
4217
4218 private void logPictureInPictureArgs(PictureInPictureParams params) {
4219 if (params.hasSetActions()) {
4220 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4221 params.getActions().size());
4222 }
4223 if (params.hasSetAspectRatio()) {
4224 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4225 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4226 MetricsLogger.action(lm);
4227 }
4228 }
4229
4230 /**
4231 * Checks the state of the system and the activity associated with the given {@param token} to
4232 * verify that picture-in-picture is supported for that activity.
4233 *
4234 * @return the activity record for the given {@param token} if all the checks pass.
4235 */
4236 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4237 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004238 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 throw new IllegalStateException(caller
4240 + ": Device doesn't support picture-in-picture mode.");
4241 }
4242
4243 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4244 if (r == null) {
4245 throw new IllegalStateException(caller
4246 + ": Can't find activity for token=" + token);
4247 }
4248
4249 if (!r.supportsPictureInPicture()) {
4250 throw new IllegalStateException(caller
4251 + ": Current activity does not support picture-in-picture.");
4252 }
4253
4254 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004255 && !mWindowManager.isValidPictureInPictureAspectRatio(
4256 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 final float minAspectRatio = mContext.getResources().getFloat(
4258 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4259 final float maxAspectRatio = mContext.getResources().getFloat(
4260 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4261 throw new IllegalArgumentException(String.format(caller
4262 + ": Aspect ratio is too extreme (must be between %f and %f).",
4263 minAspectRatio, maxAspectRatio));
4264 }
4265
4266 // Truncate the number of actions if necessary
4267 params.truncateActions(getMaxNumPictureInPictureActions(token));
4268
4269 return r;
4270 }
4271
4272 @Override
4273 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004274 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 synchronized (mGlobalLock) {
4276 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4277 if (r == null) {
4278 throw new IllegalArgumentException("Activity does not exist; token="
4279 + activityToken);
4280 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004281 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282 }
4283 }
4284
4285 @Override
4286 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4287 Rect tempDockedTaskInsetBounds,
4288 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004289 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290 long ident = Binder.clearCallingIdentity();
4291 try {
4292 synchronized (mGlobalLock) {
4293 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4294 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4295 PRESERVE_WINDOWS);
4296 }
4297 } finally {
4298 Binder.restoreCallingIdentity(ident);
4299 }
4300 }
4301
4302 @Override
4303 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004304 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004305 final long ident = Binder.clearCallingIdentity();
4306 try {
4307 synchronized (mGlobalLock) {
4308 mStackSupervisor.setSplitScreenResizing(resizing);
4309 }
4310 } finally {
4311 Binder.restoreCallingIdentity(ident);
4312 }
4313 }
4314
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004315 /**
4316 * Check that we have the features required for VR-related API calls, and throw an exception if
4317 * not.
4318 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004319 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004320 if (!mContext.getPackageManager().hasSystemFeature(
4321 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4322 throw new UnsupportedOperationException("VR mode not supported on this device!");
4323 }
4324 }
4325
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004326 @Override
4327 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004328 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329
4330 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4331
4332 ActivityRecord r;
4333 synchronized (mGlobalLock) {
4334 r = ActivityRecord.isInStackLocked(token);
4335 }
4336
4337 if (r == null) {
4338 throw new IllegalArgumentException();
4339 }
4340
4341 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004342 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 VrManagerInternal.NO_ERROR) {
4344 return err;
4345 }
4346
4347 // Clear the binder calling uid since this path may call moveToTask().
4348 final long callingId = Binder.clearCallingIdentity();
4349 try {
4350 synchronized (mGlobalLock) {
4351 r.requestedVrComponent = (enabled) ? packageName : null;
4352
4353 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004354 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004355 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 }
4357 return 0;
4358 }
4359 } finally {
4360 Binder.restoreCallingIdentity(callingId);
4361 }
4362 }
4363
4364 @Override
4365 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4366 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4367 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004368 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4370 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4371 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004372 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 || activity.voiceSession != null) {
4374 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4375 return;
4376 }
4377 if (activity.pendingVoiceInteractionStart) {
4378 Slog.w(TAG, "Pending start of voice interaction already.");
4379 return;
4380 }
4381 activity.pendingVoiceInteractionStart = true;
4382 }
4383 LocalServices.getService(VoiceInteractionManagerInternal.class)
4384 .startLocalVoiceInteraction(callingActivity, options);
4385 }
4386
4387 @Override
4388 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4389 LocalServices.getService(VoiceInteractionManagerInternal.class)
4390 .stopLocalVoiceInteraction(callingActivity);
4391 }
4392
4393 @Override
4394 public boolean supportsLocalVoiceInteraction() {
4395 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4396 .supportsLocalVoiceInteraction();
4397 }
4398
4399 /** Notifies all listeners when the pinned stack animation starts. */
4400 @Override
4401 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004402 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 }
4404
4405 /** Notifies all listeners when the pinned stack animation ends. */
4406 @Override
4407 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004408 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 }
4410
4411 @Override
4412 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 final long ident = Binder.clearCallingIdentity();
4415 try {
4416 synchronized (mGlobalLock) {
4417 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4418 }
4419 } finally {
4420 Binder.restoreCallingIdentity(ident);
4421 }
4422 }
4423
4424 @Override
4425 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427
4428 synchronized (mGlobalLock) {
4429 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004430 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 // Call might come when display is not yet added or has already been removed.
4432 if (DEBUG_CONFIGURATION) {
4433 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4434 + displayId);
4435 }
4436 return false;
4437 }
4438
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 }
4443
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004445 final Message msg = PooledLambda.obtainMessage(
4446 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4447 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 }
4449
4450 final long origId = Binder.clearCallingIdentity();
4451 try {
4452 if (values != null) {
4453 Settings.System.clearConfiguration(values);
4454 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4457 return mTmpUpdateConfigurationResult.changes != 0;
4458 } finally {
4459 Binder.restoreCallingIdentity(origId);
4460 }
4461 }
4462 }
4463
4464 @Override
4465 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004466 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467
4468 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004469 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004470 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004471 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 }
4473
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004474 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004475 final Message msg = PooledLambda.obtainMessage(
4476 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4477 DEFAULT_DISPLAY);
4478 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479 }
4480
4481 final long origId = Binder.clearCallingIdentity();
4482 try {
4483 if (values != null) {
4484 Settings.System.clearConfiguration(values);
4485 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004486 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487 UserHandle.USER_NULL, false /* deferResume */,
4488 mTmpUpdateConfigurationResult);
4489 return mTmpUpdateConfigurationResult.changes != 0;
4490 } finally {
4491 Binder.restoreCallingIdentity(origId);
4492 }
4493 }
4494 }
4495
4496 @Override
4497 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4498 CharSequence message) {
4499 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4502 }
4503 final long callingId = Binder.clearCallingIdentity();
4504 try {
4505 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004506 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 }
4508 } finally {
4509 Binder.restoreCallingIdentity(callingId);
4510 }
4511 }
4512
4513 @Override
4514 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004515 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 "cancelTaskWindowTransition()");
4517 final long ident = Binder.clearCallingIdentity();
4518 try {
4519 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004520 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 MATCH_TASK_IN_STACKS_ONLY);
4522 if (task == null) {
4523 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4524 return;
4525 }
4526 task.cancelWindowTransition();
4527 }
4528 } finally {
4529 Binder.restoreCallingIdentity(ident);
4530 }
4531 }
4532
4533 @Override
4534 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004535 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004536 final long ident = Binder.clearCallingIdentity();
4537 try {
4538 final TaskRecord task;
4539 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004540 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004541 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4542 if (task == null) {
4543 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4544 return null;
4545 }
4546 }
4547 // Don't call this while holding the lock as this operation might hit the disk.
4548 return task.getSnapshot(reducedResolution);
4549 } finally {
4550 Binder.restoreCallingIdentity(ident);
4551 }
4552 }
4553
4554 @Override
4555 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4556 synchronized (mGlobalLock) {
4557 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4558 if (r == null) {
4559 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4560 + token);
4561 return;
4562 }
4563 final long origId = Binder.clearCallingIdentity();
4564 try {
4565 r.setDisablePreviewScreenshots(disable);
4566 } finally {
4567 Binder.restoreCallingIdentity(origId);
4568 }
4569 }
4570 }
4571
4572 /** Return the user id of the last resumed activity. */
4573 @Override
4574 public @UserIdInt
4575 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004576 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004577 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4578 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004579 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004580 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004582 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 }
4584 }
4585
4586 @Override
4587 public void updateLockTaskFeatures(int userId, int flags) {
4588 final int callingUid = Binder.getCallingUid();
4589 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 "updateLockTaskFeatures()");
4592 }
4593 synchronized (mGlobalLock) {
4594 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4595 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004596 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 }
4598 }
4599
4600 @Override
4601 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4602 synchronized (mGlobalLock) {
4603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4604 if (r == null) {
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 r.setShowWhenLocked(showWhenLocked);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004617 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4618 synchronized (mGlobalLock) {
4619 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4620 if (r == null) {
4621 return;
4622 }
4623 final long origId = Binder.clearCallingIdentity();
4624 try {
4625 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4626 } finally {
4627 Binder.restoreCallingIdentity(origId);
4628 }
4629 }
4630 }
4631
4632 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4634 synchronized (mGlobalLock) {
4635 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4636 if (r == null) {
4637 return;
4638 }
4639 final long origId = Binder.clearCallingIdentity();
4640 try {
4641 r.setTurnScreenOn(turnScreenOn);
4642 } finally {
4643 Binder.restoreCallingIdentity(origId);
4644 }
4645 }
4646 }
4647
4648 @Override
4649 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004651 "registerRemoteAnimations");
4652 definition.setCallingPid(Binder.getCallingPid());
4653 synchronized (mGlobalLock) {
4654 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4655 if (r == null) {
4656 return;
4657 }
4658 final long origId = Binder.clearCallingIdentity();
4659 try {
4660 r.registerRemoteAnimations(definition);
4661 } finally {
4662 Binder.restoreCallingIdentity(origId);
4663 }
4664 }
4665 }
4666
4667 @Override
4668 public void registerRemoteAnimationForNextActivityStart(String packageName,
4669 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004670 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004671 "registerRemoteAnimationForNextActivityStart");
4672 adapter.setCallingPid(Binder.getCallingPid());
4673 synchronized (mGlobalLock) {
4674 final long origId = Binder.clearCallingIdentity();
4675 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004676 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004677 packageName, adapter);
4678 } finally {
4679 Binder.restoreCallingIdentity(origId);
4680 }
4681 }
4682 }
4683
Evan Rosky966759f2019-01-15 10:33:58 -08004684 @Override
4685 public void registerRemoteAnimationsForDisplay(int displayId,
4686 RemoteAnimationDefinition definition) {
4687 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4688 "registerRemoteAnimations");
4689 definition.setCallingPid(Binder.getCallingPid());
4690 synchronized (mGlobalLock) {
4691 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4692 if (display == null) {
4693 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4694 return;
4695 }
4696 final long origId = Binder.clearCallingIdentity();
4697 try {
4698 display.mDisplayContent.registerRemoteAnimations(definition);
4699 } finally {
4700 Binder.restoreCallingIdentity(origId);
4701 }
4702 }
4703 }
4704
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004705 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4706 @Override
4707 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4708 synchronized (mGlobalLock) {
4709 final long origId = Binder.clearCallingIdentity();
4710 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004711 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004712 } finally {
4713 Binder.restoreCallingIdentity(origId);
4714 }
4715 }
4716 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004717
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 @Override
4719 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004720 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004722 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004723 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004724 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 }
4726 }
4727
4728 @Override
4729 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004730 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 != PERMISSION_GRANTED) {
4732 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4733 + Binder.getCallingPid()
4734 + ", uid=" + Binder.getCallingUid()
4735 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4736 Slog.w(TAG, msg);
4737 throw new SecurityException(msg);
4738 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004739 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004740 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004741 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004742 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004743 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 }
4745 }
4746
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004747 @Override
4748 public void stopAppSwitches() {
4749 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4750 synchronized (mGlobalLock) {
4751 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4752 mDidAppSwitch = false;
4753 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4754 }
4755 }
4756
4757 @Override
4758 public void resumeAppSwitches() {
4759 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4760 synchronized (mGlobalLock) {
4761 // Note that we don't execute any pending app switches... we will
4762 // let those wait until either the timeout, or the next start
4763 // activity request.
4764 mAppSwitchesAllowedTime = 0;
4765 }
4766 }
4767
4768 void onStartActivitySetDidAppSwitch() {
4769 if (mDidAppSwitch) {
4770 // This is the second allowed switch since we stopped switches, so now just generally
4771 // allow switches. Use case:
4772 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4773 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4774 // anyone to switch again).
4775 mAppSwitchesAllowedTime = 0;
4776 } else {
4777 mDidAppSwitch = true;
4778 }
4779 }
4780
4781 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 boolean shouldDisableNonVrUiLocked() {
4783 return mVrController.shouldDisableNonVrUiLocked();
4784 }
4785
Wale Ogunwale53783742018-09-16 10:21:51 -07004786 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004787 // VR apps are expected to run in a main display. If an app is turning on VR for
4788 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4789 // fullscreen stack before enabling VR Mode.
4790 // TODO: The goal of this code is to keep the VR app on the main display. When the
4791 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4792 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4793 // option would be a better choice here.
4794 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4795 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4796 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004797 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004798 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004799 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004800 }
4801 mH.post(() -> {
4802 if (!mVrController.onVrModeChanged(r)) {
4803 return;
4804 }
4805 synchronized (mGlobalLock) {
4806 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4807 mWindowManager.disableNonVrUi(disableNonVrUi);
4808 if (disableNonVrUi) {
4809 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4810 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004811 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004812 }
4813 }
4814 });
4815 }
4816
Wale Ogunwale53783742018-09-16 10:21:51 -07004817 @Override
4818 public int getPackageScreenCompatMode(String packageName) {
4819 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4820 synchronized (mGlobalLock) {
4821 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4822 }
4823 }
4824
4825 @Override
4826 public void setPackageScreenCompatMode(String packageName, int mode) {
4827 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4828 "setPackageScreenCompatMode");
4829 synchronized (mGlobalLock) {
4830 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4831 }
4832 }
4833
4834 @Override
4835 public boolean getPackageAskScreenCompat(String packageName) {
4836 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4837 synchronized (mGlobalLock) {
4838 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4839 }
4840 }
4841
4842 @Override
4843 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4844 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4845 "setPackageAskScreenCompat");
4846 synchronized (mGlobalLock) {
4847 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4848 }
4849 }
4850
Wale Ogunwale64258362018-10-16 15:13:37 -07004851 public static String relaunchReasonToString(int relaunchReason) {
4852 switch (relaunchReason) {
4853 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4854 return "window_resize";
4855 case RELAUNCH_REASON_FREE_RESIZE:
4856 return "free_resize";
4857 default:
4858 return null;
4859 }
4860 }
4861
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004862 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004863 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004864 }
4865
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004866 /** Pokes the task persister. */
4867 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4868 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4869 }
4870
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004871 boolean isKeyguardLocked() {
4872 return mKeyguardController.isKeyguardLocked();
4873 }
4874
Garfield Tan01548632018-11-27 10:15:48 -08004875 /**
4876 * Clears launch params for the given package.
4877 * @param packageNames the names of the packages of which the launch params are to be cleared
4878 */
4879 @Override
4880 public void clearLaunchParamsForPackages(List<String> packageNames) {
4881 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4882 "clearLaunchParamsForPackages");
4883 synchronized (mGlobalLock) {
4884 for (int i = 0; i < packageNames.size(); ++i) {
4885 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4886 }
4887 }
4888 }
4889
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004890 /**
4891 * Makes the display with the given id a single task instance display. I.e the display can only
4892 * contain one task.
4893 */
4894 @Override
4895 public void setDisplayToSingleTaskInstance(int displayId) {
4896 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4897 "setDisplayToSingleTaskInstance");
4898 final long origId = Binder.clearCallingIdentity();
4899 try {
4900 final ActivityDisplay display =
4901 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4902 if (display != null) {
4903 display.setDisplayToSingleTaskInstance();
4904 }
4905 } finally {
4906 Binder.restoreCallingIdentity(origId);
4907 }
4908 }
4909
Wale Ogunwale31913b52018-10-13 08:29:31 -07004910 void dumpLastANRLocked(PrintWriter pw) {
4911 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4912 if (mLastANRState == null) {
4913 pw.println(" <no ANR has occurred since boot>");
4914 } else {
4915 pw.println(mLastANRState);
4916 }
4917 }
4918
4919 void dumpLastANRTracesLocked(PrintWriter pw) {
4920 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4921
4922 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4923 if (ArrayUtils.isEmpty(files)) {
4924 pw.println(" <no ANR has occurred since boot>");
4925 return;
4926 }
4927 // Find the latest file.
4928 File latest = null;
4929 for (File f : files) {
4930 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4931 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004932 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004933 }
4934 pw.print("File: ");
4935 pw.print(latest.getName());
4936 pw.println();
4937 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4938 String line;
4939 while ((line = in.readLine()) != null) {
4940 pw.println(line);
4941 }
4942 } catch (IOException e) {
4943 pw.print("Unable to read: ");
4944 pw.print(e);
4945 pw.println();
4946 }
4947 }
4948
4949 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4950 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4951 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4952 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4953 }
4954
4955 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4956 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4957 pw.println(header);
4958
Wale Ogunwaled32da472018-11-16 07:19:28 -08004959 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004960 dumpPackage);
4961 boolean needSep = printedAnything;
4962
4963 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004964 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004965 " ResumedActivity: ");
4966 if (printed) {
4967 printedAnything = true;
4968 needSep = false;
4969 }
4970
4971 if (dumpPackage == null) {
4972 if (needSep) {
4973 pw.println();
4974 }
4975 printedAnything = true;
4976 mStackSupervisor.dump(pw, " ");
4977 }
4978
4979 if (!printedAnything) {
4980 pw.println(" (nothing)");
4981 }
4982 }
4983
4984 void dumpActivityContainersLocked(PrintWriter pw) {
4985 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004986 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004987 pw.println(" ");
4988 }
4989
4990 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4991 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4992 getActivityStartController().dump(pw, "", dumpPackage);
4993 }
4994
4995 /**
4996 * There are three things that cmd can be:
4997 * - a flattened component name that matches an existing activity
4998 * - the cmd arg isn't the flattened component name of an existing activity:
4999 * dump all activity whose component contains the cmd as a substring
5000 * - A hex number of the ActivityRecord object instance.
5001 *
5002 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5003 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5004 */
5005 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5006 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5007 ArrayList<ActivityRecord> activities;
5008
5009 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005010 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005011 dumpFocusedStackOnly);
5012 }
5013
5014 if (activities.size() <= 0) {
5015 return false;
5016 }
5017
5018 String[] newArgs = new String[args.length - opti];
5019 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5020
5021 TaskRecord lastTask = null;
5022 boolean needSep = false;
5023 for (int i = activities.size() - 1; i >= 0; i--) {
5024 ActivityRecord r = activities.get(i);
5025 if (needSep) {
5026 pw.println();
5027 }
5028 needSep = true;
5029 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005030 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005031 if (lastTask != task) {
5032 lastTask = task;
5033 pw.print("TASK "); pw.print(lastTask.affinity);
5034 pw.print(" id="); pw.print(lastTask.taskId);
5035 pw.print(" userId="); pw.println(lastTask.userId);
5036 if (dumpAll) {
5037 lastTask.dump(pw, " ");
5038 }
5039 }
5040 }
5041 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5042 }
5043 return true;
5044 }
5045
5046 /**
5047 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5048 * there is a thread associated with the activity.
5049 */
5050 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5051 final ActivityRecord r, String[] args, boolean dumpAll) {
5052 String innerPrefix = prefix + " ";
5053 synchronized (mGlobalLock) {
5054 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5055 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5056 pw.print(" pid=");
5057 if (r.hasProcess()) pw.println(r.app.getPid());
5058 else pw.println("(not running)");
5059 if (dumpAll) {
5060 r.dump(pw, innerPrefix);
5061 }
5062 }
5063 if (r.attachedToProcess()) {
5064 // flush anything that is already in the PrintWriter since the thread is going
5065 // to write to the file descriptor directly
5066 pw.flush();
5067 try {
5068 TransferPipe tp = new TransferPipe();
5069 try {
5070 r.app.getThread().dumpActivity(tp.getWriteFd(),
5071 r.appToken, innerPrefix, args);
5072 tp.go(fd);
5073 } finally {
5074 tp.kill();
5075 }
5076 } catch (IOException e) {
5077 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5078 } catch (RemoteException e) {
5079 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5080 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005081 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005082 }
5083
sanryhuang498e77e2018-12-06 14:57:01 +08005084 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5085 boolean testPssMode) {
5086 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5087 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5088 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005089 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005090 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5091 st.toString());
5092 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005093 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5094 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5095 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005096 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5097 testPssMode);
5098 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005099 }
5100
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005101 int getCurrentUserId() {
5102 return mAmInternal.getCurrentUserId();
5103 }
5104
5105 private void enforceNotIsolatedCaller(String caller) {
5106 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5107 throw new SecurityException("Isolated process not allowed to call " + caller);
5108 }
5109 }
5110
Wale Ogunwalef6733932018-06-27 05:14:34 -07005111 public Configuration getConfiguration() {
5112 Configuration ci;
5113 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005114 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005115 ci.userSetLocale = false;
5116 }
5117 return ci;
5118 }
5119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005120 /**
5121 * Current global configuration information. Contains general settings for the entire system,
5122 * also corresponds to the merged configuration of the default display.
5123 */
5124 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005125 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005126 }
5127
5128 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5129 boolean initLocale) {
5130 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5131 }
5132
5133 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5134 boolean initLocale, boolean deferResume) {
5135 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5136 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5137 UserHandle.USER_NULL, deferResume);
5138 }
5139
Wale Ogunwale59507092018-10-29 09:00:30 -07005140 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005141 final long origId = Binder.clearCallingIdentity();
5142 try {
5143 synchronized (mGlobalLock) {
5144 updateConfigurationLocked(values, null, false, true, userId,
5145 false /* deferResume */);
5146 }
5147 } finally {
5148 Binder.restoreCallingIdentity(origId);
5149 }
5150 }
5151
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5153 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5154 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5155 deferResume, null /* result */);
5156 }
5157
5158 /**
5159 * Do either or both things: (1) change the current configuration, and (2)
5160 * make sure the given activity is running with the (now) current
5161 * configuration. Returns true if the activity has been left running, or
5162 * false if <var>starting</var> is being destroyed to match the new
5163 * configuration.
5164 *
5165 * @param userId is only used when persistent parameter is set to true to persist configuration
5166 * for that particular user
5167 */
5168 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5169 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5170 ActivityTaskManagerService.UpdateConfigurationResult result) {
5171 int changes = 0;
5172 boolean kept = true;
5173
5174 if (mWindowManager != null) {
5175 mWindowManager.deferSurfaceLayout();
5176 }
5177 try {
5178 if (values != null) {
5179 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5180 deferResume);
5181 }
5182
5183 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5184 } finally {
5185 if (mWindowManager != null) {
5186 mWindowManager.continueSurfaceLayout();
5187 }
5188 }
5189
5190 if (result != null) {
5191 result.changes = changes;
5192 result.activityRelaunched = !kept;
5193 }
5194 return kept;
5195 }
5196
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197 /** Update default (global) configuration and notify listeners about changes. */
5198 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5199 boolean persistent, int userId, boolean deferResume) {
5200 mTempConfig.setTo(getGlobalConfiguration());
5201 final int changes = mTempConfig.updateFrom(values);
5202 if (changes == 0) {
5203 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5204 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5205 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5206 // (even if there are no actual changes) to unfreeze the window.
5207 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5208 return 0;
5209 }
5210
5211 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5212 "Updating global configuration to: " + values);
5213
5214 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5215 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5216 values.colorMode,
5217 values.densityDpi,
5218 values.fontScale,
5219 values.hardKeyboardHidden,
5220 values.keyboard,
5221 values.keyboardHidden,
5222 values.mcc,
5223 values.mnc,
5224 values.navigation,
5225 values.navigationHidden,
5226 values.orientation,
5227 values.screenHeightDp,
5228 values.screenLayout,
5229 values.screenWidthDp,
5230 values.smallestScreenWidthDp,
5231 values.touchscreen,
5232 values.uiMode);
5233
5234
5235 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5236 final LocaleList locales = values.getLocales();
5237 int bestLocaleIndex = 0;
5238 if (locales.size() > 1) {
5239 if (mSupportedSystemLocales == null) {
5240 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5241 }
5242 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5243 }
5244 SystemProperties.set("persist.sys.locale",
5245 locales.get(bestLocaleIndex).toLanguageTag());
5246 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005247
5248 final Message m = PooledLambda.obtainMessage(
5249 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5250 locales.get(bestLocaleIndex));
5251 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252 }
5253
Yunfan Chen75157d72018-07-27 14:47:21 +09005254 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005255
5256 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005257 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258
5259 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5260 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005261 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262
5263 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005264 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265
5266 AttributeCache ac = AttributeCache.instance();
5267 if (ac != null) {
5268 ac.updateConfiguration(mTempConfig);
5269 }
5270
5271 // Make sure all resources in our process are updated right now, so that anyone who is going
5272 // to retrieve resource values after we return will be sure to get the new ones. This is
5273 // especially important during boot, where the first config change needs to guarantee all
5274 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005275 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005276
5277 // We need another copy of global config because we're scheduling some calls instead of
5278 // running them in place. We need to be sure that object we send will be handled unchanged.
5279 final Configuration configCopy = new Configuration(mTempConfig);
5280 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005281 final Message msg = PooledLambda.obtainMessage(
5282 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5283 this, userId, configCopy);
5284 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285 }
5286
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005287 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5288 for (int i = pidMap.size() - 1; i >= 0; i--) {
5289 final int pid = pidMap.keyAt(i);
5290 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005291 if (DEBUG_CONFIGURATION) {
5292 Slog.v(TAG_CONFIGURATION, "Update process config of "
5293 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005295 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005296 }
5297
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005298 final Message msg = PooledLambda.obtainMessage(
5299 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5300 mAmInternal, changes, initLocale);
5301 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302
5303 // Override configuration of the default display duplicates global config, so we need to
5304 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005305 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306 DEFAULT_DISPLAY);
5307
5308 return changes;
5309 }
5310
5311 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5312 boolean deferResume, int displayId) {
5313 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5314 displayId, null /* result */);
5315 }
5316
5317 /**
5318 * Updates override configuration specific for the selected display. If no config is provided,
5319 * new one will be computed in WM based on current display info.
5320 */
5321 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5322 ActivityRecord starting, boolean deferResume, int displayId,
5323 ActivityTaskManagerService.UpdateConfigurationResult result) {
5324 int changes = 0;
5325 boolean kept = true;
5326
5327 if (mWindowManager != null) {
5328 mWindowManager.deferSurfaceLayout();
5329 }
5330 try {
5331 if (values != null) {
5332 if (displayId == DEFAULT_DISPLAY) {
5333 // Override configuration of the default display duplicates global config, so
5334 // we're calling global config update instead for default display. It will also
5335 // apply the correct override config.
5336 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5337 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5338 } else {
5339 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5340 }
5341 }
5342
5343 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5344 } finally {
5345 if (mWindowManager != null) {
5346 mWindowManager.continueSurfaceLayout();
5347 }
5348 }
5349
5350 if (result != null) {
5351 result.changes = changes;
5352 result.activityRelaunched = !kept;
5353 }
5354 return kept;
5355 }
5356
5357 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5358 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005359 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005360 final int changes = mTempConfig.updateFrom(values);
5361 if (changes != 0) {
5362 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5363 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005364 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005365
5366 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5367 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005368 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369
Wale Ogunwale5c918702018-10-18 11:06:33 -07005370 // Post message to start process to avoid possible deadlock of calling into AMS with
5371 // the ATMS lock held.
5372 final Message msg = PooledLambda.obtainMessage(
5373 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005374 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005375 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005376 }
5377 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005378 return changes;
5379 }
5380
Wale Ogunwalef6733932018-06-27 05:14:34 -07005381 private void updateEventDispatchingLocked(boolean booted) {
5382 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5383 }
5384
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005385 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5386 final ContentResolver resolver = mContext.getContentResolver();
5387 Settings.System.putConfigurationForUser(resolver, config, userId);
5388 }
5389
5390 private void sendLocaleToMountDaemonMsg(Locale l) {
5391 try {
5392 IBinder service = ServiceManager.getService("mount");
5393 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5394 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5395 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5396 } catch (RemoteException e) {
5397 Log.e(TAG, "Error storing locale for decryption UI", e);
5398 }
5399 }
5400
Alison Cichowlas3e340502018-08-07 17:15:01 -04005401 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5402 mStartActivitySources.remove(permissionToken);
5403 mExpiredStartAsCallerTokens.add(permissionToken);
5404 }
5405
5406 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5407 mExpiredStartAsCallerTokens.remove(permissionToken);
5408 }
5409
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005410 boolean isActivityStartsLoggingEnabled() {
5411 return mAmInternal.isActivityStartsLoggingEnabled();
5412 }
5413
Michal Karpinski8596ded2018-11-14 14:43:48 +00005414 boolean isBackgroundActivityStartsEnabled() {
5415 return mAmInternal.isBackgroundActivityStartsEnabled();
5416 }
5417
Ricky Waiaca8a772019-04-04 16:01:06 +01005418 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5419 if (packageName == null) {
5420 return false;
5421 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005422 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5423 }
5424
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 void enableScreenAfterBoot(boolean booted) {
5426 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5427 SystemClock.uptimeMillis());
5428 mWindowManager.enableScreenAfterBoot();
5429
5430 synchronized (mGlobalLock) {
5431 updateEventDispatchingLocked(booted);
5432 }
5433 }
5434
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005435 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5436 if (r == null || !r.hasProcess()) {
5437 return KEY_DISPATCHING_TIMEOUT_MS;
5438 }
5439 return getInputDispatchingTimeoutLocked(r.app);
5440 }
5441
5442 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005443 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005444 }
5445
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 /**
5447 * Decide based on the configuration whether we should show the ANR,
5448 * crash, etc dialogs. The idea is that if there is no affordance to
5449 * press the on-screen buttons, or the user experience would be more
5450 * greatly impacted than the crash itself, we shouldn't show the dialog.
5451 *
5452 * A thought: SystemUI might also want to get told about this, the Power
5453 * dialog / global actions also might want different behaviors.
5454 */
5455 private void updateShouldShowDialogsLocked(Configuration config) {
5456 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5457 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5458 && config.navigation == Configuration.NAVIGATION_NONAV);
5459 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5460 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5461 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5462 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5463 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5464 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5465 HIDE_ERROR_DIALOGS, 0) != 0;
5466 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5467 }
5468
5469 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5470 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5471 FONT_SCALE, 1.0f, userId);
5472
5473 synchronized (this) {
5474 if (getGlobalConfiguration().fontScale == scaleFactor) {
5475 return;
5476 }
5477
5478 final Configuration configuration
5479 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5480 configuration.fontScale = scaleFactor;
5481 updatePersistentConfiguration(configuration, userId);
5482 }
5483 }
5484
5485 // Actually is sleeping or shutting down or whatever else in the future
5486 // is an inactive state.
5487 boolean isSleepingOrShuttingDownLocked() {
5488 return isSleepingLocked() || mShuttingDown;
5489 }
5490
5491 boolean isSleepingLocked() {
5492 return mSleeping;
5493 }
5494
Riddle Hsu16567132018-08-16 21:37:47 +08005495 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005496 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005497 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005498 if (task.isActivityTypeStandard()) {
5499 if (mCurAppTimeTracker != r.appTimeTracker) {
5500 // We are switching app tracking. Complete the current one.
5501 if (mCurAppTimeTracker != null) {
5502 mCurAppTimeTracker.stop();
5503 mH.obtainMessage(
5504 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005505 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 mCurAppTimeTracker = null;
5507 }
5508 if (r.appTimeTracker != null) {
5509 mCurAppTimeTracker = r.appTimeTracker;
5510 startTimeTrackingFocusedActivityLocked();
5511 }
5512 } else {
5513 startTimeTrackingFocusedActivityLocked();
5514 }
5515 } else {
5516 r.appTimeTracker = null;
5517 }
5518 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5519 // TODO: Probably not, because we don't want to resume voice on switching
5520 // back to this activity
5521 if (task.voiceInteractor != null) {
5522 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5523 } else {
5524 finishRunningVoiceLocked();
5525
5526 if (mLastResumedActivity != null) {
5527 final IVoiceInteractionSession session;
5528
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005529 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005530 if (lastResumedActivityTask != null
5531 && lastResumedActivityTask.voiceSession != null) {
5532 session = lastResumedActivityTask.voiceSession;
5533 } else {
5534 session = mLastResumedActivity.voiceSession;
5535 }
5536
5537 if (session != null) {
5538 // We had been in a voice interaction session, but now focused has
5539 // move to something different. Just finish the session, we can't
5540 // return to it and retain the proper state and synchronization with
5541 // the voice interaction service.
5542 finishVoiceTask(session);
5543 }
5544 }
5545 }
5546
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005547 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5548 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 }
5550 updateResumedAppTrace(r);
5551 mLastResumedActivity = r;
5552
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005553 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554
5555 applyUpdateLockStateLocked(r);
5556 applyUpdateVrModeLocked(r);
5557
5558 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005559 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005560 r == null ? "NULL" : r.shortComponentName,
5561 reason);
5562 }
5563
5564 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5565 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005566 final ActivityTaskManagerInternal.SleepToken token =
5567 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568 updateSleepIfNeededLocked();
5569 return token;
5570 }
5571 }
5572
5573 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005574 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005575 final boolean wasSleeping = mSleeping;
5576 boolean updateOomAdj = false;
5577
5578 if (!shouldSleep) {
5579 // If wasSleeping is true, we need to wake up activity manager state from when
5580 // we started sleeping. In either case, we need to apply the sleep tokens, which
5581 // will wake up stacks or put them to sleep as appropriate.
5582 if (wasSleeping) {
5583 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005584 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5585 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005586 startTimeTrackingFocusedActivityLocked();
5587 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005588 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5590 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005591 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 if (wasSleeping) {
5593 updateOomAdj = true;
5594 }
5595 } else if (!mSleeping && shouldSleep) {
5596 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005597 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5598 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005599 if (mCurAppTimeTracker != null) {
5600 mCurAppTimeTracker.stop();
5601 }
5602 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005603 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005604 mStackSupervisor.goingToSleepLocked();
5605 updateResumedAppTrace(null /* resumed */);
5606 updateOomAdj = true;
5607 }
5608 if (updateOomAdj) {
5609 mH.post(mAmInternal::updateOomAdj);
5610 }
5611 }
5612
5613 void updateOomAdj() {
5614 mH.post(mAmInternal::updateOomAdj);
5615 }
5616
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 void updateCpuStats() {
5618 mH.post(mAmInternal::updateCpuStats);
5619 }
5620
Hui Yu03d12402018-12-06 18:00:37 -08005621 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5622 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005623 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5624 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005625 mH.sendMessage(m);
5626 }
5627
Hui Yu03d12402018-12-06 18:00:37 -08005628 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005629 ComponentName taskRoot = null;
5630 final TaskRecord task = activity.getTaskRecord();
5631 if (task != null) {
5632 final ActivityRecord rootActivity = task.getRootActivity();
5633 if (rootActivity != null) {
5634 taskRoot = rootActivity.mActivityComponent;
5635 }
5636 }
5637
Hui Yu03d12402018-12-06 18:00:37 -08005638 final Message m = PooledLambda.obtainMessage(
5639 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005640 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005641 mH.sendMessage(m);
5642 }
5643
Wale Ogunwale53783742018-09-16 10:21:51 -07005644 void setBooting(boolean booting) {
5645 mAmInternal.setBooting(booting);
5646 }
5647
5648 boolean isBooting() {
5649 return mAmInternal.isBooting();
5650 }
5651
5652 void setBooted(boolean booted) {
5653 mAmInternal.setBooted(booted);
5654 }
5655
5656 boolean isBooted() {
5657 return mAmInternal.isBooted();
5658 }
5659
5660 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5661 mH.post(() -> {
5662 if (finishBooting) {
5663 mAmInternal.finishBooting();
5664 }
5665 if (enableScreen) {
5666 mInternal.enableScreenAfterBoot(isBooted());
5667 }
5668 });
5669 }
5670
5671 void setHeavyWeightProcess(ActivityRecord root) {
5672 mHeavyWeightProcess = root.app;
5673 final Message m = PooledLambda.obtainMessage(
5674 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005675 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005676 mH.sendMessage(m);
5677 }
5678
5679 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5680 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5681 return;
5682 }
5683
5684 mHeavyWeightProcess = null;
5685 final Message m = PooledLambda.obtainMessage(
5686 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5687 proc.mUserId);
5688 mH.sendMessage(m);
5689 }
5690
5691 private void cancelHeavyWeightProcessNotification(int userId) {
5692 final INotificationManager inm = NotificationManager.getService();
5693 if (inm == null) {
5694 return;
5695 }
5696 try {
5697 inm.cancelNotificationWithTag("android", null,
5698 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5699 } catch (RuntimeException e) {
5700 Slog.w(TAG, "Error canceling notification for service", e);
5701 } catch (RemoteException e) {
5702 }
5703
5704 }
5705
5706 private void postHeavyWeightProcessNotification(
5707 WindowProcessController proc, Intent intent, int userId) {
5708 if (proc == null) {
5709 return;
5710 }
5711
5712 final INotificationManager inm = NotificationManager.getService();
5713 if (inm == null) {
5714 return;
5715 }
5716
5717 try {
5718 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5719 String text = mContext.getString(R.string.heavy_weight_notification,
5720 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5721 Notification notification =
5722 new Notification.Builder(context,
5723 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5724 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5725 .setWhen(0)
5726 .setOngoing(true)
5727 .setTicker(text)
5728 .setColor(mContext.getColor(
5729 com.android.internal.R.color.system_notification_accent_color))
5730 .setContentTitle(text)
5731 .setContentText(
5732 mContext.getText(R.string.heavy_weight_notification_detail))
5733 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5734 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5735 new UserHandle(userId)))
5736 .build();
5737 try {
5738 inm.enqueueNotificationWithTag("android", "android", null,
5739 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5740 } catch (RuntimeException e) {
5741 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5742 } catch (RemoteException e) {
5743 }
5744 } catch (PackageManager.NameNotFoundException e) {
5745 Slog.w(TAG, "Unable to create context for heavy notification", e);
5746 }
5747
5748 }
5749
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005750 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5751 IBinder token, String resultWho, int requestCode, Intent[] intents,
5752 String[] resolvedTypes, int flags, Bundle bOptions) {
5753
5754 ActivityRecord activity = null;
5755 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5756 activity = ActivityRecord.isInStackLocked(token);
5757 if (activity == null) {
5758 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5759 return null;
5760 }
5761 if (activity.finishing) {
5762 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5763 return null;
5764 }
5765 }
5766
5767 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5768 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5769 bOptions);
5770 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5771 if (noCreate) {
5772 return rec;
5773 }
5774 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5775 if (activity.pendingResults == null) {
5776 activity.pendingResults = new HashSet<>();
5777 }
5778 activity.pendingResults.add(rec.ref);
5779 }
5780 return rec;
5781 }
5782
Andrii Kulian52d255c2018-07-13 11:32:19 -07005783 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005784 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005785 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005786 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5787 mCurAppTimeTracker.start(resumedActivity.packageName);
5788 }
5789 }
5790
5791 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5792 if (mTracedResumedActivity != null) {
5793 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5794 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5795 }
5796 if (resumed != null) {
5797 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5798 constructResumedTraceName(resumed.packageName), 0);
5799 }
5800 mTracedResumedActivity = resumed;
5801 }
5802
5803 private String constructResumedTraceName(String packageName) {
5804 return "focused app: " + packageName;
5805 }
5806
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005807 /** Applies latest configuration and/or visibility updates if needed. */
5808 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5809 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005810 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005811 // mainStack is null during startup.
5812 if (mainStack != null) {
5813 if (changes != 0 && starting == null) {
5814 // If the configuration changed, and the caller is not already
5815 // in the process of starting an activity, then find the top
5816 // activity to check if its configuration needs to change.
5817 starting = mainStack.topRunningActivityLocked();
5818 }
5819
5820 if (starting != null) {
5821 kept = starting.ensureActivityConfiguration(changes,
5822 false /* preserveWindow */);
5823 // And we need to make sure at this point that all other activities
5824 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005825 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 !PRESERVE_WINDOWS);
5827 }
5828 }
5829
5830 return kept;
5831 }
5832
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005833 void scheduleAppGcsLocked() {
5834 mH.post(() -> mAmInternal.scheduleAppGcs());
5835 }
5836
Wale Ogunwale53783742018-09-16 10:21:51 -07005837 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5838 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5839 }
5840
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005841 /**
5842 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5843 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5844 * on demand.
5845 */
5846 IPackageManager getPackageManager() {
5847 return AppGlobals.getPackageManager();
5848 }
5849
5850 PackageManagerInternal getPackageManagerInternalLocked() {
5851 if (mPmInternal == null) {
5852 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5853 }
5854 return mPmInternal;
5855 }
5856
Hai Zhangf4da9be2019-05-01 13:46:06 +08005857 PermissionPolicyInternal getPermissionPolicyInternal() {
5858 if (mPermissionPolicyInternal == null) {
5859 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5860 }
5861 return mPermissionPolicyInternal;
5862 }
5863
Wale Ogunwale008163e2018-07-23 23:11:08 -07005864 AppWarnings getAppWarningsLocked() {
5865 return mAppWarnings;
5866 }
5867
Wale Ogunwale214f3482018-10-04 11:00:47 -07005868 Intent getHomeIntent() {
5869 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5870 intent.setComponent(mTopComponent);
5871 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5872 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5873 intent.addCategory(Intent.CATEGORY_HOME);
5874 }
5875 return intent;
5876 }
5877
Chilun2ef71f72018-11-16 17:57:15 +08005878 /**
5879 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5880 * activities.
5881 *
5882 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5883 * component defined in config_secondaryHomeComponent.
5884 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5885 */
5886 Intent getSecondaryHomeIntent(String preferredPackage) {
5887 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005888 if (preferredPackage == null) {
5889 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005890 final String secondaryHomeComponent = mContext.getResources().getString(
5891 com.android.internal.R.string.config_secondaryHomeComponent);
5892 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5893 } else {
5894 intent.setPackage(preferredPackage);
5895 }
5896 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5897 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5898 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5899 }
5900 return intent;
5901 }
5902
Wale Ogunwale214f3482018-10-04 11:00:47 -07005903 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5904 if (info == null) return null;
5905 ApplicationInfo newInfo = new ApplicationInfo(info);
5906 newInfo.initForUser(userId);
5907 return newInfo;
5908 }
5909
Wale Ogunwale9c103022018-10-18 07:44:54 -07005910 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005911 if (uid == SYSTEM_UID) {
5912 // The system gets to run in any process. If there are multiple processes with the same
5913 // uid, just pick the first (this should never happen).
5914 final SparseArray<WindowProcessController> procs =
5915 mProcessNames.getMap().get(processName);
5916 if (procs == null) return null;
5917 final int procCount = procs.size();
5918 for (int i = 0; i < procCount; i++) {
5919 final int procUid = procs.keyAt(i);
5920 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5921 // Don't use an app process or different user process for system component.
5922 continue;
5923 }
5924 return procs.valueAt(i);
5925 }
5926 }
5927
5928 return mProcessNames.get(processName, uid);
5929 }
5930
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005931 WindowProcessController getProcessController(IApplicationThread thread) {
5932 if (thread == null) {
5933 return null;
5934 }
5935
5936 final IBinder threadBinder = thread.asBinder();
5937 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5938 for (int i = pmap.size()-1; i >= 0; i--) {
5939 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5940 for (int j = procs.size() - 1; j >= 0; j--) {
5941 final WindowProcessController proc = procs.valueAt(j);
5942 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5943 return proc;
5944 }
5945 }
5946 }
5947
5948 return null;
5949 }
5950
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005951 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005952 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005953 if (proc == null) return null;
5954 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5955 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005956 }
5957 return null;
5958 }
5959
Riddle Hsua0536432019-02-16 00:38:59 +08005960 int getUidState(int uid) {
5961 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005962 }
5963
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005964 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005965 // A uid is considered to be foreground if it has a visible non-toast window.
5966 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005967 }
5968
Ricky Wai96f5c352019-04-10 18:40:17 +01005969 boolean isDeviceOwner(int uid) {
5970 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005971 }
5972
Ricky Wai96f5c352019-04-10 18:40:17 +01005973 void setDeviceOwnerUid(int uid) {
5974 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005975 }
5976
Wale Ogunwale9de19442018-10-18 19:05:03 -07005977 /**
5978 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5979 * the whitelist
5980 */
5981 String getPendingTempWhitelistTagForUidLocked(int uid) {
5982 return mPendingTempWhitelist.get(uid);
5983 }
5984
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005985 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5986 if (true || Build.IS_USER) {
5987 return;
5988 }
5989
5990 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5991 StrictMode.allowThreadDiskWrites();
5992 try {
5993 File tracesDir = new File("/data/anr");
5994 File tracesFile = null;
5995 try {
5996 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5997
5998 StringBuilder sb = new StringBuilder();
5999 Time tobj = new Time();
6000 tobj.set(System.currentTimeMillis());
6001 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
6002 sb.append(": ");
6003 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6004 sb.append(" since ");
6005 sb.append(msg);
6006 FileOutputStream fos = new FileOutputStream(tracesFile);
6007 fos.write(sb.toString().getBytes());
6008 if (app == null) {
6009 fos.write("\n*** No application process!".getBytes());
6010 }
6011 fos.close();
6012 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6013 } catch (IOException e) {
6014 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6015 return;
6016 }
6017
6018 if (app != null && app.getPid() > 0) {
6019 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6020 firstPids.add(app.getPid());
6021 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6022 }
6023
6024 File lastTracesFile = null;
6025 File curTracesFile = null;
6026 for (int i=9; i>=0; i--) {
6027 String name = String.format(Locale.US, "slow%02d.txt", i);
6028 curTracesFile = new File(tracesDir, name);
6029 if (curTracesFile.exists()) {
6030 if (lastTracesFile != null) {
6031 curTracesFile.renameTo(lastTracesFile);
6032 } else {
6033 curTracesFile.delete();
6034 }
6035 }
6036 lastTracesFile = curTracesFile;
6037 }
6038 tracesFile.renameTo(curTracesFile);
6039 } finally {
6040 StrictMode.setThreadPolicy(oldPolicy);
6041 }
6042 }
6043
Michal Karpinskida34cd42019-04-02 19:46:52 +01006044 boolean isAssociatedCompanionApp(int userId, int uid) {
6045 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6046 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006047 return false;
6048 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006049 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006050 }
6051
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006052 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006053 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006054
6055
Wale Ogunwale98875612018-10-12 07:53:02 -07006056 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6057 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006058
Riddle Hsud93a6c42018-11-29 21:50:06 +08006059 H(Looper looper) {
6060 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006061 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006062
6063 @Override
6064 public void handleMessage(Message msg) {
6065 switch (msg.what) {
6066 case REPORT_TIME_TRACKER_MSG: {
6067 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6068 tracker.deliverResult(mContext);
6069 } break;
6070 }
6071 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006072 }
6073
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006074 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006075 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006076
6077 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006078 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006079 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006080
6081 @Override
6082 public void handleMessage(Message msg) {
6083 switch (msg.what) {
6084 case DISMISS_DIALOG_UI_MSG: {
6085 final Dialog d = (Dialog) msg.obj;
6086 d.dismiss();
6087 break;
6088 }
6089 }
6090 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006091 }
6092
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006093 final class LocalService extends ActivityTaskManagerInternal {
6094 @Override
6095 public SleepToken acquireSleepToken(String tag, int displayId) {
6096 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006097 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 }
6099
6100 @Override
6101 public ComponentName getHomeActivityForUser(int userId) {
6102 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006103 final ActivityRecord homeActivity =
6104 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006105 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 }
6107 }
6108
6109 @Override
6110 public void onLocalVoiceInteractionStarted(IBinder activity,
6111 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6112 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006113 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114 }
6115 }
6116
6117 @Override
6118 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6119 synchronized (mGlobalLock) {
6120 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6121 reasons, timestamp);
6122 }
6123 }
6124
6125 @Override
6126 public void notifyAppTransitionFinished() {
6127 synchronized (mGlobalLock) {
6128 mStackSupervisor.notifyAppTransitionDone();
6129 }
6130 }
6131
6132 @Override
6133 public void notifyAppTransitionCancelled() {
6134 synchronized (mGlobalLock) {
6135 mStackSupervisor.notifyAppTransitionDone();
6136 }
6137 }
6138
6139 @Override
6140 public List<IBinder> getTopVisibleActivities() {
6141 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006142 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 }
6144 }
6145
6146 @Override
6147 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6148 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006149 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006150 }
6151 }
6152
6153 @Override
6154 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6155 Bundle bOptions) {
6156 Preconditions.checkNotNull(intents, "intents");
6157 final String[] resolvedTypes = new String[intents.length];
6158
6159 // UID of the package on user userId.
6160 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6161 // packageUid may not be initialized.
6162 int packageUid = 0;
6163 final long ident = Binder.clearCallingIdentity();
6164
6165 try {
6166 for (int i = 0; i < intents.length; i++) {
6167 resolvedTypes[i] =
6168 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6169 }
6170
6171 packageUid = AppGlobals.getPackageManager().getPackageUid(
6172 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6173 } catch (RemoteException e) {
6174 // Shouldn't happen.
6175 } finally {
6176 Binder.restoreCallingIdentity(ident);
6177 }
6178
Riddle Hsu591bf612019-02-14 17:55:31 +08006179 return getActivityStartController().startActivitiesInPackage(
6180 packageUid, packageName,
6181 intents, resolvedTypes, null /* resultTo */,
6182 SafeActivityOptions.fromBundle(bOptions), userId,
6183 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6184 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006185 }
6186
6187 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006188 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6189 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6190 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6191 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006192 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006193 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006194 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6195 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6196 userId, validateIncomingUser, originatingPendingIntent,
6197 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006198 }
6199 }
6200
6201 @Override
6202 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6203 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6204 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6205 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006206 PendingIntentRecord originatingPendingIntent,
6207 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006208 synchronized (mGlobalLock) {
6209 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6210 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6211 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006212 validateIncomingUser, originatingPendingIntent,
6213 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006214 }
6215 }
6216
6217 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6219 Intent intent, Bundle options, int userId) {
6220 return ActivityTaskManagerService.this.startActivityAsUser(
6221 caller, callerPacakge, intent,
6222 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6223 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6224 false /*validateIncomingUser*/);
6225 }
6226
6227 @Override
lumark588a3e82018-07-20 18:53:54 +08006228 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 synchronized (mGlobalLock) {
6230
6231 // We might change the visibilities here, so prepare an empty app transition which
6232 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006233 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006234 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006235 if (activityDisplay == null) {
6236 return;
6237 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006238 final DisplayContent dc = activityDisplay.mDisplayContent;
6239 final boolean wasTransitionSet =
6240 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006242 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006243 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006244 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006245
6246 // If there was a transition set already we don't want to interfere with it as we
6247 // might be starting it too early.
6248 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006249 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 }
6251 }
6252 if (callback != null) {
6253 callback.run();
6254 }
6255 }
6256
6257 @Override
6258 public void notifyKeyguardTrustedChanged() {
6259 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006260 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006261 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 }
6263 }
6264 }
6265
6266 /**
6267 * Called after virtual display Id is updated by
6268 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6269 * {@param vrVr2dDisplayId}.
6270 */
6271 @Override
6272 public void setVr2dDisplayId(int vr2dDisplayId) {
6273 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6274 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006275 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 }
6277 }
6278
6279 @Override
6280 public void setFocusedActivity(IBinder token) {
6281 synchronized (mGlobalLock) {
6282 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6283 if (r == null) {
6284 throw new IllegalArgumentException(
6285 "setFocusedActivity: No activity record matching token=" + token);
6286 }
Louis Chang19443452018-10-09 12:10:21 +08006287 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006288 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290 }
6291 }
6292
6293 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006295 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006296 }
6297
6298 @Override
6299 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006300 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 }
6302
6303 @Override
6304 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006305 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 }
6307
6308 @Override
6309 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6310 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6311 }
6312
6313 @Override
6314 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006315 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006316 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006317
6318 @Override
6319 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6320 synchronized (mGlobalLock) {
6321 mActiveVoiceInteractionServiceComponent = component;
6322 }
6323 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006324
6325 @Override
6326 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6327 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6328 return;
6329 }
6330 synchronized (mGlobalLock) {
6331 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6332 if (types == null) {
6333 if (uid < 0) {
6334 return;
6335 }
6336 types = new ArrayMap<>();
6337 mAllowAppSwitchUids.put(userId, types);
6338 }
6339 if (uid < 0) {
6340 types.remove(type);
6341 } else {
6342 types.put(type, uid);
6343 }
6344 }
6345 }
6346
6347 @Override
6348 public void onUserStopped(int userId) {
6349 synchronized (mGlobalLock) {
6350 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6351 mAllowAppSwitchUids.remove(userId);
6352 }
6353 }
6354
6355 @Override
6356 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6357 synchronized (mGlobalLock) {
6358 return ActivityTaskManagerService.this.isGetTasksAllowed(
6359 caller, callingPid, callingUid);
6360 }
6361 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006362
Riddle Hsua0536432019-02-16 00:38:59 +08006363 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006364 @Override
6365 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006366 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006367 mProcessNames.put(proc.mName, proc.mUid, proc);
6368 }
6369 }
6370
Riddle Hsua0536432019-02-16 00:38:59 +08006371 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006372 @Override
6373 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006374 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006375 mProcessNames.remove(name, uid);
6376 }
6377 }
6378
Riddle Hsua0536432019-02-16 00:38:59 +08006379 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006380 @Override
6381 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006382 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006383 if (proc == mHomeProcess) {
6384 mHomeProcess = null;
6385 }
6386 if (proc == mPreviousProcess) {
6387 mPreviousProcess = null;
6388 }
6389 }
6390 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006391
Riddle Hsua0536432019-02-16 00:38:59 +08006392 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006393 @Override
6394 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006395 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006396 return mTopProcessState;
6397 }
6398 }
6399
Riddle Hsua0536432019-02-16 00:38:59 +08006400 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006401 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006402 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006403 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006404 return proc == mHeavyWeightProcess;
6405 }
6406 }
6407
Riddle Hsua0536432019-02-16 00:38:59 +08006408 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006409 @Override
6410 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006411 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006412 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6413 }
6414 }
6415
6416 @Override
6417 public void finishHeavyWeightApp() {
6418 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006419 if (mHeavyWeightProcess != null) {
6420 mHeavyWeightProcess.finishActivities();
6421 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6423 mHeavyWeightProcess);
6424 }
6425 }
6426
Riddle Hsua0536432019-02-16 00:38:59 +08006427 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006428 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006429 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006430 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006431 return isSleepingLocked();
6432 }
6433 }
6434
6435 @Override
6436 public boolean isShuttingDown() {
6437 synchronized (mGlobalLock) {
6438 return mShuttingDown;
6439 }
6440 }
6441
6442 @Override
6443 public boolean shuttingDown(boolean booted, int timeout) {
6444 synchronized (mGlobalLock) {
6445 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006446 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006447 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006448 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006449 return mStackSupervisor.shutdownLocked(timeout);
6450 }
6451 }
6452
6453 @Override
6454 public void enableScreenAfterBoot(boolean booted) {
6455 synchronized (mGlobalLock) {
6456 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6457 SystemClock.uptimeMillis());
6458 mWindowManager.enableScreenAfterBoot();
6459 updateEventDispatchingLocked(booted);
6460 }
6461 }
6462
6463 @Override
6464 public boolean showStrictModeViolationDialog() {
6465 synchronized (mGlobalLock) {
6466 return mShowDialogs && !mSleeping && !mShuttingDown;
6467 }
6468 }
6469
6470 @Override
6471 public void showSystemReadyErrorDialogsIfNeeded() {
6472 synchronized (mGlobalLock) {
6473 try {
6474 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6475 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6476 + " data partition or your device will be unstable.");
6477 mUiHandler.post(() -> {
6478 if (mShowDialogs) {
6479 AlertDialog d = new BaseErrorDialog(mUiContext);
6480 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6481 d.setCancelable(false);
6482 d.setTitle(mUiContext.getText(R.string.android_system_label));
6483 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6484 d.setButton(DialogInterface.BUTTON_POSITIVE,
6485 mUiContext.getText(R.string.ok),
6486 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6487 d.show();
6488 }
6489 });
6490 }
6491 } catch (RemoteException e) {
6492 }
6493
6494 if (!Build.isBuildConsistent()) {
6495 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6496 mUiHandler.post(() -> {
6497 if (mShowDialogs) {
6498 AlertDialog d = new BaseErrorDialog(mUiContext);
6499 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6500 d.setCancelable(false);
6501 d.setTitle(mUiContext.getText(R.string.android_system_label));
6502 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6503 d.setButton(DialogInterface.BUTTON_POSITIVE,
6504 mUiContext.getText(R.string.ok),
6505 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6506 d.show();
6507 }
6508 });
6509 }
6510 }
6511 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006512
6513 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006514 public void onProcessMapped(int pid, WindowProcessController proc) {
6515 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006516 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006517 }
6518 }
6519
6520 @Override
6521 public void onProcessUnMapped(int pid) {
6522 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006523 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006524 }
6525 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006526
6527 @Override
6528 public void onPackageDataCleared(String name) {
6529 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006530 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006531 mAppWarnings.onPackageDataCleared(name);
6532 }
6533 }
6534
6535 @Override
6536 public void onPackageUninstalled(String name) {
6537 synchronized (mGlobalLock) {
6538 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006539 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006540 }
6541 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006542
6543 @Override
6544 public void onPackageAdded(String name, boolean replacing) {
6545 synchronized (mGlobalLock) {
6546 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6547 }
6548 }
6549
6550 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006551 public void onPackageReplaced(ApplicationInfo aInfo) {
6552 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006553 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006554 }
6555 }
6556
6557 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006558 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6559 synchronized (mGlobalLock) {
6560 return compatibilityInfoForPackageLocked(ai);
6561 }
6562 }
6563
Yunfan Chen75157d72018-07-27 14:47:21 +09006564 /**
6565 * Set the corresponding display information for the process global configuration. To be
6566 * called when we need to show IME on a different display.
6567 *
6568 * @param pid The process id associated with the IME window.
6569 * @param displayId The ID of the display showing the IME.
6570 */
6571 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006572 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006573 // Don't update process-level configuration for Multi-Client IME process since other
6574 // IMEs on other displays will also receive this configuration change due to IME
6575 // services use the same application config/context.
6576 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006577
Yunfan Chen75157d72018-07-27 14:47:21 +09006578 if (pid == MY_PID || pid < 0) {
6579 if (DEBUG_CONFIGURATION) {
6580 Slog.w(TAG,
6581 "Trying to update display configuration for system/invalid process.");
6582 }
6583 return;
6584 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006585 synchronized (mGlobalLock) {
6586 final ActivityDisplay activityDisplay =
6587 mRootActivityContainer.getActivityDisplay(displayId);
6588 if (activityDisplay == null) {
6589 // Call might come when display is not yet added or has been removed.
6590 if (DEBUG_CONFIGURATION) {
6591 Slog.w(TAG, "Trying to update display configuration for non-existing "
6592 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006593 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006594 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006595 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006596 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006597 if (process == null) {
6598 if (DEBUG_CONFIGURATION) {
6599 Slog.w(TAG, "Trying to update display configuration for invalid "
6600 + "process, pid=" + pid);
6601 }
6602 return;
6603 }
6604 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6605 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006606 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006607
6608 @Override
6609 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006610 int requestCode, int resultCode, Intent resultData) {
6611 final ActivityRecord r;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006612 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006613 r = ActivityRecord.isInStackLocked(activityToken);
6614 if (r == null || r.getActivityStack() == null) {
6615 return;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006616 }
6617 }
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006618
6619 // Carefully collect grants without holding lock
6620 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
6621 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
6622
6623 synchronized (mGlobalLock) {
6624 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6625 requestCode, resultCode, resultData, resultGrants);
6626 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006627 }
6628
6629 @Override
6630 public void clearPendingResultForActivity(IBinder activityToken,
6631 WeakReference<PendingIntentRecord> pir) {
6632 synchronized (mGlobalLock) {
6633 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6634 if (r != null && r.pendingResults != null) {
6635 r.pendingResults.remove(pir);
6636 }
6637 }
6638 }
6639
6640 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006641 public ActivityTokens getTopActivityForTask(int taskId) {
6642 synchronized (mGlobalLock) {
6643 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6644 if (taskRecord == null) {
6645 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6646 + " Requested task not found");
6647 return null;
6648 }
6649 final ActivityRecord activity = taskRecord.getTopActivity();
6650 if (activity == null) {
6651 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6652 + " Requested activity not found");
6653 return null;
6654 }
6655 if (!activity.attachedToProcess()) {
6656 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6657 + activity);
6658 return null;
6659 }
6660 return new ActivityTokens(activity.appToken, activity.assistToken,
6661 activity.app.getThread());
6662 }
6663 }
6664
6665 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006666 public IIntentSender getIntentSender(int type, String packageName,
6667 int callingUid, int userId, IBinder token, String resultWho,
6668 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6669 Bundle bOptions) {
6670 synchronized (mGlobalLock) {
6671 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6672 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6673 }
6674 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006675
6676 @Override
6677 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6678 synchronized (mGlobalLock) {
6679 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6680 if (r == null) {
6681 return null;
6682 }
6683 if (r.mServiceConnectionsHolder == null) {
6684 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6685 ActivityTaskManagerService.this, r);
6686 }
6687
6688 return r.mServiceConnectionsHolder;
6689 }
6690 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006691
6692 @Override
6693 public Intent getHomeIntent() {
6694 synchronized (mGlobalLock) {
6695 return ActivityTaskManagerService.this.getHomeIntent();
6696 }
6697 }
6698
6699 @Override
6700 public boolean startHomeActivity(int userId, String reason) {
6701 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006702 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006703 }
6704 }
6705
6706 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006707 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006708 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006709 synchronized (mGlobalLock) {
6710 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006711 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006712 }
Chilun8b1f1be2019-03-13 17:14:36 +08006713 }
6714
6715 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006716 public boolean startHomeOnAllDisplays(int userId, String reason) {
6717 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006718 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006719 }
6720 }
6721
Riddle Hsua0536432019-02-16 00:38:59 +08006722 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006723 @Override
6724 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006725 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006726 if (mFactoryTest == FACTORY_TEST_OFF) {
6727 return false;
6728 }
6729 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6730 && wpc.mName.equals(mTopComponent.getPackageName())) {
6731 return true;
6732 }
6733 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6734 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6735 }
6736 }
6737
6738 @Override
6739 public void updateTopComponentForFactoryTest() {
6740 synchronized (mGlobalLock) {
6741 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6742 return;
6743 }
6744 final ResolveInfo ri = mContext.getPackageManager()
6745 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6746 final CharSequence errorMsg;
6747 if (ri != null) {
6748 final ActivityInfo ai = ri.activityInfo;
6749 final ApplicationInfo app = ai.applicationInfo;
6750 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6751 mTopAction = Intent.ACTION_FACTORY_TEST;
6752 mTopData = null;
6753 mTopComponent = new ComponentName(app.packageName, ai.name);
6754 errorMsg = null;
6755 } else {
6756 errorMsg = mContext.getResources().getText(
6757 com.android.internal.R.string.factorytest_not_system);
6758 }
6759 } else {
6760 errorMsg = mContext.getResources().getText(
6761 com.android.internal.R.string.factorytest_no_action);
6762 }
6763 if (errorMsg == null) {
6764 return;
6765 }
6766
6767 mTopAction = null;
6768 mTopData = null;
6769 mTopComponent = null;
6770 mUiHandler.post(() -> {
6771 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6772 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006773 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006774 });
6775 }
6776 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777
Riddle Hsua0536432019-02-16 00:38:59 +08006778 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 @Override
6780 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6781 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006782 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006784 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006785
6786 wpc.clearRecentTasks();
6787 wpc.clearActivities();
6788
6789 if (wpc.isInstrumenting()) {
6790 finishInstrumentationCallback.run();
6791 }
6792
Jorim Jaggid0752812018-10-16 16:07:20 +02006793 if (!restarting && hasVisibleActivities) {
6794 mWindowManager.deferSurfaceLayout();
6795 try {
6796 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6797 // If there was nothing to resume, and we are not already restarting
6798 // this process, but there is a visible activity that is hosted by the
6799 // process...then make sure all visible activities are running, taking
6800 // care of restarting this process.
6801 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6802 !PRESERVE_WINDOWS);
6803 }
6804 } finally {
6805 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 }
6808 }
6809 }
6810
6811 @Override
6812 public void closeSystemDialogs(String reason) {
6813 enforceNotIsolatedCaller("closeSystemDialogs");
6814
6815 final int pid = Binder.getCallingPid();
6816 final int uid = Binder.getCallingUid();
6817 final long origId = Binder.clearCallingIdentity();
6818 try {
6819 synchronized (mGlobalLock) {
6820 // Only allow this from foreground processes, so that background
6821 // applications can't abuse it to prevent system UI from being shown.
6822 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006823 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006824 if (!proc.isPerceptible()) {
6825 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6826 + " from background process " + proc);
6827 return;
6828 }
6829 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 mWindowManager.closeSystemDialogs(reason);
6831
Wale Ogunwaled32da472018-11-16 07:19:28 -08006832 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006834 // Call into AM outside the synchronized block.
6835 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 } finally {
6837 Binder.restoreCallingIdentity(origId);
6838 }
6839 }
6840
6841 @Override
6842 public void cleanupDisabledPackageComponents(
6843 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6844 synchronized (mGlobalLock) {
6845 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006846 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006848 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 mStackSupervisor.scheduleIdleLocked();
6850 }
6851
6852 // Clean-up disabled tasks
6853 getRecentTasks().cleanupDisabledPackageTasksLocked(
6854 packageName, disabledClasses, userId);
6855 }
6856 }
6857
6858 @Override
6859 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6860 int userId) {
6861 synchronized (mGlobalLock) {
6862
6863 boolean didSomething =
6864 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006865 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 null, doit, evenPersistent, userId);
6867 return didSomething;
6868 }
6869 }
6870
6871 @Override
6872 public void resumeTopActivities(boolean scheduleIdle) {
6873 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006874 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006875 if (scheduleIdle) {
6876 mStackSupervisor.scheduleIdleLocked();
6877 }
6878 }
6879 }
6880
Riddle Hsua0536432019-02-16 00:38:59 +08006881 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006882 @Override
6883 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006884 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6886 }
6887 }
6888
Riddle Hsua0536432019-02-16 00:38:59 +08006889 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 @Override
6891 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006892 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006893 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 }
6895 }
6896
6897 @Override
6898 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6899 try {
6900 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6901 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6902 }
6903 } catch (RemoteException ex) {
6904 throw new SecurityException("Fail to check is caller a privileged app", ex);
6905 }
6906
6907 synchronized (mGlobalLock) {
6908 final long ident = Binder.clearCallingIdentity();
6909 try {
6910 if (mAmInternal.shouldConfirmCredentials(userId)) {
6911 if (mKeyguardController.isKeyguardLocked()) {
6912 // Showing launcher to avoid user entering credential twice.
6913 startHomeActivity(currentUserId, "notifyLockedProfile");
6914 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006915 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006916 }
6917 } finally {
6918 Binder.restoreCallingIdentity(ident);
6919 }
6920 }
6921 }
6922
6923 @Override
6924 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6925 mAmInternal.enforceCallingPermission(
6926 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6927
6928 synchronized (mGlobalLock) {
6929 final long ident = Binder.clearCallingIdentity();
6930 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006931 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6932 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006933 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6935 UserHandle.CURRENT);
6936 } finally {
6937 Binder.restoreCallingIdentity(ident);
6938 }
6939 }
6940 }
6941
6942 @Override
6943 public void writeActivitiesToProto(ProtoOutputStream proto) {
6944 synchronized (mGlobalLock) {
6945 // The output proto of "activity --proto activities"
6946 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006947 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006948 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6949 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006950 }
6951 }
6952
6953 @Override
6954 public void saveANRState(String reason) {
6955 synchronized (mGlobalLock) {
6956 final StringWriter sw = new StringWriter();
6957 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6958 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6959 if (reason != null) {
6960 pw.println(" Reason: " + reason);
6961 }
6962 pw.println();
6963 getActivityStartController().dump(pw, " ", null);
6964 pw.println();
6965 pw.println("-------------------------------------------------------------------------------");
6966 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6967 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6968 "" /* header */);
6969 pw.println();
6970 pw.close();
6971
6972 mLastANRState = sw.toString();
6973 }
6974 }
6975
6976 @Override
6977 public void clearSavedANRState() {
6978 synchronized (mGlobalLock) {
6979 mLastANRState = null;
6980 }
6981 }
6982
6983 @Override
6984 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6985 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6986 synchronized (mGlobalLock) {
6987 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6988 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6989 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6990 dumpLastANRLocked(pw);
6991 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6992 dumpLastANRTracesLocked(pw);
6993 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6994 dumpActivityStarterLocked(pw, dumpPackage);
6995 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6996 dumpActivityContainersLocked(pw);
6997 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6998 if (getRecentTasks() != null) {
6999 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7000 }
7001 }
7002 }
7003 }
7004
7005 @Override
7006 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7007 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7008 int wakefulness) {
7009 synchronized (mGlobalLock) {
7010 if (mHomeProcess != null && (dumpPackage == null
7011 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7012 if (needSep) {
7013 pw.println();
7014 needSep = false;
7015 }
7016 pw.println(" mHomeProcess: " + mHomeProcess);
7017 }
7018 if (mPreviousProcess != null && (dumpPackage == null
7019 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7020 if (needSep) {
7021 pw.println();
7022 needSep = false;
7023 }
7024 pw.println(" mPreviousProcess: " + mPreviousProcess);
7025 }
7026 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7027 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7028 StringBuilder sb = new StringBuilder(128);
7029 sb.append(" mPreviousProcessVisibleTime: ");
7030 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7031 pw.println(sb);
7032 }
7033 if (mHeavyWeightProcess != null && (dumpPackage == null
7034 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7035 if (needSep) {
7036 pw.println();
7037 needSep = false;
7038 }
7039 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7040 }
7041 if (dumpPackage == null) {
7042 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007043 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007044 }
7045 if (dumpAll) {
7046 if (dumpPackage == null) {
7047 pw.println(" mConfigWillChange: "
7048 + getTopDisplayFocusedStack().mConfigWillChange);
7049 }
7050 if (mCompatModePackages.getPackages().size() > 0) {
7051 boolean printed = false;
7052 for (Map.Entry<String, Integer> entry
7053 : mCompatModePackages.getPackages().entrySet()) {
7054 String pkg = entry.getKey();
7055 int mode = entry.getValue();
7056 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7057 continue;
7058 }
7059 if (!printed) {
7060 pw.println(" mScreenCompatPackages:");
7061 printed = true;
7062 }
7063 pw.println(" " + pkg + ": " + mode);
7064 }
7065 }
7066 }
7067
7068 if (dumpPackage == null) {
7069 pw.println(" mWakefulness="
7070 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007071 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 if (mRunningVoice != null) {
7073 pw.println(" mRunningVoice=" + mRunningVoice);
7074 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7075 }
7076 pw.println(" mSleeping=" + mSleeping);
7077 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7078 pw.println(" mVrController=" + mVrController);
7079 }
7080 if (mCurAppTimeTracker != null) {
7081 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7082 }
7083 if (mAllowAppSwitchUids.size() > 0) {
7084 boolean printed = false;
7085 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7086 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7087 for (int j = 0; j < types.size(); j++) {
7088 if (dumpPackage == null ||
7089 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7090 if (needSep) {
7091 pw.println();
7092 needSep = false;
7093 }
7094 if (!printed) {
7095 pw.println(" mAllowAppSwitchUids:");
7096 printed = true;
7097 }
7098 pw.print(" User ");
7099 pw.print(mAllowAppSwitchUids.keyAt(i));
7100 pw.print(": Type ");
7101 pw.print(types.keyAt(j));
7102 pw.print(" = ");
7103 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7104 pw.println();
7105 }
7106 }
7107 }
7108 }
7109 if (dumpPackage == null) {
7110 if (mController != null) {
7111 pw.println(" mController=" + mController
7112 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7113 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007114 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7115 pw.println(" mLaunchingActivityWakeLock="
7116 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007117 }
7118
7119 return needSep;
7120 }
7121 }
7122
7123 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007124 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7125 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 synchronized (mGlobalLock) {
7127 if (dumpPackage == null) {
7128 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7129 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007130 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7131 if (mRunningVoice != null) {
7132 final long vrToken = proto.start(
7133 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7134 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7135 mRunningVoice.toString());
7136 mVoiceWakeLock.writeToProto(
7137 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7138 proto.end(vrToken);
7139 }
7140 mVrController.writeToProto(proto,
7141 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007142 if (mController != null) {
7143 final long token = proto.start(CONTROLLER);
7144 proto.write(CONTROLLER, mController.toString());
7145 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7146 proto.end(token);
7147 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007148 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7149 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7150 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152
7153 if (mHomeProcess != null && (dumpPackage == null
7154 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007155 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 }
7157
7158 if (mPreviousProcess != null && (dumpPackage == null
7159 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007160 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7162 }
7163
7164 if (mHeavyWeightProcess != null && (dumpPackage == null
7165 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007166 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 }
7168
7169 for (Map.Entry<String, Integer> entry
7170 : mCompatModePackages.getPackages().entrySet()) {
7171 String pkg = entry.getKey();
7172 int mode = entry.getValue();
7173 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7174 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7175 proto.write(PACKAGE, pkg);
7176 proto.write(MODE, mode);
7177 proto.end(compatToken);
7178 }
7179 }
7180
7181 if (mCurAppTimeTracker != null) {
7182 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7183 }
7184
7185 }
7186 }
7187
7188 @Override
7189 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7190 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7191 boolean dumpFocusedStackOnly) {
7192 synchronized (mGlobalLock) {
7193 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7194 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7195 }
7196 }
7197
7198 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007199 public void dumpForOom(PrintWriter pw) {
7200 synchronized (mGlobalLock) {
7201 pw.println(" mHomeProcess: " + mHomeProcess);
7202 pw.println(" mPreviousProcess: " + mPreviousProcess);
7203 if (mHeavyWeightProcess != null) {
7204 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7205 }
7206 }
7207 }
7208
7209 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 public boolean canGcNow() {
7211 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007212 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007213 }
7214 }
7215
Riddle Hsua0536432019-02-16 00:38:59 +08007216 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 @Override
7218 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007219 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007220 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 return top != null ? top.app : null;
7222 }
7223 }
7224
Riddle Hsua0536432019-02-16 00:38:59 +08007225 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007226 @Override
7227 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007228 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007229 if (mRootActivityContainer != null) {
7230 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007231 }
7232 }
7233 }
7234
7235 @Override
7236 public void scheduleDestroyAllActivities(String reason) {
7237 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007238 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007239 }
7240 }
7241
7242 @Override
7243 public void removeUser(int userId) {
7244 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007245 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007246 }
7247 }
7248
7249 @Override
7250 public boolean switchUser(int userId, UserState userState) {
7251 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007252 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007253 }
7254 }
7255
7256 @Override
7257 public void onHandleAppCrash(WindowProcessController wpc) {
7258 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007259 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007260 }
7261 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007262
7263 @Override
7264 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7265 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007266 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007267 }
7268 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007269
Riddle Hsua0536432019-02-16 00:38:59 +08007270 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007271 @Override
7272 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007273 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007274 }
7275
Riddle Hsua0536432019-02-16 00:38:59 +08007276 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007277 @Override
7278 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007279 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007280 }
7281
Riddle Hsua0536432019-02-16 00:38:59 +08007282 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007283 @Override
7284 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007285 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007286 }
7287
Riddle Hsua0536432019-02-16 00:38:59 +08007288 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007289 @Override
7290 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007291 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007292 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007293
7294 @Override
7295 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007296 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007297 mPendingTempWhitelist.put(uid, tag);
7298 }
7299 }
7300
7301 @Override
7302 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007303 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007304 mPendingTempWhitelist.remove(uid);
7305 }
7306 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007307
7308 @Override
7309 public boolean handleAppCrashInActivityController(String processName, int pid,
7310 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7311 Runnable killCrashingAppCallback) {
7312 synchronized (mGlobalLock) {
7313 if (mController == null) {
7314 return false;
7315 }
7316
7317 try {
7318 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7319 stackTrace)) {
7320 killCrashingAppCallback.run();
7321 return true;
7322 }
7323 } catch (RemoteException e) {
7324 mController = null;
7325 Watchdog.getInstance().setActivityController(null);
7326 }
7327 return false;
7328 }
7329 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007330
7331 @Override
7332 public void removeRecentTasksByPackageName(String packageName, int userId) {
7333 synchronized (mGlobalLock) {
7334 mRecentTasks.removeTasksByPackageName(packageName, userId);
7335 }
7336 }
7337
7338 @Override
7339 public void cleanupRecentTasksForUser(int userId) {
7340 synchronized (mGlobalLock) {
7341 mRecentTasks.cleanupLocked(userId);
7342 }
7343 }
7344
7345 @Override
7346 public void loadRecentTasksForUser(int userId) {
7347 synchronized (mGlobalLock) {
7348 mRecentTasks.loadUserRecentsLocked(userId);
7349 }
7350 }
7351
7352 @Override
7353 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7354 synchronized (mGlobalLock) {
7355 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7356 }
7357 }
7358
7359 @Override
7360 public void flushRecentTasks() {
7361 mRecentTasks.flush();
7362 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007363
7364 @Override
7365 public WindowProcessController getHomeProcess() {
7366 synchronized (mGlobalLock) {
7367 return mHomeProcess;
7368 }
7369 }
7370
7371 @Override
7372 public WindowProcessController getPreviousProcess() {
7373 synchronized (mGlobalLock) {
7374 return mPreviousProcess;
7375 }
7376 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007377
7378 @Override
7379 public void clearLockedTasks(String reason) {
7380 synchronized (mGlobalLock) {
7381 getLockTaskController().clearLockedTasks(reason);
7382 }
7383 }
7384
7385 @Override
7386 public void updateUserConfiguration() {
7387 synchronized (mGlobalLock) {
7388 final Configuration configuration = new Configuration(getGlobalConfiguration());
7389 final int currentUserId = mAmInternal.getCurrentUserId();
7390 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7391 configuration, currentUserId, Settings.System.canWrite(mContext));
7392 updateConfigurationLocked(configuration, null /* starting */,
7393 false /* initLocale */, false /* persistent */, currentUserId,
7394 false /* deferResume */);
7395 }
7396 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007397
7398 @Override
7399 public boolean canShowErrorDialogs() {
7400 synchronized (mGlobalLock) {
7401 return mShowDialogs && !mSleeping && !mShuttingDown
7402 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7403 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7404 mAmInternal.getCurrentUserId())
7405 && !(UserManager.isDeviceInDemoMode(mContext)
7406 && mAmInternal.getCurrentUser().isDemo());
7407 }
7408 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007409
7410 @Override
7411 public void setProfileApp(String profileApp) {
7412 synchronized (mGlobalLock) {
7413 mProfileApp = profileApp;
7414 }
7415 }
7416
7417 @Override
7418 public void setProfileProc(WindowProcessController wpc) {
7419 synchronized (mGlobalLock) {
7420 mProfileProc = wpc;
7421 }
7422 }
7423
7424 @Override
7425 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7426 synchronized (mGlobalLock) {
7427 mProfilerInfo = profilerInfo;
7428 }
7429 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007430
7431 @Override
7432 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7433 synchronized (mGlobalLock) {
7434 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7435 }
7436 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007437
7438 @Override
7439 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7440 synchronized (mGlobalLock) {
7441 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7442 }
7443 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007444
7445 @Override
7446 public boolean isUidForeground(int uid) {
7447 synchronized (mGlobalLock) {
7448 return ActivityTaskManagerService.this.isUidForeground(uid);
7449 }
7450 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007451
7452 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007453 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007454 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007455 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007456 }
7457 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007458
7459 @Override
7460 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007461 // Translate package names into UIDs
7462 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007463 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007464 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7465 if (uid >= 0) {
7466 result.add(uid);
7467 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007468 }
7469 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007470 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007471 }
7472 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007473 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007474}