blob: 7186ed169f5d7d4e660d675cf7111bc40ac714f6 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100314 // How long we permit background activity starts after an activity in the process
315 // started or finished.
316 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317
Wale Ogunwale98875612018-10-12 07:53:02 -0700318 /** Used to indicate that an app transition should be animated. */
319 static final boolean ANIMATE = true;
320
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700321 /** Hardware-reported OpenGLES version. */
322 final int GL_ES_VERSION;
323
Wale Ogunwale31913b52018-10-13 08:29:31 -0700324 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
325 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
326 public static final String DUMP_LASTANR_CMD = "lastanr" ;
327 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
328 public static final String DUMP_STARTER_CMD = "starter" ;
329 public static final String DUMP_CONTAINERS_CMD = "containers" ;
330 public static final String DUMP_RECENTS_CMD = "recents" ;
331 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
332
Wale Ogunwale64258362018-10-16 15:13:37 -0700333 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
334 public static final int RELAUNCH_REASON_NONE = 0;
335 /** This activity is being relaunched due to windowing mode change. */
336 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
337 /** This activity is being relaunched due to a free-resize operation. */
338 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
339
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700340 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700341
Wale Ogunwalef6733932018-06-27 05:14:34 -0700342 /**
343 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
344 * change at runtime. Use mContext for non-UI purposes.
345 */
346 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700348 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700351 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700352 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800353 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800354 @VisibleForTesting
355 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 PowerManagerInternal mPowerManagerInternal;
357 private UsageStatsManagerInternal mUsageStatsInternal;
358
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700359 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 IntentFirewall mIntentFirewall;
361
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700362 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800363 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 /**
365 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
366 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
367 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
368 *
369 * @see WindowManagerThreadPriorityBooster
370 */
371 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700372 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800373 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700374 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700375 private UserManagerService mUserManager;
376 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700377 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800378 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700379 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** All processes currently running that might have a window organized by name. */
381 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100382 /** All processes we currently have running mapped by pid and uid */
383 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** This is the process holding what we currently consider to be the "home" activity. */
385 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700386 /** The currently running heavy-weight process, if any. */
387 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700388 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /**
390 * This is the process holding the activity the user last visited that is in a different process
391 * from the one they are currently in.
392 */
393 WindowProcessController mPreviousProcess;
394 /** The time at which the previous process was last visible. */
395 long mPreviousProcessVisibleTime;
396
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700397 /** List of intents that were used to start the most recent tasks. */
398 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700399 /** State of external calls telling us if the device is awake or asleep. */
400 private boolean mKeyguardShown = false;
401
402 // Wrapper around VoiceInteractionServiceManager
403 private AssistUtils mAssistUtils;
404
405 // VoiceInteraction session ID that changes for each new request except when
406 // being called for multi-window assist in a single session.
407 private int mViSessionId = 1000;
408
409 // How long to wait in getAssistContextExtras for the activity and foreground services
410 // to respond with the result.
411 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
412
413 // How long top wait when going through the modern assist (which doesn't need to block
414 // on getting this result before starting to launch its UI).
415 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
416
417 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
418 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
419
Alison Cichowlas3e340502018-08-07 17:15:01 -0400420 // Permission tokens are used to temporarily granted a trusted app the ability to call
421 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
422 // showing any appropriate error messages to the user.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
424 10 * MINUTE_IN_MILLIS;
425
426 // How long before the service actually expires a token. This is slightly longer than
427 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
428 // expiration exception.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
430 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
431
432 // How long the service will remember expired tokens, for the purpose of providing error
433 // messaging when a client uses an expired token.
434 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
435 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
436
Marvin Ramin830d4e32019-03-12 13:16:58 +0100437 // How long to whitelist the Services for when requested.
438 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
439
Alison Cichowlas3e340502018-08-07 17:15:01 -0400440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
466 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
553 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
602 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
603 // automatically. Important for devices without direct input devices.
604 private boolean mShowDialogs = true;
605
606 /** Set if we are shutting down the system, similar to sleeping. */
607 boolean mShuttingDown = false;
608
609 /**
610 * We want to hold a wake lock while running a voice interaction session, since
611 * this may happen with the screen off and we need to keep the CPU running to
612 * be able to continue to interact with the user.
613 */
614 PowerManager.WakeLock mVoiceWakeLock;
615
616 /**
617 * Set while we are running a voice interaction. This overrides sleeping while it is active.
618 */
619 IVoiceInteractionSession mRunningVoice;
620
621 /**
622 * The last resumed activity. This is identical to the current resumed activity most
623 * of the time but could be different when we're pausing one activity before we resume
624 * another activity.
625 */
626 ActivityRecord mLastResumedActivity;
627
628 /**
629 * The activity that is currently being traced as the active resumed activity.
630 *
631 * @see #updateResumedAppTrace
632 */
633 private @Nullable ActivityRecord mTracedResumedActivity;
634
635 /** If non-null, we are tracking the time the user spends in the currently focused app. */
636 AppTimeTracker mCurAppTimeTracker;
637
Wale Ogunwale008163e2018-07-23 23:11:08 -0700638 private AppWarnings mAppWarnings;
639
Wale Ogunwale53783742018-09-16 10:21:51 -0700640 /**
641 * Packages that the user has asked to have run in screen size
642 * compatibility mode instead of filling the screen.
643 */
644 CompatModePackages mCompatModePackages;
645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private FontScaleSettingObserver mFontScaleSettingObserver;
647
Ricky Wai96f5c352019-04-10 18:40:17 +0100648 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000649
Wale Ogunwalef6733932018-06-27 05:14:34 -0700650 private final class FontScaleSettingObserver extends ContentObserver {
651 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
652 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
653
654 public FontScaleSettingObserver() {
655 super(mH);
656 final ContentResolver resolver = mContext.getContentResolver();
657 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
658 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
659 UserHandle.USER_ALL);
660 }
661
662 @Override
663 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
664 if (mFontScaleUri.equals(uri)) {
665 updateFontScaleIfNeeded(userId);
666 } else if (mHideErrorDialogsUri.equals(uri)) {
667 synchronized (mGlobalLock) {
668 updateShouldShowDialogsLocked(getGlobalConfiguration());
669 }
670 }
671 }
672 }
673
Riddle Hsua0536432019-02-16 00:38:59 +0800674 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
675 @Target(ElementType.METHOD)
676 @Retention(RetentionPolicy.SOURCE)
677 @interface HotPath {
678 int NONE = 0;
679 int OOM_ADJUSTMENT = 1;
680 int LRU_UPDATE = 2;
681 int PROCESS_CHANGE = 3;
682 int caller() default NONE;
683 }
684
Charles Chen8d98dd22018-12-26 17:36:54 +0800685 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
686 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700687 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700688 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 mSystemThread = ActivityThread.currentActivityThread();
690 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700691 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800692 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700693 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700694 }
695
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 public void onSystemReady() {
697 synchronized (mGlobalLock) {
698 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
699 PackageManager.FEATURE_CANT_SAVE_STATE);
700 mAssistUtils = new AssistUtils(mContext);
701 mVrController.onSystemReady();
702 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700703 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700704 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void onInitPowerManagement() {
708 synchronized (mGlobalLock) {
709 mStackSupervisor.initPowerManagement();
710 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
711 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
712 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
713 mVoiceWakeLock.setReferenceCounted(false);
714 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700718 mFontScaleSettingObserver = new FontScaleSettingObserver();
719 }
720
Wale Ogunwale59507092018-10-29 09:00:30 -0700721 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722 final boolean freeformWindowManagement =
723 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
724 || Settings.Global.getInt(
725 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
726
727 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
728 final boolean supportsPictureInPicture = supportsMultiWindow &&
729 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
730 final boolean supportsSplitScreenMultiWindow =
731 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
732 final boolean supportsMultiDisplay = mContext.getPackageManager()
733 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
735 final boolean forceResizable = Settings.Global.getInt(
736 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700737 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700738
739 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900740 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700741
742 final Configuration configuration = new Configuration();
743 Settings.System.getConfiguration(resolver, configuration);
744 if (forceRtl) {
745 // This will take care of setting the correct layout direction flags
746 configuration.setLayoutDirection(configuration.locale);
747 }
748
749 synchronized (mGlobalLock) {
750 mForceResizableActivities = forceResizable;
751 final boolean multiWindowFormEnabled = freeformWindowManagement
752 || supportsSplitScreenMultiWindow
753 || supportsPictureInPicture
754 || supportsMultiDisplay;
755 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
756 mSupportsMultiWindow = true;
757 mSupportsFreeformWindowManagement = freeformWindowManagement;
758 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
759 mSupportsPictureInPicture = supportsPictureInPicture;
760 mSupportsMultiDisplay = supportsMultiDisplay;
761 } else {
762 mSupportsMultiWindow = false;
763 mSupportsFreeformWindowManagement = false;
764 mSupportsSplitScreenMultiWindow = false;
765 mSupportsPictureInPicture = false;
766 mSupportsMultiDisplay = false;
767 }
768 mWindowManager.setForceResizableTasks(mForceResizableActivities);
769 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700770 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
771 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700772 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 // This happens before any activities are started, so we can change global configuration
774 // in-place.
775 updateConfigurationLocked(configuration, null, true);
776 final Configuration globalConfig = getGlobalConfiguration();
777 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
778
779 // Load resources only after the current configuration has been set.
780 final Resources res = mContext.getResources();
781 mThumbnailWidth = res.getDimensionPixelSize(
782 com.android.internal.R.dimen.thumbnail_width);
783 mThumbnailHeight = res.getDimensionPixelSize(
784 com.android.internal.R.dimen.thumbnail_height);
785
786 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
787 mFullscreenThumbnailScale = (float) res
788 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
789 (float) globalConfig.screenWidthDp;
790 } else {
791 mFullscreenThumbnailScale = res.getFraction(
792 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
793 }
794 }
795 }
796
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800797 public WindowManagerGlobalLock getGlobalLock() {
798 return mGlobalLock;
799 }
800
Yunfan Chen585f2932019-01-29 16:04:45 +0900801 /** For test purpose only. */
802 @VisibleForTesting
803 public ActivityTaskManagerInternal getAtmInternal() {
804 return mInternal;
805 }
806
Riddle Hsud93a6c42018-11-29 21:50:06 +0800807 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
808 Looper looper) {
809 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700812 final File systemDir = SystemServiceManager.ensureSystemDir();
813 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
814 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700815 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700816
817 mTempConfig.setToDefaults();
818 mTempConfig.setLocales(LocaleList.getDefault());
819 mConfigurationSeq = mTempConfig.seq = 1;
820 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800821 mRootActivityContainer = new RootActivityContainer(this);
822 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700824 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700826 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700827 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700828 mRecentTasks = createRecentTasks();
829 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700830 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700831 mKeyguardController = mStackSupervisor.getKeyguardController();
832 }
833
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700834 public void onActivityManagerInternalAdded() {
835 synchronized (mGlobalLock) {
836 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
837 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
838 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700839 }
840
Yunfan Chen75157d72018-07-27 14:47:21 +0900841 int increaseConfigurationSeqLocked() {
842 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
843 return mConfigurationSeq;
844 }
845
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700846 protected ActivityStackSupervisor createStackSupervisor() {
847 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
848 supervisor.initialize();
849 return supervisor;
850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setWindowManager(WindowManagerService wm) {
853 synchronized (mGlobalLock) {
854 mWindowManager = wm;
855 mLockTaskController.setWindowManager(wm);
856 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800857 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 }
860
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700861 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
862 synchronized (mGlobalLock) {
863 mUsageStatsInternal = usageStatsManager;
864 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700865 }
866
Wale Ogunwalef6733932018-06-27 05:14:34 -0700867 UserManagerService getUserManager() {
868 if (mUserManager == null) {
869 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
870 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
871 }
872 return mUserManager;
873 }
874
875 AppOpsService getAppOpsService() {
876 if (mAppOpsService == null) {
877 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
878 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
879 }
880 return mAppOpsService;
881 }
882
883 boolean hasUserRestriction(String restriction, int userId) {
884 return getUserManager().hasUserRestriction(restriction, userId);
885 }
886
Michal Karpinski15486842019-04-25 17:33:42 +0100887 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
888 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
889 callingUid, callingPackage);
890 if (mode == AppOpsManager.MODE_DEFAULT) {
891 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
892 == PERMISSION_GRANTED;
893 }
894 return mode == AppOpsManager.MODE_ALLOWED;
895 }
896
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700897 protected RecentTasks createRecentTasks() {
898 return new RecentTasks(this, mStackSupervisor);
899 }
900
901 RecentTasks getRecentTasks() {
902 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700903 }
904
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700905 ClientLifecycleManager getLifecycleManager() {
906 return mLifecycleManager;
907 }
908
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700909 ActivityStartController getActivityStartController() {
910 return mActivityStartController;
911 }
912
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700913 TaskChangeNotificationController getTaskChangeNotificationController() {
914 return mTaskChangeNotificationController;
915 }
916
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700917 LockTaskController getLockTaskController() {
918 return mLockTaskController;
919 }
920
Yunfan Chen75157d72018-07-27 14:47:21 +0900921 /**
922 * Return the global configuration used by the process corresponding to the input pid. This is
923 * usually the global configuration with some overrides specific to that process.
924 */
925 Configuration getGlobalConfigurationForCallingPid() {
926 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800927 return getGlobalConfigurationForPid(pid);
928 }
929
930 /**
931 * Return the global configuration used by the process corresponding to the given pid.
932 */
933 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900934 if (pid == MY_PID || pid < 0) {
935 return getGlobalConfiguration();
936 }
937 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100938 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 return app != null ? app.getConfiguration() : getGlobalConfiguration();
940 }
941 }
942
943 /**
944 * Return the device configuration info used by the process corresponding to the input pid.
945 * The value is consistent with the global configuration for the process.
946 */
947 @Override
948 public ConfigurationInfo getDeviceConfigurationInfo() {
949 ConfigurationInfo config = new ConfigurationInfo();
950 synchronized (mGlobalLock) {
951 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
952 config.reqTouchScreen = globalConfig.touchscreen;
953 config.reqKeyboardType = globalConfig.keyboard;
954 config.reqNavigation = globalConfig.navigation;
955 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
956 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
957 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
958 }
959 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
960 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
961 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
962 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700963 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900964 }
965 return config;
966 }
967
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700968 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700969 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700970 }
971
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700972 public static final class Lifecycle extends SystemService {
973 private final ActivityTaskManagerService mService;
974
975 public Lifecycle(Context context) {
976 super(context);
977 mService = new ActivityTaskManagerService(context);
978 }
979
980 @Override
981 public void onStart() {
982 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700983 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700984 }
985
Garfield Tan891146c2018-10-09 12:14:00 -0700986 @Override
987 public void onUnlockUser(int userId) {
988 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800989 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700990 }
991 }
992
993 @Override
994 public void onCleanupUser(int userId) {
995 synchronized (mService.getGlobalLock()) {
996 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
997 }
998 }
999
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 public ActivityTaskManagerService getService() {
1001 return mService;
1002 }
1003 }
1004
1005 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 public final int startActivity(IApplicationThread caller, String callingPackage,
1007 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1008 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1009 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1010 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1011 UserHandle.getCallingUserId());
1012 }
1013
1014 @Override
1015 public final int startActivities(IApplicationThread caller, String callingPackage,
1016 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1017 int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001018 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001020 enforceNotIsolatedCaller(reason);
1021 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001023 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1024 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1025 reason, null /* originatingPendingIntent */,
1026 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1031 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1032 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1033 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1034 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1035 true /*validateIncomingUser*/);
1036 }
1037
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001038 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1040 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1041 boolean validateIncomingUser) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001042 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001043 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001045 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1047
1048 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001049 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 .setCaller(caller)
1051 .setCallingPackage(callingPackage)
1052 .setResolvedType(resolvedType)
1053 .setResultTo(resultTo)
1054 .setResultWho(resultWho)
1055 .setRequestCode(requestCode)
1056 .setStartFlags(startFlags)
1057 .setProfilerInfo(profilerInfo)
1058 .setActivityOptions(bOptions)
1059 .setMayWait(userId)
1060 .execute();
1061
1062 }
1063
1064 @Override
1065 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1066 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001067 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1068 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 // Refuse possible leaked file descriptors
1070 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1071 throw new IllegalArgumentException("File descriptors passed in Intent");
1072 }
1073
1074 if (!(target instanceof PendingIntentRecord)) {
1075 throw new IllegalArgumentException("Bad PendingIntent object");
1076 }
1077
1078 PendingIntentRecord pir = (PendingIntentRecord)target;
1079
1080 synchronized (mGlobalLock) {
1081 // If this is coming from the currently resumed activity, it is
1082 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001083 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 if (stack.mResumedActivity != null &&
1085 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001086 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 }
1088 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001089 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 }
1092
1093 @Override
1094 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1095 Bundle bOptions) {
1096 // Refuse possible leaked file descriptors
1097 if (intent != null && intent.hasFileDescriptors()) {
1098 throw new IllegalArgumentException("File descriptors passed in Intent");
1099 }
1100 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1101
1102 synchronized (mGlobalLock) {
1103 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1104 if (r == null) {
1105 SafeActivityOptions.abort(options);
1106 return false;
1107 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001108 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001109 // The caller is not running... d'oh!
1110 SafeActivityOptions.abort(options);
1111 return false;
1112 }
1113 intent = new Intent(intent);
1114 // The caller is not allowed to change the data.
1115 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1116 // And we are resetting to find the next component...
1117 intent.setComponent(null);
1118
1119 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1120
1121 ActivityInfo aInfo = null;
1122 try {
1123 List<ResolveInfo> resolves =
1124 AppGlobals.getPackageManager().queryIntentActivities(
1125 intent, r.resolvedType,
1126 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1127 UserHandle.getCallingUserId()).getList();
1128
1129 // Look for the original activity in the list...
1130 final int N = resolves != null ? resolves.size() : 0;
1131 for (int i=0; i<N; i++) {
1132 ResolveInfo rInfo = resolves.get(i);
1133 if (rInfo.activityInfo.packageName.equals(r.packageName)
1134 && rInfo.activityInfo.name.equals(r.info.name)) {
1135 // We found the current one... the next matching is
1136 // after it.
1137 i++;
1138 if (i<N) {
1139 aInfo = resolves.get(i).activityInfo;
1140 }
1141 if (debug) {
1142 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1143 + "/" + r.info.name);
1144 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1145 ? "null" : aInfo.packageName + "/" + aInfo.name));
1146 }
1147 break;
1148 }
1149 }
1150 } catch (RemoteException e) {
1151 }
1152
1153 if (aInfo == null) {
1154 // Nobody who is next!
1155 SafeActivityOptions.abort(options);
1156 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1157 return false;
1158 }
1159
1160 intent.setComponent(new ComponentName(
1161 aInfo.applicationInfo.packageName, aInfo.name));
1162 intent.setFlags(intent.getFlags()&~(
1163 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1164 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1165 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1166 FLAG_ACTIVITY_NEW_TASK));
1167
1168 // Okay now we need to start the new activity, replacing the currently running activity.
1169 // This is a little tricky because we want to start the new one as if the current one is
1170 // finished, but not finish the current one first so that there is no flicker.
1171 // And thus...
1172 final boolean wasFinishing = r.finishing;
1173 r.finishing = true;
1174
1175 // Propagate reply information over to the new activity.
1176 final ActivityRecord resultTo = r.resultTo;
1177 final String resultWho = r.resultWho;
1178 final int requestCode = r.requestCode;
1179 r.resultTo = null;
1180 if (resultTo != null) {
1181 resultTo.removeResultsLocked(r, resultWho, requestCode);
1182 }
1183
1184 final long origId = Binder.clearCallingIdentity();
1185 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001186 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001187 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001188 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001189 .setResolvedType(r.resolvedType)
1190 .setActivityInfo(aInfo)
1191 .setResultTo(resultTo != null ? resultTo.appToken : null)
1192 .setResultWho(resultWho)
1193 .setRequestCode(requestCode)
1194 .setCallingPid(-1)
1195 .setCallingUid(r.launchedFromUid)
1196 .setCallingPackage(r.launchedFromPackage)
1197 .setRealCallingPid(-1)
1198 .setRealCallingUid(r.launchedFromUid)
1199 .setActivityOptions(options)
1200 .execute();
1201 Binder.restoreCallingIdentity(origId);
1202
1203 r.finishing = wasFinishing;
1204 if (res != ActivityManager.START_SUCCESS) {
1205 return false;
1206 }
1207 return true;
1208 }
1209 }
1210
1211 @Override
1212 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1213 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1214 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001215 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 final WaitResult res = new WaitResult();
1217 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001218 enforceNotIsolatedCaller("startActivityAndWait");
1219 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1220 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001222 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001223 .setCaller(caller)
1224 .setCallingPackage(callingPackage)
1225 .setResolvedType(resolvedType)
1226 .setResultTo(resultTo)
1227 .setResultWho(resultWho)
1228 .setRequestCode(requestCode)
1229 .setStartFlags(startFlags)
1230 .setActivityOptions(bOptions)
1231 .setMayWait(userId)
1232 .setProfilerInfo(profilerInfo)
1233 .setWaitResult(res)
1234 .execute();
1235 }
1236 return res;
1237 }
1238
1239 @Override
1240 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1241 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1242 int startFlags, Configuration config, Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001243 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001245 enforceNotIsolatedCaller("startActivityWithConfig");
1246 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1247 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001248 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001249 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001250 .setCaller(caller)
1251 .setCallingPackage(callingPackage)
1252 .setResolvedType(resolvedType)
1253 .setResultTo(resultTo)
1254 .setResultWho(resultWho)
1255 .setRequestCode(requestCode)
1256 .setStartFlags(startFlags)
1257 .setGlobalConfiguration(config)
1258 .setActivityOptions(bOptions)
1259 .setMayWait(userId)
1260 .execute();
1261 }
1262 }
1263
Alison Cichowlas3e340502018-08-07 17:15:01 -04001264
1265 @Override
1266 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1267 int callingUid = Binder.getCallingUid();
1268 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1269 throw new SecurityException("Only the system process can request a permission token, "
1270 + "received request from uid: " + callingUid);
1271 }
1272 IBinder permissionToken = new Binder();
1273 synchronized (mGlobalLock) {
1274 mStartActivitySources.put(permissionToken, delegatorToken);
1275 }
1276
1277 Message expireMsg = PooledLambda.obtainMessage(
1278 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1279 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1280
1281 Message forgetMsg = PooledLambda.obtainMessage(
1282 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1283 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1284
1285 return permissionToken;
1286 }
1287
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 @Override
1289 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1290 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001291 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1292 boolean ignoreTargetSecurity, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001293 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001294 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 // permission grants) as any app that may launch one of your own activities. So we only
1296 // allow this in two cases:
1297 // 1) The caller is an activity that is part of the core framework, and then only when it
1298 // is running as the system.
1299 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1300 // can only be requested by a system activity, which may then delegate this call to
1301 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001302 final ActivityRecord sourceRecord;
1303 final int targetUid;
1304 final String targetPackage;
1305 final boolean isResolver;
1306 synchronized (mGlobalLock) {
1307 if (resultTo == null) {
1308 throw new SecurityException("Must be called from an activity");
1309 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001310 final IBinder sourceToken;
1311 if (permissionToken != null) {
1312 // To even attempt to use a permissionToken, an app must also have this signature
1313 // permission.
1314 mAmInternal.enforceCallingPermission(
1315 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1316 "startActivityAsCaller");
1317 // If called with a permissionToken, we want the sourceRecord from the delegator
1318 // activity that requested this token.
1319 sourceToken = mStartActivitySources.remove(permissionToken);
1320 if (sourceToken == null) {
1321 // Invalid permissionToken, check if it recently expired.
1322 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1323 throw new SecurityException("Called with expired permission token: "
1324 + permissionToken);
1325 } else {
1326 throw new SecurityException("Called with invalid permission token: "
1327 + permissionToken);
1328 }
1329 }
1330 } else {
1331 // This method was called directly by the source.
1332 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001333 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001334
Wale Ogunwaled32da472018-11-16 07:19:28 -08001335 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001336 if (sourceRecord == null) {
1337 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 }
1339 if (sourceRecord.app == null) {
1340 throw new SecurityException("Called without a process attached to activity");
1341 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001342
1343 // Whether called directly or from a delegate, the source activity must be from the
1344 // android package.
1345 if (!sourceRecord.info.packageName.equals("android")) {
1346 throw new SecurityException("Must be called from an activity that is "
1347 + "declared in the android package");
1348 }
1349
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001350 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 // This is still okay, as long as this activity is running under the
1352 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001353 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001355 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 + " must be system uid or original calling uid "
1357 + sourceRecord.launchedFromUid);
1358 }
1359 }
1360 if (ignoreTargetSecurity) {
1361 if (intent.getComponent() == null) {
1362 throw new SecurityException(
1363 "Component must be specified with ignoreTargetSecurity");
1364 }
1365 if (intent.getSelector() != null) {
1366 throw new SecurityException(
1367 "Selector not allowed with ignoreTargetSecurity");
1368 }
1369 }
1370 targetUid = sourceRecord.launchedFromUid;
1371 targetPackage = sourceRecord.launchedFromPackage;
1372 isResolver = sourceRecord.isResolverOrChildActivity();
1373 }
1374
1375 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001376 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 }
1378
1379 // TODO: Switch to user app stacks here.
1380 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001381 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001382 .setCallingUid(targetUid)
1383 .setCallingPackage(targetPackage)
1384 .setResolvedType(resolvedType)
1385 .setResultTo(resultTo)
1386 .setResultWho(resultWho)
1387 .setRequestCode(requestCode)
1388 .setStartFlags(startFlags)
1389 .setActivityOptions(bOptions)
1390 .setMayWait(userId)
1391 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1392 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001393 // The target may well be in the background, which would normally prevent it
1394 // from starting an activity. Here we definitely want the start to succeed.
1395 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .execute();
1397 } catch (SecurityException e) {
1398 // XXX need to figure out how to propagate to original app.
1399 // A SecurityException here is generally actually a fault of the original
1400 // calling activity (such as a fairly granting permissions), so propagate it
1401 // back to them.
1402 /*
1403 StringBuilder msg = new StringBuilder();
1404 msg.append("While launching");
1405 msg.append(intent.toString());
1406 msg.append(": ");
1407 msg.append(e.getMessage());
1408 */
1409 throw e;
1410 }
1411 }
1412
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1414 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1415 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1416 }
1417
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 @Override
1419 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1420 Intent intent, String resolvedType, IVoiceInteractionSession session,
1421 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1422 Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001423 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001424 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 if (session == null || interactor == null) {
1426 throw new NullPointerException("null session or interactor");
1427 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001430 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 .setCallingUid(callingUid)
1432 .setCallingPackage(callingPackage)
1433 .setResolvedType(resolvedType)
1434 .setVoiceSession(session)
1435 .setVoiceInteractor(interactor)
1436 .setStartFlags(startFlags)
1437 .setProfilerInfo(profilerInfo)
1438 .setActivityOptions(bOptions)
1439 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001440 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 .execute();
1442 }
1443
1444 @Override
1445 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1446 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07001447 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001448 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1449 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001451 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .setCallingUid(callingUid)
1453 .setCallingPackage(callingPackage)
1454 .setResolvedType(resolvedType)
1455 .setActivityOptions(bOptions)
1456 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001457 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 .execute();
1459 }
1460
Riddle Hsu609a8e22019-06-27 16:46:29 -06001461 /**
1462 * Start the recents activity to perform the recents animation.
1463 *
1464 * @param intent The intent to start the recents activity.
1465 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1466 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1469 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001470 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 final int callingPid = Binder.getCallingPid();
1472 final long origId = Binder.clearCallingIdentity();
1473 try {
1474 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001475 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1476 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477
1478 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001479 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001480 getActivityStartController(), mWindowManager, intent, recentsComponent,
1481 recentsUid, callingPid);
1482 if (recentsAnimationRunner == null) {
1483 anim.preloadRecentsActivity();
1484 } else {
1485 anim.startRecentsActivity(recentsAnimationRunner);
1486 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001487 }
1488 } finally {
1489 Binder.restoreCallingIdentity(origId);
1490 }
1491 }
1492
1493 @Override
1494 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001495 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 "startActivityFromRecents()");
1497
1498 final int callingPid = Binder.getCallingPid();
1499 final int callingUid = Binder.getCallingUid();
1500 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1501 final long origId = Binder.clearCallingIdentity();
1502 try {
1503 synchronized (mGlobalLock) {
1504 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1505 safeOptions);
1506 }
1507 } finally {
1508 Binder.restoreCallingIdentity(origId);
1509 }
1510 }
1511
1512 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001513 * Public API to check if the client is allowed to start an activity on specified display.
1514 *
1515 * If the target display is private or virtual, some restrictions will apply.
1516 *
1517 * @param displayId Target display id.
1518 * @param intent Intent used to launch the activity.
1519 * @param resolvedType The MIME type of the intent.
1520 * @param userId The id of the user for whom the call is made.
1521 * @return {@code true} if a call to start an activity on the target display should succeed and
1522 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1523 */
1524 @Override
1525 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1526 String resolvedType, int userId) {
1527 final int callingUid = Binder.getCallingUid();
1528 final int callingPid = Binder.getCallingPid();
1529 final long origId = Binder.clearCallingIdentity();
1530
1531 try {
1532 // Collect information about the target of the Intent.
1533 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1534 0 /* startFlags */, null /* profilerInfo */, userId,
1535 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1536 UserHandle.USER_NULL));
1537 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1538
1539 synchronized (mGlobalLock) {
1540 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1541 aInfo);
1542 }
1543 } finally {
1544 Binder.restoreCallingIdentity(origId);
1545 }
1546 }
1547
1548 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001549 * This is the internal entry point for handling Activity.finish().
1550 *
1551 * @param token The Binder token referencing the Activity we want to finish.
1552 * @param resultCode Result code, if any, from this Activity.
1553 * @param resultData Result data (Intent), if any, from this Activity.
1554 * @param finishTask Whether to finish the task associated with this Activity.
1555 *
1556 * @return Returns true if the activity successfully finished, or false if it is still running.
1557 */
1558 @Override
1559 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1560 int finishTask) {
1561 // Refuse possible leaked file descriptors
1562 if (resultData != null && resultData.hasFileDescriptors()) {
1563 throw new IllegalArgumentException("File descriptors passed in Intent");
1564 }
1565
1566 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001567 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 if (r == null) {
1569 return true;
1570 }
1571 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001572 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 ActivityRecord rootR = tr.getRootActivity();
1574 if (rootR == null) {
1575 Slog.w(TAG, "Finishing task with all activities already finished");
1576 }
1577 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1578 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001579 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 return false;
1581 }
1582
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001583 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1584 // We should consolidate.
1585 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001587 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 if (next != null) {
1589 // ask watcher if this is allowed
1590 boolean resumeOK = true;
1591 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001592 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001594 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 Watchdog.getInstance().setActivityController(null);
1596 }
1597
1598 if (!resumeOK) {
1599 Slog.i(TAG, "Not finishing activity because controller resumed");
1600 return false;
1601 }
1602 }
1603 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001604
1605 // note down that the process has finished an activity and is in background activity
1606 // starts grace period
1607 if (r.app != null) {
1608 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1609 }
1610
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 final long origId = Binder.clearCallingIdentity();
1612 try {
1613 boolean res;
1614 final boolean finishWithRootActivity =
1615 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1616 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1617 || (finishWithRootActivity && r == rootR)) {
1618 // If requested, remove the task that is associated to this activity only if it
1619 // was the root activity in the task. The result code and data is ignored
1620 // because we don't support returning them across task boundaries. Also, to
1621 // keep backwards compatibility we remove the task from recents when finishing
1622 // task with root activity.
1623 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1624 finishWithRootActivity, "finish-activity");
1625 if (!res) {
1626 Slog.i(TAG, "Removing task failed to finish activity");
1627 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001628 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001629 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001630 } else {
1631 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001632 resultData, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001633 if (!res) {
1634 Slog.i(TAG, "Failed to finish by app-request");
1635 }
1636 }
1637 return res;
1638 } finally {
1639 Binder.restoreCallingIdentity(origId);
1640 }
1641 }
1642 }
1643
1644 @Override
1645 public boolean finishActivityAffinity(IBinder token) {
1646 synchronized (mGlobalLock) {
1647 final long origId = Binder.clearCallingIdentity();
1648 try {
1649 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1650 if (r == null) {
1651 return false;
1652 }
1653
1654 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1655 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001656 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001657 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 return false;
1659 }
1660 return task.getStack().finishActivityAffinityLocked(r);
1661 } finally {
1662 Binder.restoreCallingIdentity(origId);
1663 }
1664 }
1665 }
1666
1667 @Override
1668 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1669 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001670 try {
1671 WindowProcessController proc = null;
1672 synchronized (mGlobalLock) {
1673 ActivityStack stack = ActivityRecord.getStackLocked(token);
1674 if (stack == null) {
1675 return;
1676 }
1677 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1678 false /* fromTimeout */, false /* processPausingActivities */, config);
1679 if (r != null) {
1680 proc = r.app;
1681 }
1682 if (stopProfiling && proc != null) {
1683 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001686 } finally {
1687 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001688 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
1690
1691 @Override
1692 public final void activityResumed(IBinder token) {
1693 final long origId = Binder.clearCallingIdentity();
1694 synchronized (mGlobalLock) {
1695 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001696 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 }
1698 Binder.restoreCallingIdentity(origId);
1699 }
1700
1701 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001702 public final void activityTopResumedStateLost() {
1703 final long origId = Binder.clearCallingIdentity();
1704 synchronized (mGlobalLock) {
1705 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1706 }
1707 Binder.restoreCallingIdentity(origId);
1708 }
1709
1710 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 public final void activityPaused(IBinder token) {
1712 final long origId = Binder.clearCallingIdentity();
1713 synchronized (mGlobalLock) {
1714 ActivityStack stack = ActivityRecord.getStackLocked(token);
1715 if (stack != null) {
1716 stack.activityPausedLocked(token, false);
1717 }
1718 }
1719 Binder.restoreCallingIdentity(origId);
1720 }
1721
1722 @Override
1723 public final void activityStopped(IBinder token, Bundle icicle,
1724 PersistableBundle persistentState, CharSequence description) {
1725 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1726
1727 // Refuse possible leaked file descriptors
1728 if (icicle != null && icicle.hasFileDescriptors()) {
1729 throw new IllegalArgumentException("File descriptors passed in Bundle");
1730 }
1731
1732 final long origId = Binder.clearCallingIdentity();
1733
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001734 String restartingName = null;
1735 int restartingUid = 0;
1736 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001738 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001740 if (r.attachedToProcess()
1741 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1742 // The activity was requested to restart from
1743 // {@link #restartActivityProcessIfVisible}.
1744 restartingName = r.app.mName;
1745 restartingUid = r.app.mUid;
1746 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 r.activityStoppedLocked(icicle, persistentState, description);
1748 }
1749 }
1750
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001751 if (restartingName != null) {
1752 // In order to let the foreground activity can be restarted with its saved state from
1753 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1754 // until the activity reports stopped with the state. And the activity record will be
1755 // kept because the record state is restarting, then the activity will be restarted
1756 // immediately if it is still the top one.
1757 mStackSupervisor.removeRestartTimeouts(r);
1758 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1759 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001760 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761
1762 Binder.restoreCallingIdentity(origId);
1763 }
1764
1765 @Override
1766 public final void activityDestroyed(IBinder token) {
1767 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1768 synchronized (mGlobalLock) {
1769 ActivityStack stack = ActivityRecord.getStackLocked(token);
1770 if (stack != null) {
1771 stack.activityDestroyedLocked(token, "activityDestroyed");
1772 }
1773 }
1774 }
1775
1776 @Override
1777 public final void activityRelaunched(IBinder token) {
1778 final long origId = Binder.clearCallingIdentity();
1779 synchronized (mGlobalLock) {
1780 mStackSupervisor.activityRelaunchedLocked(token);
1781 }
1782 Binder.restoreCallingIdentity(origId);
1783 }
1784
1785 public final void activitySlept(IBinder token) {
1786 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1787
1788 final long origId = Binder.clearCallingIdentity();
1789
1790 synchronized (mGlobalLock) {
1791 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1792 if (r != null) {
1793 mStackSupervisor.activitySleptLocked(r);
1794 }
1795 }
1796
1797 Binder.restoreCallingIdentity(origId);
1798 }
1799
1800 @Override
1801 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1802 synchronized (mGlobalLock) {
1803 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1804 if (r == null) {
1805 return;
1806 }
1807 final long origId = Binder.clearCallingIdentity();
1808 try {
1809 r.setRequestedOrientation(requestedOrientation);
1810 } finally {
1811 Binder.restoreCallingIdentity(origId);
1812 }
1813 }
1814 }
1815
1816 @Override
1817 public int getRequestedOrientation(IBinder token) {
1818 synchronized (mGlobalLock) {
1819 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1820 if (r == null) {
1821 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1822 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001823 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 }
1825 }
1826
1827 @Override
1828 public void setImmersive(IBinder token, boolean immersive) {
1829 synchronized (mGlobalLock) {
1830 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1831 if (r == null) {
1832 throw new IllegalArgumentException();
1833 }
1834 r.immersive = immersive;
1835
1836 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001837 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001838 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842 }
1843
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001844 void applyUpdateLockStateLocked(ActivityRecord r) {
1845 // Modifications to the UpdateLock state are done on our handler, outside
1846 // the activity manager's locks. The new state is determined based on the
1847 // state *now* of the relevant activity record. The object is passed to
1848 // the handler solely for logging detail, not to be consulted/modified.
1849 final boolean nextState = r != null && r.immersive;
1850 mH.post(() -> {
1851 if (mUpdateLock.isHeld() != nextState) {
1852 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1853 "Applying new update lock state '" + nextState + "' for " + r);
1854 if (nextState) {
1855 mUpdateLock.acquire();
1856 } else {
1857 mUpdateLock.release();
1858 }
1859 }
1860 });
1861 }
1862
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 @Override
1864 public boolean isImmersive(IBinder token) {
1865 synchronized (mGlobalLock) {
1866 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1867 if (r == null) {
1868 throw new IllegalArgumentException();
1869 }
1870 return r.immersive;
1871 }
1872 }
1873
1874 @Override
1875 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001878 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 return (r != null) ? r.immersive : false;
1880 }
1881 }
1882
1883 @Override
1884 public void overridePendingTransition(IBinder token, String packageName,
1885 int enterAnim, int exitAnim) {
1886 synchronized (mGlobalLock) {
1887 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1888 if (self == null) {
1889 return;
1890 }
1891
1892 final long origId = Binder.clearCallingIdentity();
1893
1894 if (self.isState(
1895 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001896 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001897 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001898 }
1899
1900 Binder.restoreCallingIdentity(origId);
1901 }
1902 }
1903
1904 @Override
1905 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
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 return ActivityManager.COMPAT_MODE_UNKNOWN;
1911 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001912 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914 }
1915
1916 @Override
1917 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001922 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 if (r == null) {
1924 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1925 return;
1926 }
1927 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public int getLaunchedFromUid(IBinder activityToken) {
1934 ActivityRecord srec;
1935 synchronized (mGlobalLock) {
1936 srec = ActivityRecord.forTokenLocked(activityToken);
1937 }
1938 if (srec == null) {
1939 return -1;
1940 }
1941 return srec.launchedFromUid;
1942 }
1943
1944 @Override
1945 public String getLaunchedFromPackage(IBinder activityToken) {
1946 ActivityRecord srec;
1947 synchronized (mGlobalLock) {
1948 srec = ActivityRecord.forTokenLocked(activityToken);
1949 }
1950 if (srec == null) {
1951 return null;
1952 }
1953 return srec.launchedFromPackage;
1954 }
1955
1956 @Override
1957 public boolean convertFromTranslucent(IBinder token) {
1958 final long origId = Binder.clearCallingIdentity();
1959 try {
1960 synchronized (mGlobalLock) {
1961 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1962 if (r == null) {
1963 return false;
1964 }
1965 final boolean translucentChanged = r.changeWindowTranslucency(true);
1966 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001967 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001968 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001969 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 return translucentChanged;
1971 }
1972 } finally {
1973 Binder.restoreCallingIdentity(origId);
1974 }
1975 }
1976
1977 @Override
1978 public boolean convertToTranslucent(IBinder token, Bundle options) {
1979 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1980 final long origId = Binder.clearCallingIdentity();
1981 try {
1982 synchronized (mGlobalLock) {
1983 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1984 if (r == null) {
1985 return false;
1986 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001987 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 int index = task.mActivities.lastIndexOf(r);
1989 if (index > 0) {
1990 ActivityRecord under = task.mActivities.get(index - 1);
1991 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1992 }
1993 final boolean translucentChanged = r.changeWindowTranslucency(false);
1994 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001995 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001997 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001998 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 return translucentChanged;
2000 }
2001 } finally {
2002 Binder.restoreCallingIdentity(origId);
2003 }
2004 }
2005
2006 @Override
2007 public void notifyActivityDrawn(IBinder token) {
2008 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2009 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002010 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002012 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 }
2014 }
2015 }
2016
2017 @Override
2018 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2019 synchronized (mGlobalLock) {
2020 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2021 if (r == null) {
2022 return;
2023 }
2024 r.reportFullyDrawnLocked(restoredFromBundle);
2025 }
2026 }
2027
2028 @Override
2029 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2030 synchronized (mGlobalLock) {
2031 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2032 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2033 return stack.mDisplayId;
2034 }
2035 return DEFAULT_DISPLAY;
2036 }
2037 }
2038
2039 @Override
2040 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002041 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 long ident = Binder.clearCallingIdentity();
2043 try {
2044 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002045 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002047 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002048 }
2049 return null;
2050 }
2051 } finally {
2052 Binder.restoreCallingIdentity(ident);
2053 }
2054 }
2055
2056 @Override
2057 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002058 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2060 final long callingId = Binder.clearCallingIdentity();
2061 try {
2062 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002063 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (stack == null) {
2065 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2066 return;
2067 }
2068 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002069 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002070 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 }
2072 }
2073 } finally {
2074 Binder.restoreCallingIdentity(callingId);
2075 }
2076 }
2077
2078 @Override
2079 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002080 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2082 final long callingId = Binder.clearCallingIdentity();
2083 try {
2084 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002085 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002086 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 if (task == null) {
2088 return;
2089 }
2090 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002091 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002092 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002093 }
2094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(callingId);
2097 }
2098 }
2099
2100 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002101 public void restartActivityProcessIfVisible(IBinder activityToken) {
2102 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2103 final long callingId = Binder.clearCallingIdentity();
2104 try {
2105 synchronized (mGlobalLock) {
2106 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2107 if (r == null) {
2108 return;
2109 }
2110 r.restartProcessIfVisible();
2111 }
2112 } finally {
2113 Binder.restoreCallingIdentity(callingId);
2114 }
2115 }
2116
2117 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002119 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002120 synchronized (mGlobalLock) {
2121 final long ident = Binder.clearCallingIdentity();
2122 try {
2123 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2124 "remove-task");
2125 } finally {
2126 Binder.restoreCallingIdentity(ident);
2127 }
2128 }
2129 }
2130
2131 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002132 public void removeAllVisibleRecentTasks() {
2133 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2134 synchronized (mGlobalLock) {
2135 final long ident = Binder.clearCallingIdentity();
2136 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002137 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002138 } finally {
2139 Binder.restoreCallingIdentity(ident);
2140 }
2141 }
2142 }
2143
2144 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2146 synchronized (mGlobalLock) {
2147 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2148 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002149 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002150 }
2151 }
2152 return false;
2153 }
2154
2155 @Override
2156 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2157 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002158
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002159 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002160 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2161 if (r != null) {
2162 return r.getActivityStack().navigateUpToLocked(
2163 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002164 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002165 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 }
2167 }
2168
2169 /**
2170 * Attempts to move a task backwards in z-order (the order of activities within the task is
2171 * unchanged).
2172 *
2173 * There are several possible results of this call:
2174 * - if the task is locked, then we will show the lock toast
2175 * - if there is a task behind the provided task, then that task is made visible and resumed as
2176 * this task is moved to the back
2177 * - otherwise, if there are no other tasks in the stack:
2178 * - if this task is in the pinned stack, then we remove the stack completely, which will
2179 * have the effect of moving the task to the top or bottom of the fullscreen stack
2180 * (depending on whether it is visible)
2181 * - otherwise, we simply return home and hide this task
2182 *
2183 * @param token A reference to the activity we wish to move
2184 * @param nonRoot If false then this only works if the activity is the root
2185 * of a task; if true it will work for any activity in a task.
2186 * @return Returns true if the move completed, false if not.
2187 */
2188 @Override
2189 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002190 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 synchronized (mGlobalLock) {
2192 final long origId = Binder.clearCallingIdentity();
2193 try {
2194 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002195 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 if (task != null) {
2197 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2198 }
2199 } finally {
2200 Binder.restoreCallingIdentity(origId);
2201 }
2202 }
2203 return false;
2204 }
2205
2206 @Override
2207 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002208 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 long ident = Binder.clearCallingIdentity();
2210 Rect rect = new Rect();
2211 try {
2212 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002213 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2215 if (task == null) {
2216 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2217 return rect;
2218 }
2219 if (task.getStack() != null) {
2220 // Return the bounds from window manager since it will be adjusted for various
2221 // things like the presense of a docked stack for tasks that aren't resizeable.
2222 task.getWindowContainerBounds(rect);
2223 } else {
2224 // Task isn't in window manager yet since it isn't associated with a stack.
2225 // Return the persist value from activity manager
2226 if (!task.matchParentBounds()) {
2227 rect.set(task.getBounds());
2228 } else if (task.mLastNonFullscreenBounds != null) {
2229 rect.set(task.mLastNonFullscreenBounds);
2230 }
2231 }
2232 }
2233 } finally {
2234 Binder.restoreCallingIdentity(ident);
2235 }
2236 return rect;
2237 }
2238
2239 @Override
2240 public ActivityManager.TaskDescription getTaskDescription(int id) {
2241 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002242 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002244 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2246 if (tr != null) {
2247 return tr.lastTaskDescription;
2248 }
2249 }
2250 return null;
2251 }
2252
2253 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002254 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2255 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2256 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2257 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2258 return;
2259 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002260 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002261 synchronized (mGlobalLock) {
2262 final long ident = Binder.clearCallingIdentity();
2263 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002264 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002265 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 if (task == null) {
2267 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2268 return;
2269 }
2270
2271 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2272 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2273
2274 if (!task.isActivityTypeStandardOrUndefined()) {
2275 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2276 + " non-standard task " + taskId + " to windowing mode="
2277 + windowingMode);
2278 }
2279
2280 final ActivityStack stack = task.getStack();
2281 if (toTop) {
2282 stack.moveToFront("setTaskWindowingMode", task);
2283 }
2284 stack.setWindowingMode(windowingMode);
2285 } finally {
2286 Binder.restoreCallingIdentity(ident);
2287 }
2288 }
2289 }
2290
2291 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002293 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 ActivityRecord r = getCallingRecordLocked(token);
2295 return r != null ? r.info.packageName : null;
2296 }
2297 }
2298
2299 @Override
2300 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002301 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002302 ActivityRecord r = getCallingRecordLocked(token);
2303 return r != null ? r.intent.getComponent() : null;
2304 }
2305 }
2306
2307 private ActivityRecord getCallingRecordLocked(IBinder token) {
2308 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2309 if (r == null) {
2310 return null;
2311 }
2312 return r.resultTo;
2313 }
2314
2315 @Override
2316 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002317 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318
2319 synchronized (mGlobalLock) {
2320 final long origId = Binder.clearCallingIdentity();
2321 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002322 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323 } finally {
2324 Binder.restoreCallingIdentity(origId);
2325 }
2326 }
2327 }
2328
Mark Renouf446251d2019-04-26 10:22:41 -04002329 @Override
2330 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2331 synchronized (mGlobalLock) {
2332 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2333 if (r == null) {
2334 return;
2335 }
2336 ActivityStack stack = r.getActivityStack();
2337 if (stack != null && stack.isSingleTaskInstance()) {
2338 // Single-task stacks are used for activities which are presented in floating
2339 // windows above full screen activities. Instead of directly finishing the
2340 // task, a task change listener is used to notify SystemUI so the action can be
2341 // handled specially.
2342 final TaskRecord task = r.getTaskRecord();
2343 mTaskChangeNotificationController
2344 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2345 } else {
2346 try {
2347 callback.requestFinish();
2348 } catch (RemoteException e) {
2349 Slog.e(TAG, "Failed to invoke request finish callback", e);
2350 }
2351 }
2352 }
2353 }
2354
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 /**
2356 * TODO: Add mController hook
2357 */
2358 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002359 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2360 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002361 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002362
2363 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2364 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2366 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 }
2368 }
2369
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2371 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 final int callingPid = Binder.getCallingPid();
2374 final int callingUid = Binder.getCallingUid();
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002375 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002376 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 SafeActivityOptions.abort(options);
2378 return;
2379 }
2380 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002381 WindowProcessController callerApp = null;
2382 if (appThread != null) {
2383 callerApp = getProcessController(appThread);
2384 }
2385 final ActivityStarter starter = getActivityStartController().obtainStarter(
2386 null /* intent */, "moveTaskToFront");
2387 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2388 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002389 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002390 return;
2391 }
2392 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002394 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 if (task == null) {
2396 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002397 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 return;
2399 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002400 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002401 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002402 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 return;
2404 }
2405 ActivityOptions realOptions = options != null
2406 ? options.getOptions(mStackSupervisor)
2407 : null;
2408 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2409 false /* forceNonResizable */);
2410
2411 final ActivityRecord topActivity = task.getTopActivity();
2412 if (topActivity != null) {
2413
2414 // We are reshowing a task, use a starting window to hide the initial draw delay
2415 // so the transition can start earlier.
2416 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2417 true /* taskSwitch */, fromRecents);
2418 }
2419 } finally {
2420 Binder.restoreCallingIdentity(origId);
2421 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002422 }
2423
Ricky Waiaca8a772019-04-04 16:01:06 +01002424 /**
2425 * Return true if callingUid is system, or packageName belongs to that callingUid.
2426 */
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002427 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002428 try {
2429 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2430 if (packageName == null) {
2431 return false;
2432 }
2433 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2434 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2435 UserHandle.getUserId(callingUid));
2436 return UserHandle.isSameApp(callingUid, uid);
2437 }
2438 } catch (RemoteException e) {
2439 // Should not happen
2440 }
2441 return true;
2442 }
2443
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002444 /**
2445 * Checks that the provided package name matches the current calling UID, throws a security
2446 * exception if it doesn't.
2447 */
2448 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2449 final int callingUid = Binder.getCallingUid();
2450 if (isSameApp(callingUid, packageName)) {
2451 return;
2452 }
2453 final String msg = "Permission Denial: package=" + packageName
2454 + " does not belong to uid=" + callingUid;
2455 Slog.w(TAG, msg);
2456 throw new SecurityException(msg);
2457 }
2458
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002459 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2460 int callingPid, int callingUid, String name) {
2461 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2462 return true;
2463 }
2464
2465 if (getRecentTasks().isCallerRecents(sourceUid)) {
2466 return true;
2467 }
2468
2469 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2470 if (perm == PackageManager.PERMISSION_GRANTED) {
2471 return true;
2472 }
2473 if (checkAllowAppSwitchUid(sourceUid)) {
2474 return true;
2475 }
2476
2477 // If the actual IPC caller is different from the logical source, then
2478 // also see if they are allowed to control app switches.
2479 if (callingUid != -1 && callingUid != sourceUid) {
2480 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2481 if (perm == PackageManager.PERMISSION_GRANTED) {
2482 return true;
2483 }
2484 if (checkAllowAppSwitchUid(callingUid)) {
2485 return true;
2486 }
2487 }
2488
2489 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2490 return false;
2491 }
2492
2493 private boolean checkAllowAppSwitchUid(int uid) {
2494 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2495 if (types != null) {
2496 for (int i = types.size() - 1; i >= 0; i--) {
2497 if (types.valueAt(i).intValue() == uid) {
2498 return true;
2499 }
2500 }
2501 }
2502 return false;
2503 }
2504
2505 @Override
2506 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2507 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2508 "setActivityController()");
2509 synchronized (mGlobalLock) {
2510 mController = controller;
2511 mControllerIsAMonkey = imAMonkey;
2512 Watchdog.getInstance().setActivityController(controller);
2513 }
2514 }
2515
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002516 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002517 synchronized (mGlobalLock) {
2518 return mController != null && mControllerIsAMonkey;
2519 }
2520 }
2521
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002522 @Override
2523 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2524 synchronized (mGlobalLock) {
2525 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2526 }
2527 }
2528
2529 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002530 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2531 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2532 }
2533
2534 @Override
2535 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2536 @WindowConfiguration.ActivityType int ignoreActivityType,
2537 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2538 final int callingUid = Binder.getCallingUid();
2539 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2540
2541 synchronized (mGlobalLock) {
2542 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2543
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002545 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002546 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002547 ignoreWindowingMode, callingUid, allowed);
2548 }
2549
2550 return list;
2551 }
2552
2553 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2555 synchronized (mGlobalLock) {
2556 final long origId = Binder.clearCallingIdentity();
2557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2558 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002559 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560 }
2561 Binder.restoreCallingIdentity(origId);
2562 }
2563 }
2564
2565 @Override
2566 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002567 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002568 ActivityStack stack = ActivityRecord.getStackLocked(token);
2569 if (stack != null) {
2570 return stack.willActivityBeVisibleLocked(token);
2571 }
2572 return false;
2573 }
2574 }
2575
2576 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002578 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002579 synchronized (mGlobalLock) {
2580 final long ident = Binder.clearCallingIdentity();
2581 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002582 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002583 if (task == null) {
2584 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2585 return;
2586 }
2587
2588 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2589 + " to stackId=" + stackId + " toTop=" + toTop);
2590
Wale Ogunwaled32da472018-11-16 07:19:28 -08002591 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 if (stack == null) {
2593 throw new IllegalStateException(
2594 "moveTaskToStack: No stack for stackId=" + stackId);
2595 }
2596 if (!stack.isActivityTypeStandardOrUndefined()) {
2597 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2598 + taskId + " to stack " + stackId);
2599 }
2600 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002601 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2603 }
2604 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2605 "moveTaskToStack");
2606 } finally {
2607 Binder.restoreCallingIdentity(ident);
2608 }
2609 }
2610 }
2611
2612 @Override
2613 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2614 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002615 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616
2617 final long ident = Binder.clearCallingIdentity();
2618 try {
2619 synchronized (mGlobalLock) {
2620 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -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 }
2626 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2627 throw new IllegalArgumentException("Stack: " + stackId
2628 + " doesn't support animated resize.");
2629 }
2630 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2631 animationDuration, false /* fromFullscreen */);
2632 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002633 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002634 if (stack == null) {
2635 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2636 return;
2637 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002638 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002639 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2640 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2641 }
2642 }
2643 } finally {
2644 Binder.restoreCallingIdentity(ident);
2645 }
2646 }
2647
wilsonshih5c4cf522019-01-25 09:03:47 +08002648 @Override
2649 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2650 int animationDuration) {
2651 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2652
2653 final long ident = Binder.clearCallingIdentity();
2654 try {
2655 synchronized (mGlobalLock) {
2656 if (xOffset == 0 && yOffset == 0) {
2657 return;
2658 }
2659 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2660 if (stack == null) {
2661 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2662 return;
2663 }
2664 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2665 throw new IllegalArgumentException("Stack: " + stackId
2666 + " doesn't support animated resize.");
2667 }
2668 final Rect destBounds = new Rect();
2669 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002670 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002671 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2672 return;
2673 }
2674 destBounds.offset(xOffset, yOffset);
2675 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2676 animationDuration, false /* fromFullscreen */);
2677 }
2678 } finally {
2679 Binder.restoreCallingIdentity(ident);
2680 }
2681 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 /**
2683 * Moves the specified task to the primary-split-screen stack.
2684 *
2685 * @param taskId Id of task to move.
2686 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2687 * exist already. See
2688 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2689 * and
2690 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2691 * @param toTop If the task and stack should be moved to the top.
2692 * @param animate Whether we should play an animation for the moving the task.
2693 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2694 * stack. Pass {@code null} to use default bounds.
2695 * @param showRecents If the recents activity should be shown on the other side of the task
2696 * going into split-screen mode.
2697 */
2698 @Override
2699 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2700 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002701 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002702 "setTaskWindowingModeSplitScreenPrimary()");
2703 synchronized (mGlobalLock) {
2704 final long ident = Binder.clearCallingIdentity();
2705 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002706 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002707 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002708 if (task == null) {
2709 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2710 return false;
2711 }
2712 if (DEBUG_STACK) Slog.d(TAG_STACK,
2713 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2714 + " to createMode=" + createMode + " toTop=" + toTop);
2715 if (!task.isActivityTypeStandardOrUndefined()) {
2716 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2717 + " non-standard task " + taskId + " to split-screen windowing mode");
2718 }
2719
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002720 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 final int windowingMode = task.getWindowingMode();
2722 final ActivityStack stack = task.getStack();
2723 if (toTop) {
2724 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2725 }
2726 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002727 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2728 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002729 return windowingMode != task.getWindowingMode();
2730 } finally {
2731 Binder.restoreCallingIdentity(ident);
2732 }
2733 }
2734 }
2735
2736 /**
2737 * Removes stacks in the input windowing modes from the system if they are of activity type
2738 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2739 */
2740 @Override
2741 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002742 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002743 "removeStacksInWindowingModes()");
2744
2745 synchronized (mGlobalLock) {
2746 final long ident = Binder.clearCallingIdentity();
2747 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002748 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002749 } finally {
2750 Binder.restoreCallingIdentity(ident);
2751 }
2752 }
2753 }
2754
2755 @Override
2756 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002757 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002758 "removeStacksWithActivityTypes()");
2759
2760 synchronized (mGlobalLock) {
2761 final long ident = Binder.clearCallingIdentity();
2762 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002763 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002764 } finally {
2765 Binder.restoreCallingIdentity(ident);
2766 }
2767 }
2768 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769
2770 @Override
2771 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2772 int userId) {
2773 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002774 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2775 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002777 final boolean detailed = checkGetTasksPermission(
2778 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2779 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 == PackageManager.PERMISSION_GRANTED;
2781
2782 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002783 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 callingUid);
2785 }
2786 }
2787
2788 @Override
2789 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002790 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 long ident = Binder.clearCallingIdentity();
2792 try {
2793 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002794 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
2799 }
2800
2801 @Override
2802 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 long ident = Binder.clearCallingIdentity();
2805 try {
2806 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002807 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808 }
2809 } finally {
2810 Binder.restoreCallingIdentity(ident);
2811 }
2812 }
2813
2814 @Override
2815 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 final long callingUid = Binder.getCallingUid();
2818 final long origId = Binder.clearCallingIdentity();
2819 try {
2820 synchronized (mGlobalLock) {
2821 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002822 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2824 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2825 }
2826 } finally {
2827 Binder.restoreCallingIdentity(origId);
2828 }
2829 }
2830
2831 @Override
2832 public void startLockTaskModeByToken(IBinder token) {
2833 synchronized (mGlobalLock) {
2834 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2835 if (r == null) {
2836 return;
2837 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002838 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 }
2840 }
2841
2842 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002843 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002844 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 // This makes inner call to look as if it was initiated by system.
2846 long ident = Binder.clearCallingIdentity();
2847 try {
2848 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002849 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002850 MATCH_TASK_IN_STACKS_ONLY);
2851 if (task == null) {
2852 return;
2853 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854
2855 // When starting lock task mode the stack must be in front and focused
2856 task.getStack().moveToFront("startSystemLockTaskMode");
2857 startLockTaskModeLocked(task, true /* isSystemCaller */);
2858 }
2859 } finally {
2860 Binder.restoreCallingIdentity(ident);
2861 }
2862 }
2863
2864 @Override
2865 public void stopLockTaskModeByToken(IBinder token) {
2866 synchronized (mGlobalLock) {
2867 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2868 if (r == null) {
2869 return;
2870 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002871 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002872 }
2873 }
2874
2875 /**
2876 * This API should be called by SystemUI only when user perform certain action to dismiss
2877 * lock task mode. We should only dismiss pinned lock task mode in this case.
2878 */
2879 @Override
2880 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002881 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2883 }
2884
2885 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2886 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2887 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2888 return;
2889 }
2890
Wale Ogunwaled32da472018-11-16 07:19:28 -08002891 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 if (stack == null || task != stack.topTask()) {
2893 throw new IllegalArgumentException("Invalid task, not in foreground");
2894 }
2895
2896 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2897 // system or a specific app.
2898 // * System-initiated requests will only start the pinned mode (screen pinning)
2899 // * App-initiated requests
2900 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2901 // - will start the pinned mode, otherwise
2902 final int callingUid = Binder.getCallingUid();
2903 long ident = Binder.clearCallingIdentity();
2904 try {
2905 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002906 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002908 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 } finally {
2910 Binder.restoreCallingIdentity(ident);
2911 }
2912 }
2913
2914 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2915 final int callingUid = Binder.getCallingUid();
2916 long ident = Binder.clearCallingIdentity();
2917 try {
2918 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002919 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920 }
2921 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2922 // task and jumping straight into a call in the case of emergency call back.
2923 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2924 if (tm != null) {
2925 tm.showInCallScreen(false);
2926 }
2927 } finally {
2928 Binder.restoreCallingIdentity(ident);
2929 }
2930 }
2931
2932 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002933 public void updateLockTaskPackages(int userId, String[] packages) {
2934 final int callingUid = Binder.getCallingUid();
2935 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2936 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2937 "updateLockTaskPackages()");
2938 }
2939 synchronized (this) {
2940 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2941 + Arrays.toString(packages));
2942 getLockTaskController().updateLockTaskPackages(userId, packages);
2943 }
2944 }
2945
2946 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 public boolean isInLockTaskMode() {
2948 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2949 }
2950
2951 @Override
2952 public int getLockTaskModeState() {
2953 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002954 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 }
2956 }
2957
2958 @Override
2959 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2960 synchronized (mGlobalLock) {
2961 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2962 if (r != null) {
2963 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002964 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002966 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002967 }
2968 }
2969 }
2970
2971 @Override
2972 public Bundle getActivityOptions(IBinder token) {
2973 final long origId = Binder.clearCallingIdentity();
2974 try {
2975 synchronized (mGlobalLock) {
2976 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2977 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002978 final ActivityOptions activityOptions = r.takeOptionsLocked(
2979 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 return activityOptions == null ? null : activityOptions.toBundle();
2981 }
2982 return null;
2983 }
2984 } finally {
2985 Binder.restoreCallingIdentity(origId);
2986 }
2987 }
2988
2989 @Override
2990 public List<IBinder> getAppTasks(String callingPackage) {
2991 int callingUid = Binder.getCallingUid();
Andrii Kulianfbc35b92019-07-16 11:24:45 -07002992 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 long ident = Binder.clearCallingIdentity();
2994 try {
2995 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002996 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 }
2998 } finally {
2999 Binder.restoreCallingIdentity(ident);
3000 }
3001 }
3002
3003 @Override
3004 public void finishVoiceTask(IVoiceInteractionSession session) {
3005 synchronized (mGlobalLock) {
3006 final long origId = Binder.clearCallingIdentity();
3007 try {
3008 // TODO: VI Consider treating local voice interactions and voice tasks
3009 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003010 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 } finally {
3012 Binder.restoreCallingIdentity(origId);
3013 }
3014 }
3015
3016 }
3017
3018 @Override
3019 public boolean isTopOfTask(IBinder token) {
3020 synchronized (mGlobalLock) {
3021 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003022 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 }
3024 }
3025
3026 @Override
3027 public void notifyLaunchTaskBehindComplete(IBinder token) {
3028 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3029 }
3030
3031 @Override
3032 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003033 mH.post(() -> {
3034 synchronized (mGlobalLock) {
3035 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003036 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003037 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003038 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003039 } catch (RemoteException e) {
3040 }
3041 }
3042 }
3043
3044 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 }
3046
3047 /** Called from an app when assist data is ready. */
3048 @Override
3049 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3050 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 synchronized (pae) {
3053 pae.result = extras;
3054 pae.structure = structure;
3055 pae.content = content;
3056 if (referrer != null) {
3057 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3058 }
3059 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003060 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003061 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3062 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003063 structure.setHomeActivity(pae.isHome);
3064 }
3065 pae.haveResult = true;
3066 pae.notifyAll();
3067 if (pae.intent == null && pae.receiver == null) {
3068 // Caller is just waiting for the result.
3069 return;
3070 }
3071 }
3072 // We are now ready to launch the assist activity.
3073 IAssistDataReceiver sendReceiver = null;
3074 Bundle sendBundle = null;
3075 synchronized (mGlobalLock) {
3076 buildAssistBundleLocked(pae, extras);
3077 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003078 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 if (!exists) {
3080 // Timed out.
3081 return;
3082 }
3083
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003084 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 // Caller wants result sent back to them.
3086 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003087 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3088 pae.activity.getTaskRecord().taskId);
3089 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3090 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3092 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3093 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3094 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3095 }
3096 }
3097 if (sendReceiver != null) {
3098 try {
3099 sendReceiver.onHandleAssistData(sendBundle);
3100 } catch (RemoteException e) {
3101 }
3102 return;
3103 }
3104
3105 final long ident = Binder.clearCallingIdentity();
3106 try {
3107 if (TextUtils.equals(pae.intent.getAction(),
3108 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3109 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003110
3111 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 } else {
3113 pae.intent.replaceExtras(pae.extras);
3114 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3115 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3116 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003117 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118
3119 try {
3120 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3121 } catch (ActivityNotFoundException e) {
3122 Slog.w(TAG, "No activity to handle assist action.", e);
3123 }
3124 }
3125 } finally {
3126 Binder.restoreCallingIdentity(ident);
3127 }
3128 }
3129
Marvin Ramin830d4e32019-03-12 13:16:58 +01003130 /**
3131 * Workaround for historical API which starts the Assist service with a non-foreground
3132 * {@code startService()} call.
3133 */
3134 private void startVoiceInteractionServiceAsUser(
3135 Intent intent, int userHandle, String reason) {
3136 // Resolve the intent to find out which package we need to whitelist.
3137 ResolveInfo resolveInfo =
3138 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3139 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3140 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3141 return;
3142 }
3143 intent.setPackage(resolveInfo.serviceInfo.packageName);
3144
3145 // Whitelist background services temporarily.
3146 LocalServices.getService(DeviceIdleController.LocalService.class)
3147 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3148 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3149
3150 // Finally, try to start the service.
3151 try {
3152 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3153 } catch (RuntimeException e) {
3154 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3155 }
3156 }
3157
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 @Override
3159 public int addAppTask(IBinder activityToken, Intent intent,
3160 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3161 final int callingUid = Binder.getCallingUid();
3162 final long callingIdent = Binder.clearCallingIdentity();
3163
3164 try {
3165 synchronized (mGlobalLock) {
3166 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3167 if (r == null) {
3168 throw new IllegalArgumentException("Activity does not exist; token="
3169 + activityToken);
3170 }
3171 ComponentName comp = intent.getComponent();
3172 if (comp == null) {
3173 throw new IllegalArgumentException("Intent " + intent
3174 + " must specify explicit component");
3175 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003176 if (thumbnail.getWidth() != mThumbnailWidth
3177 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 throw new IllegalArgumentException("Bad thumbnail size: got "
3179 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 }
3182 if (intent.getSelector() != null) {
3183 intent.setSelector(null);
3184 }
3185 if (intent.getSourceBounds() != null) {
3186 intent.setSourceBounds(null);
3187 }
3188 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3189 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3190 // The caller has added this as an auto-remove task... that makes no
3191 // sense, so turn off auto-remove.
3192 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3193 }
3194 }
3195 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3196 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3197 if (ainfo.applicationInfo.uid != callingUid) {
3198 throw new SecurityException(
3199 "Can't add task for another application: target uid="
3200 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3201 }
3202
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003203 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003205 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003207 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 // The app has too many tasks already and we can't add any more
3209 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3210 return INVALID_TASK_ID;
3211 }
3212 task.lastTaskDescription.copyFrom(description);
3213
3214 // TODO: Send the thumbnail to WM to store it.
3215
3216 return task.taskId;
3217 }
3218 } finally {
3219 Binder.restoreCallingIdentity(callingIdent);
3220 }
3221 }
3222
3223 @Override
3224 public Point getAppTaskThumbnailSize() {
3225 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003226 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228 }
3229
3230 @Override
3231 public void setTaskResizeable(int taskId, int resizeableMode) {
3232 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003233 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3235 if (task == null) {
3236 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3237 return;
3238 }
3239 task.setResizeMode(resizeableMode);
3240 }
3241 }
3242
3243 @Override
3244 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 long ident = Binder.clearCallingIdentity();
3247 try {
3248 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003249 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003250 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 if (task == null) {
3252 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3253 return;
3254 }
3255 // Place the task in the right stack if it isn't there already based on
3256 // the requested bounds.
3257 // The stack transition logic is:
3258 // - a null bounds on a freeform task moves that task to fullscreen
3259 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3260 // that task to freeform
3261 // - otherwise the task is not moved
3262 ActivityStack stack = task.getStack();
3263 if (!task.getWindowConfiguration().canResizeTask()) {
3264 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3265 }
3266 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3267 stack = stack.getDisplay().getOrCreateStack(
3268 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3269 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3270 stack = stack.getDisplay().getOrCreateStack(
3271 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3272 }
3273
3274 // Reparent the task to the right stack if necessary
3275 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3276 if (stack != task.getStack()) {
3277 // Defer resume until the task is resized below
3278 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3279 DEFER_RESUME, "resizeTask");
3280 preserveWindow = false;
3281 }
3282
3283 // After reparenting (which only resizes the task to the stack bounds), resize the
3284 // task to the actual bounds provided
3285 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3286 }
3287 } finally {
3288 Binder.restoreCallingIdentity(ident);
3289 }
3290 }
3291
3292 @Override
3293 public boolean releaseActivityInstance(IBinder token) {
3294 synchronized (mGlobalLock) {
3295 final long origId = Binder.clearCallingIdentity();
3296 try {
3297 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3298 if (r == null) {
3299 return false;
3300 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003301 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 } finally {
3303 Binder.restoreCallingIdentity(origId);
3304 }
3305 }
3306 }
3307
3308 @Override
3309 public void releaseSomeActivities(IApplicationThread appInt) {
3310 synchronized (mGlobalLock) {
3311 final long origId = Binder.clearCallingIdentity();
3312 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003313 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003314 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 } finally {
3316 Binder.restoreCallingIdentity(origId);
3317 }
3318 }
3319 }
3320
3321 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003322 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003323 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 != PackageManager.PERMISSION_GRANTED) {
3325 throw new SecurityException("Requires permission "
3326 + android.Manifest.permission.DEVICE_POWER);
3327 }
3328
3329 synchronized (mGlobalLock) {
3330 long ident = Binder.clearCallingIdentity();
3331 if (mKeyguardShown != keyguardShowing) {
3332 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003333 final Message msg = PooledLambda.obtainMessage(
3334 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3335 keyguardShowing);
3336 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 }
3338 try {
wilsonshih177261f2019-02-22 12:02:18 +08003339 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 } finally {
3341 Binder.restoreCallingIdentity(ident);
3342 }
3343 }
3344
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003345 mH.post(() -> {
3346 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3347 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3348 }
3349 });
3350 }
3351
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003352 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 mH.post(() -> {
3354 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3355 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3356 }
3357 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
3359
3360 @Override
3361 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003362 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3363 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003364
3365 final File passedIconFile = new File(filePath);
3366 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3367 passedIconFile.getName());
3368 if (!legitIconFile.getPath().equals(filePath)
3369 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3370 throw new IllegalArgumentException("Bad file path: " + filePath
3371 + " passed for userId " + userId);
3372 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003373 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 }
3375
3376 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003377 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3379 final ActivityOptions activityOptions = safeOptions != null
3380 ? safeOptions.getOptions(mStackSupervisor)
3381 : null;
3382 if (activityOptions == null
3383 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3384 || activityOptions.getCustomInPlaceResId() == 0) {
3385 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3386 "with valid animation");
3387 }
lumark588a3e82018-07-20 18:53:54 +08003388 // Get top display of front most application.
3389 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3390 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003391 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3392 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3393 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003394 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003395 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003396 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 }
3398
3399 @Override
3400 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003401 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 synchronized (mGlobalLock) {
3403 final long ident = Binder.clearCallingIdentity();
3404 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003405 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 if (stack == null) {
3407 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3408 return;
3409 }
3410 if (!stack.isActivityTypeStandardOrUndefined()) {
3411 throw new IllegalArgumentException(
3412 "Removing non-standard stack is not allowed.");
3413 }
3414 mStackSupervisor.removeStack(stack);
3415 } finally {
3416 Binder.restoreCallingIdentity(ident);
3417 }
3418 }
3419 }
3420
3421 @Override
3422 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003423 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424
3425 synchronized (mGlobalLock) {
3426 final long ident = Binder.clearCallingIdentity();
3427 try {
3428 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3429 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003430 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 } finally {
3432 Binder.restoreCallingIdentity(ident);
3433 }
3434 }
3435 }
3436
3437 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003438 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439 synchronized (mGlobalLock) {
3440 long ident = Binder.clearCallingIdentity();
3441 try {
3442 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3443 if (r == null) {
3444 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003445 "toggleFreeformWindowingMode: No activity record matching token="
3446 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 }
3448
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003449 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003450 if (stack == null) {
3451 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3452 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003453 }
3454
Yunfan Chend967af82019-01-17 18:30:18 +09003455 if (!stack.inFreeformWindowingMode()
3456 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3457 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3458 + "toggle between fullscreen and freeform.");
3459 }
3460
3461 if (stack.inFreeformWindowingMode()) {
3462 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003463 } else if (stack.getParent().inFreeformWindowingMode()) {
3464 // If the window is on a freeform display, set it to undefined. It will be
3465 // resolved to freeform and it can adjust windowing mode when the display mode
3466 // changes in runtime.
3467 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003468 } else {
3469 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3470 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 } finally {
3472 Binder.restoreCallingIdentity(ident);
3473 }
3474 }
3475 }
3476
3477 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3478 @Override
3479 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003480 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003482 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 }
3484
3485 /** Unregister a task stack listener so that it stops receiving callbacks. */
3486 @Override
3487 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003488 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003490 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003491 }
3492
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003493 @Override
3494 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3495 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3496 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3497 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3498 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3499 }
3500
3501 @Override
3502 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3503 IBinder activityToken, int flags) {
3504 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3505 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3506 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3507 }
3508
3509 @Override
3510 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3511 Bundle args) {
3512 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3513 true /* focused */, true /* newSessionId */, userHandle, args,
3514 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3515 }
3516
3517 @Override
3518 public Bundle getAssistContextExtras(int requestType) {
3519 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3520 null, null, true /* focused */, true /* newSessionId */,
3521 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3522 if (pae == null) {
3523 return null;
3524 }
3525 synchronized (pae) {
3526 while (!pae.haveResult) {
3527 try {
3528 pae.wait();
3529 } catch (InterruptedException e) {
3530 }
3531 }
3532 }
3533 synchronized (mGlobalLock) {
3534 buildAssistBundleLocked(pae, pae.result);
3535 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003536 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003537 }
3538 return pae.extras;
3539 }
3540
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003541 /**
3542 * Binder IPC calls go through the public entry point.
3543 * This can be called with or without the global lock held.
3544 */
3545 private static int checkCallingPermission(String permission) {
3546 return checkPermission(
3547 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3548 }
3549
3550 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003551 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003552 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3553 mAmInternal.enforceCallingPermission(permission, func);
3554 }
3555 }
3556
3557 @VisibleForTesting
3558 int checkGetTasksPermission(String permission, int pid, int uid) {
3559 return checkPermission(permission, pid, uid);
3560 }
3561
3562 static int checkPermission(String permission, int pid, int uid) {
3563 if (permission == null) {
3564 return PackageManager.PERMISSION_DENIED;
3565 }
3566 return checkComponentPermission(permission, pid, uid, -1, true);
3567 }
3568
Wale Ogunwale214f3482018-10-04 11:00:47 -07003569 public static int checkComponentPermission(String permission, int pid, int uid,
3570 int owningUid, boolean exported) {
3571 return ActivityManagerService.checkComponentPermission(
3572 permission, pid, uid, owningUid, exported);
3573 }
3574
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3576 if (getRecentTasks().isCallerRecents(callingUid)) {
3577 // Always allow the recents component to get tasks
3578 return true;
3579 }
3580
3581 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3582 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3583 if (!allowed) {
3584 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3585 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3586 // Temporary compatibility: some existing apps on the system image may
3587 // still be requesting the old permission and not switched to the new
3588 // one; if so, we'll still allow them full access. This means we need
3589 // to see if they are holding the old permission and are a system app.
3590 try {
3591 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3592 allowed = true;
3593 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3594 + " is using old GET_TASKS but privileged; allowing");
3595 }
3596 } catch (RemoteException e) {
3597 }
3598 }
3599 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3600 + " does not hold REAL_GET_TASKS; limiting output");
3601 }
3602 return allowed;
3603 }
3604
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3606 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3607 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3608 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003609 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610 "enqueueAssistContext()");
3611
3612 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003613 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 if (activity == null) {
3615 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3616 return null;
3617 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003618 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003619 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3620 return null;
3621 }
3622 if (focused) {
3623 if (activityToken != null) {
3624 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3625 if (activity != caller) {
3626 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3627 + " is not current top " + activity);
3628 return null;
3629 }
3630 }
3631 } else {
3632 activity = ActivityRecord.forTokenLocked(activityToken);
3633 if (activity == null) {
3634 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3635 + " couldn't be found");
3636 return null;
3637 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003638 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3640 return null;
3641 }
3642 }
3643
3644 PendingAssistExtras pae;
3645 Bundle extras = new Bundle();
3646 if (args != null) {
3647 extras.putAll(args);
3648 }
3649 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003650 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003651
3652 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3653 userHandle);
3654 pae.isHome = activity.isActivityTypeHome();
3655
3656 // Increment the sessionId if necessary
3657 if (newSessionId) {
3658 mViSessionId++;
3659 }
3660 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003661 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3662 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003664 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003665 } catch (RemoteException e) {
3666 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3667 return null;
3668 }
3669 return pae;
3670 }
3671 }
3672
3673 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3674 if (result != null) {
3675 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3676 }
3677 if (pae.hint != null) {
3678 pae.extras.putBoolean(pae.hint, true);
3679 }
3680 }
3681
3682 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3683 IAssistDataReceiver receiver;
3684 synchronized (mGlobalLock) {
3685 mPendingAssistExtras.remove(pae);
3686 receiver = pae.receiver;
3687 }
3688 if (receiver != null) {
3689 // Caller wants result sent back to them.
3690 Bundle sendBundle = new Bundle();
3691 // At least return the receiver extras
3692 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3693 try {
3694 pae.receiver.onHandleAssistData(sendBundle);
3695 } catch (RemoteException e) {
3696 }
3697 }
3698 }
3699
3700 public class PendingAssistExtras extends Binder implements Runnable {
3701 public final ActivityRecord activity;
3702 public boolean isHome;
3703 public final Bundle extras;
3704 public final Intent intent;
3705 public final String hint;
3706 public final IAssistDataReceiver receiver;
3707 public final int userHandle;
3708 public boolean haveResult = false;
3709 public Bundle result = null;
3710 public AssistStructure structure = null;
3711 public AssistContent content = null;
3712 public Bundle receiverExtras;
3713
3714 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3715 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3716 int _userHandle) {
3717 activity = _activity;
3718 extras = _extras;
3719 intent = _intent;
3720 hint = _hint;
3721 receiver = _receiver;
3722 receiverExtras = _receiverExtras;
3723 userHandle = _userHandle;
3724 }
3725
3726 @Override
3727 public void run() {
3728 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3729 synchronized (this) {
3730 haveResult = true;
3731 notifyAll();
3732 }
3733 pendingAssistExtrasTimedOut(this);
3734 }
3735 }
3736
3737 @Override
3738 public boolean isAssistDataAllowedOnCurrentActivity() {
3739 int userId;
3740 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003741 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3743 return false;
3744 }
3745
3746 final ActivityRecord activity = focusedStack.getTopActivity();
3747 if (activity == null) {
3748 return false;
3749 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003750 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 }
3752 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3753 }
3754
3755 @Override
3756 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3757 long ident = Binder.clearCallingIdentity();
3758 try {
3759 synchronized (mGlobalLock) {
3760 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003761 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003762 if (top != caller) {
3763 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3764 + " is not current top " + top);
3765 return false;
3766 }
3767 if (!top.nowVisible) {
3768 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3769 + " is not visible");
3770 return false;
3771 }
3772 }
3773 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3774 token);
3775 } finally {
3776 Binder.restoreCallingIdentity(ident);
3777 }
3778 }
3779
3780 @Override
3781 public boolean isRootVoiceInteraction(IBinder token) {
3782 synchronized (mGlobalLock) {
3783 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3784 if (r == null) {
3785 return false;
3786 }
3787 return r.rootVoiceInteraction;
3788 }
3789 }
3790
Wale Ogunwalef6733932018-06-27 05:14:34 -07003791 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3792 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3793 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3794 if (activityToCallback == null) return;
3795 activityToCallback.setVoiceSessionLocked(voiceSession);
3796
3797 // Inform the activity
3798 try {
3799 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3800 voiceInteractor);
3801 long token = Binder.clearCallingIdentity();
3802 try {
3803 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3804 } finally {
3805 Binder.restoreCallingIdentity(token);
3806 }
3807 // TODO: VI Should we cache the activity so that it's easier to find later
3808 // rather than scan through all the stacks and activities?
3809 } catch (RemoteException re) {
3810 activityToCallback.clearVoiceSessionLocked();
3811 // TODO: VI Should this terminate the voice session?
3812 }
3813 }
3814
3815 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3816 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3817 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3818 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3819 boolean wasRunningVoice = mRunningVoice != null;
3820 mRunningVoice = session;
3821 if (!wasRunningVoice) {
3822 mVoiceWakeLock.acquire();
3823 updateSleepIfNeededLocked();
3824 }
3825 }
3826 }
3827
3828 void finishRunningVoiceLocked() {
3829 if (mRunningVoice != null) {
3830 mRunningVoice = null;
3831 mVoiceWakeLock.release();
3832 updateSleepIfNeededLocked();
3833 }
3834 }
3835
3836 @Override
3837 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3838 synchronized (mGlobalLock) {
3839 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3840 if (keepAwake) {
3841 mVoiceWakeLock.acquire();
3842 } else {
3843 mVoiceWakeLock.release();
3844 }
3845 }
3846 }
3847 }
3848
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003849 @Override
3850 public ComponentName getActivityClassForToken(IBinder token) {
3851 synchronized (mGlobalLock) {
3852 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3853 if (r == null) {
3854 return null;
3855 }
3856 return r.intent.getComponent();
3857 }
3858 }
3859
3860 @Override
3861 public String getPackageForToken(IBinder token) {
3862 synchronized (mGlobalLock) {
3863 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3864 if (r == null) {
3865 return null;
3866 }
3867 return r.packageName;
3868 }
3869 }
3870
3871 @Override
3872 public void showLockTaskEscapeMessage(IBinder token) {
3873 synchronized (mGlobalLock) {
3874 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3875 if (r == null) {
3876 return;
3877 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003878 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003879 }
3880 }
3881
3882 @Override
3883 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003884 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 final long token = Binder.clearCallingIdentity();
3886 try {
3887 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003888 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 }
3890 } finally {
3891 Binder.restoreCallingIdentity(token);
3892 }
3893 }
3894
3895 /**
3896 * Try to place task to provided position. The final position might be different depending on
3897 * current user and stacks state. The task will be moved to target stack if it's currently in
3898 * different stack.
3899 */
3900 @Override
3901 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003902 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003903 synchronized (mGlobalLock) {
3904 long ident = Binder.clearCallingIdentity();
3905 try {
3906 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3907 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003908 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 if (task == null) {
3910 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3911 + taskId);
3912 }
3913
Wale Ogunwaled32da472018-11-16 07:19:28 -08003914 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915
3916 if (stack == null) {
3917 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3918 + stackId);
3919 }
3920 if (!stack.isActivityTypeStandardOrUndefined()) {
3921 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3922 + " the position of task " + taskId + " in/to non-standard stack");
3923 }
3924
3925 // TODO: Have the callers of this API call a separate reparent method if that is
3926 // what they intended to do vs. having this method also do reparenting.
3927 if (task.getStack() == stack) {
3928 // Change position in current stack.
3929 stack.positionChildAt(task, position);
3930 } else {
3931 // Reparent to new stack.
3932 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3933 !DEFER_RESUME, "positionTaskInStack");
3934 }
3935 } finally {
3936 Binder.restoreCallingIdentity(ident);
3937 }
3938 }
3939 }
3940
3941 @Override
3942 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3943 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3944 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3945 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3946 synchronized (mGlobalLock) {
3947 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3948 if (record == null) {
3949 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3950 + "found for: " + token);
3951 }
3952 record.setSizeConfigurations(horizontalSizeConfiguration,
3953 verticalSizeConfigurations, smallestSizeConfigurations);
3954 }
3955 }
3956
3957 /**
3958 * Dismisses split-screen multi-window mode.
3959 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3960 */
3961 @Override
3962 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003963 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3965 final long ident = Binder.clearCallingIdentity();
3966 try {
3967 synchronized (mGlobalLock) {
3968 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003969 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003970 if (stack == null) {
3971 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3972 return;
3973 }
3974
3975 if (toTop) {
3976 // Caller wants the current split-screen primary stack to be the top stack after
3977 // it goes fullscreen, so move it to the front.
3978 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003979 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 // In this case the current split-screen primary stack shouldn't be the top
3981 // stack after it goes fullscreen, but it current has focus, so we move the
3982 // focus to the top-most split-screen secondary stack next to it.
3983 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3984 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3985 if (otherStack != null) {
3986 otherStack.moveToFront("dismissSplitScreenMode_other");
3987 }
3988 }
3989
Evan Rosky10475742018-09-05 19:02:48 -07003990 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 }
3992 } finally {
3993 Binder.restoreCallingIdentity(ident);
3994 }
3995 }
3996
3997 /**
3998 * Dismisses Pip
3999 * @param animate True if the dismissal should be animated.
4000 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4001 * default animation duration should be used.
4002 */
4003 @Override
4004 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004005 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 final long ident = Binder.clearCallingIdentity();
4007 try {
4008 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004009 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004010 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004011 if (stack == null) {
4012 Slog.w(TAG, "dismissPip: pinned stack not found.");
4013 return;
4014 }
4015 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4016 throw new IllegalArgumentException("Stack: " + stack
4017 + " doesn't support animated resize.");
4018 }
4019 if (animate) {
4020 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4021 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4022 } else {
4023 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4024 }
4025 }
4026 } finally {
4027 Binder.restoreCallingIdentity(ident);
4028 }
4029 }
4030
4031 @Override
4032 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 synchronized (mGlobalLock) {
4035 mSuppressResizeConfigChanges = suppress;
4036 }
4037 }
4038
4039 /**
4040 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4041 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4042 * activity and clearing the task at the same time.
4043 */
4044 @Override
4045 // TODO: API should just be about changing windowing modes...
4046 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004047 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004048 "moveTasksToFullscreenStack()");
4049 synchronized (mGlobalLock) {
4050 final long origId = Binder.clearCallingIdentity();
4051 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004052 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 if (stack != null){
4054 if (!stack.isActivityTypeStandardOrUndefined()) {
4055 throw new IllegalArgumentException(
4056 "You can't move tasks from non-standard stacks.");
4057 }
4058 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4059 }
4060 } finally {
4061 Binder.restoreCallingIdentity(origId);
4062 }
4063 }
4064 }
4065
4066 /**
4067 * Moves the top activity in the input stackId to the pinned stack.
4068 *
4069 * @param stackId Id of stack to move the top activity to pinned stack.
4070 * @param bounds Bounds to use for pinned stack.
4071 *
4072 * @return True if the top activity of the input stack was successfully moved to the pinned
4073 * stack.
4074 */
4075 @Override
4076 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004077 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 "moveTopActivityToPinnedStack()");
4079 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004080 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4082 + "Device doesn't support picture-in-picture mode");
4083 }
4084
4085 long ident = Binder.clearCallingIdentity();
4086 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004087 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 } finally {
4089 Binder.restoreCallingIdentity(ident);
4090 }
4091 }
4092 }
4093
4094 @Override
4095 public boolean isInMultiWindowMode(IBinder token) {
4096 final long origId = Binder.clearCallingIdentity();
4097 try {
4098 synchronized (mGlobalLock) {
4099 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4100 if (r == null) {
4101 return false;
4102 }
4103 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4104 return r.inMultiWindowMode();
4105 }
4106 } finally {
4107 Binder.restoreCallingIdentity(origId);
4108 }
4109 }
4110
4111 @Override
4112 public boolean isInPictureInPictureMode(IBinder token) {
4113 final long origId = Binder.clearCallingIdentity();
4114 try {
4115 synchronized (mGlobalLock) {
4116 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4117 }
4118 } finally {
4119 Binder.restoreCallingIdentity(origId);
4120 }
4121 }
4122
4123 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004124 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4125 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 return false;
4127 }
4128
4129 // If we are animating to fullscreen then we have already dispatched the PIP mode
4130 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004131 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4132 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 }
4134
4135 @Override
4136 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4137 final long origId = Binder.clearCallingIdentity();
4138 try {
4139 synchronized (mGlobalLock) {
4140 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4141 "enterPictureInPictureMode", token, params);
4142
4143 // If the activity is already in picture in picture mode, then just return early
4144 if (isInPictureInPictureMode(r)) {
4145 return true;
4146 }
4147
4148 // Activity supports picture-in-picture, now check that we can enter PiP at this
4149 // point, if it is
4150 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4151 false /* beforeStopping */)) {
4152 return false;
4153 }
4154
4155 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004156 synchronized (mGlobalLock) {
4157 // Only update the saved args from the args that are set
4158 r.pictureInPictureArgs.copyOnlySet(params);
4159 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4160 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4161 // Adjust the source bounds by the insets for the transition down
4162 final Rect sourceBounds = new Rect(
4163 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004164 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004165 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004166 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004167 stack.setPictureInPictureAspectRatio(aspectRatio);
4168 stack.setPictureInPictureActions(actions);
4169 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4170 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4171 logPictureInPictureArgs(params);
4172 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 };
4174
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004175 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 // If the keyguard is showing or occluded, then try and dismiss it before
4177 // entering picture-in-picture (this will prompt the user to authenticate if the
4178 // device is currently locked).
4179 dismissKeyguard(token, new KeyguardDismissCallback() {
4180 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004181 public void onDismissSucceeded() {
4182 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004183 }
4184 }, null /* message */);
4185 } else {
4186 // Enter picture in picture immediately otherwise
4187 enterPipRunnable.run();
4188 }
4189 return true;
4190 }
4191 } finally {
4192 Binder.restoreCallingIdentity(origId);
4193 }
4194 }
4195
4196 @Override
4197 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4198 final long origId = Binder.clearCallingIdentity();
4199 try {
4200 synchronized (mGlobalLock) {
4201 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4202 "setPictureInPictureParams", token, params);
4203
4204 // Only update the saved args from the args that are set
4205 r.pictureInPictureArgs.copyOnlySet(params);
4206 if (r.inPinnedWindowingMode()) {
4207 // If the activity is already in picture-in-picture, update the pinned stack now
4208 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4209 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004210 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004211 if (!stack.isAnimatingBoundsToFullscreen()) {
4212 stack.setPictureInPictureAspectRatio(
4213 r.pictureInPictureArgs.getAspectRatio());
4214 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4215 }
4216 }
4217 logPictureInPictureArgs(params);
4218 }
4219 } finally {
4220 Binder.restoreCallingIdentity(origId);
4221 }
4222 }
4223
4224 @Override
4225 public int getMaxNumPictureInPictureActions(IBinder token) {
4226 // Currently, this is a static constant, but later, we may change this to be dependent on
4227 // the context of the activity
4228 return 3;
4229 }
4230
4231 private void logPictureInPictureArgs(PictureInPictureParams params) {
4232 if (params.hasSetActions()) {
4233 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4234 params.getActions().size());
4235 }
4236 if (params.hasSetAspectRatio()) {
4237 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4238 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4239 MetricsLogger.action(lm);
4240 }
4241 }
4242
4243 /**
4244 * Checks the state of the system and the activity associated with the given {@param token} to
4245 * verify that picture-in-picture is supported for that activity.
4246 *
4247 * @return the activity record for the given {@param token} if all the checks pass.
4248 */
4249 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4250 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004251 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 throw new IllegalStateException(caller
4253 + ": Device doesn't support picture-in-picture mode.");
4254 }
4255
4256 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4257 if (r == null) {
4258 throw new IllegalStateException(caller
4259 + ": Can't find activity for token=" + token);
4260 }
4261
4262 if (!r.supportsPictureInPicture()) {
4263 throw new IllegalStateException(caller
4264 + ": Current activity does not support picture-in-picture.");
4265 }
4266
4267 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004268 && !mWindowManager.isValidPictureInPictureAspectRatio(
4269 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004270 final float minAspectRatio = mContext.getResources().getFloat(
4271 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4272 final float maxAspectRatio = mContext.getResources().getFloat(
4273 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4274 throw new IllegalArgumentException(String.format(caller
4275 + ": Aspect ratio is too extreme (must be between %f and %f).",
4276 minAspectRatio, maxAspectRatio));
4277 }
4278
4279 // Truncate the number of actions if necessary
4280 params.truncateActions(getMaxNumPictureInPictureActions(token));
4281
4282 return r;
4283 }
4284
4285 @Override
4286 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 synchronized (mGlobalLock) {
4289 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4290 if (r == null) {
4291 throw new IllegalArgumentException("Activity does not exist; token="
4292 + activityToken);
4293 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004294 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004295 }
4296 }
4297
4298 @Override
4299 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4300 Rect tempDockedTaskInsetBounds,
4301 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 long ident = Binder.clearCallingIdentity();
4304 try {
4305 synchronized (mGlobalLock) {
4306 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4307 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4308 PRESERVE_WINDOWS);
4309 }
4310 } finally {
4311 Binder.restoreCallingIdentity(ident);
4312 }
4313 }
4314
4315 @Override
4316 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004317 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 final long ident = Binder.clearCallingIdentity();
4319 try {
4320 synchronized (mGlobalLock) {
4321 mStackSupervisor.setSplitScreenResizing(resizing);
4322 }
4323 } finally {
4324 Binder.restoreCallingIdentity(ident);
4325 }
4326 }
4327
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004328 /**
4329 * Check that we have the features required for VR-related API calls, and throw an exception if
4330 * not.
4331 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004332 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004333 if (!mContext.getPackageManager().hasSystemFeature(
4334 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4335 throw new UnsupportedOperationException("VR mode not supported on this device!");
4336 }
4337 }
4338
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 @Override
4340 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004341 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342
4343 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4344
4345 ActivityRecord r;
4346 synchronized (mGlobalLock) {
4347 r = ActivityRecord.isInStackLocked(token);
4348 }
4349
4350 if (r == null) {
4351 throw new IllegalArgumentException();
4352 }
4353
4354 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004355 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 VrManagerInternal.NO_ERROR) {
4357 return err;
4358 }
4359
4360 // Clear the binder calling uid since this path may call moveToTask().
4361 final long callingId = Binder.clearCallingIdentity();
4362 try {
4363 synchronized (mGlobalLock) {
4364 r.requestedVrComponent = (enabled) ? packageName : null;
4365
4366 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004367 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004368 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 }
4370 return 0;
4371 }
4372 } finally {
4373 Binder.restoreCallingIdentity(callingId);
4374 }
4375 }
4376
4377 @Override
4378 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4379 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4380 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004381 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4383 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4384 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004385 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 || activity.voiceSession != null) {
4387 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4388 return;
4389 }
4390 if (activity.pendingVoiceInteractionStart) {
4391 Slog.w(TAG, "Pending start of voice interaction already.");
4392 return;
4393 }
4394 activity.pendingVoiceInteractionStart = true;
4395 }
4396 LocalServices.getService(VoiceInteractionManagerInternal.class)
4397 .startLocalVoiceInteraction(callingActivity, options);
4398 }
4399
4400 @Override
4401 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4402 LocalServices.getService(VoiceInteractionManagerInternal.class)
4403 .stopLocalVoiceInteraction(callingActivity);
4404 }
4405
4406 @Override
4407 public boolean supportsLocalVoiceInteraction() {
4408 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4409 .supportsLocalVoiceInteraction();
4410 }
4411
4412 /** Notifies all listeners when the pinned stack animation starts. */
4413 @Override
4414 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004415 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 }
4417
4418 /** Notifies all listeners when the pinned stack animation ends. */
4419 @Override
4420 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 }
4423
4424 @Override
4425 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 final long ident = Binder.clearCallingIdentity();
4428 try {
4429 synchronized (mGlobalLock) {
4430 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4431 }
4432 } finally {
4433 Binder.restoreCallingIdentity(ident);
4434 }
4435 }
4436
4437 @Override
4438 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440
4441 synchronized (mGlobalLock) {
4442 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004443 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 // Call might come when display is not yet added or has already been removed.
4445 if (DEBUG_CONFIGURATION) {
4446 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4447 + displayId);
4448 }
4449 return false;
4450 }
4451
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 }
4456
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004458 final Message msg = PooledLambda.obtainMessage(
4459 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4460 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 }
4462
4463 final long origId = Binder.clearCallingIdentity();
4464 try {
4465 if (values != null) {
4466 Settings.System.clearConfiguration(values);
4467 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4470 return mTmpUpdateConfigurationResult.changes != 0;
4471 } finally {
4472 Binder.restoreCallingIdentity(origId);
4473 }
4474 }
4475 }
4476
4477 @Override
4478 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480
4481 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004482 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004484 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 }
4486
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004487 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004488 final Message msg = PooledLambda.obtainMessage(
4489 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4490 DEFAULT_DISPLAY);
4491 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 }
4493
4494 final long origId = Binder.clearCallingIdentity();
4495 try {
4496 if (values != null) {
4497 Settings.System.clearConfiguration(values);
4498 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 UserHandle.USER_NULL, false /* deferResume */,
4501 mTmpUpdateConfigurationResult);
4502 return mTmpUpdateConfigurationResult.changes != 0;
4503 } finally {
4504 Binder.restoreCallingIdentity(origId);
4505 }
4506 }
4507 }
4508
4509 @Override
4510 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4511 CharSequence message) {
4512 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004513 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004514 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4515 }
4516 final long callingId = Binder.clearCallingIdentity();
4517 try {
4518 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004519 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 }
4521 } finally {
4522 Binder.restoreCallingIdentity(callingId);
4523 }
4524 }
4525
4526 @Override
4527 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004528 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004529 "cancelTaskWindowTransition()");
4530 final long ident = Binder.clearCallingIdentity();
4531 try {
4532 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004533 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004534 MATCH_TASK_IN_STACKS_ONLY);
4535 if (task == null) {
4536 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4537 return;
4538 }
4539 task.cancelWindowTransition();
4540 }
4541 } finally {
4542 Binder.restoreCallingIdentity(ident);
4543 }
4544 }
4545
4546 @Override
4547 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004548 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 final long ident = Binder.clearCallingIdentity();
4550 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004551 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 } finally {
4553 Binder.restoreCallingIdentity(ident);
4554 }
4555 }
4556
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004557 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4558 boolean restoreFromDisk) {
4559 final TaskRecord task;
4560 synchronized (mGlobalLock) {
4561 task = mRootActivityContainer.anyTaskForId(taskId,
4562 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4563 if (task == null) {
4564 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4565 return null;
4566 }
4567 }
4568 // Don't call this while holding the lock as this operation might hit the disk.
4569 return task.getSnapshot(reducedResolution, restoreFromDisk);
4570 }
4571
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572 @Override
4573 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4574 synchronized (mGlobalLock) {
4575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4576 if (r == null) {
4577 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4578 + token);
4579 return;
4580 }
4581 final long origId = Binder.clearCallingIdentity();
4582 try {
4583 r.setDisablePreviewScreenshots(disable);
4584 } finally {
4585 Binder.restoreCallingIdentity(origId);
4586 }
4587 }
4588 }
4589
4590 /** Return the user id of the last resumed activity. */
4591 @Override
4592 public @UserIdInt
4593 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004594 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4596 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004597 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004598 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004599 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004600 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 }
4602 }
4603
4604 @Override
4605 public void updateLockTaskFeatures(int userId, int flags) {
4606 final int callingUid = Binder.getCallingUid();
4607 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004608 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 "updateLockTaskFeatures()");
4610 }
4611 synchronized (mGlobalLock) {
4612 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4613 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004614 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 }
4616 }
4617
4618 @Override
4619 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4620 synchronized (mGlobalLock) {
4621 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4622 if (r == null) {
4623 return;
4624 }
4625 final long origId = Binder.clearCallingIdentity();
4626 try {
4627 r.setShowWhenLocked(showWhenLocked);
4628 } finally {
4629 Binder.restoreCallingIdentity(origId);
4630 }
4631 }
4632 }
4633
4634 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004635 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4636 synchronized (mGlobalLock) {
4637 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4638 if (r == null) {
4639 return;
4640 }
4641 final long origId = Binder.clearCallingIdentity();
4642 try {
4643 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4644 } finally {
4645 Binder.restoreCallingIdentity(origId);
4646 }
4647 }
4648 }
4649
4650 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004651 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4652 synchronized (mGlobalLock) {
4653 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4654 if (r == null) {
4655 return;
4656 }
4657 final long origId = Binder.clearCallingIdentity();
4658 try {
4659 r.setTurnScreenOn(turnScreenOn);
4660 } finally {
4661 Binder.restoreCallingIdentity(origId);
4662 }
4663 }
4664 }
4665
4666 @Override
4667 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004668 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 "registerRemoteAnimations");
4670 definition.setCallingPid(Binder.getCallingPid());
4671 synchronized (mGlobalLock) {
4672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4673 if (r == null) {
4674 return;
4675 }
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
4678 r.registerRemoteAnimations(definition);
4679 } finally {
4680 Binder.restoreCallingIdentity(origId);
4681 }
4682 }
4683 }
4684
4685 @Override
4686 public void registerRemoteAnimationForNextActivityStart(String packageName,
4687 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004688 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 "registerRemoteAnimationForNextActivityStart");
4690 adapter.setCallingPid(Binder.getCallingPid());
4691 synchronized (mGlobalLock) {
4692 final long origId = Binder.clearCallingIdentity();
4693 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004694 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004695 packageName, adapter);
4696 } finally {
4697 Binder.restoreCallingIdentity(origId);
4698 }
4699 }
4700 }
4701
Evan Rosky966759f2019-01-15 10:33:58 -08004702 @Override
4703 public void registerRemoteAnimationsForDisplay(int displayId,
4704 RemoteAnimationDefinition definition) {
4705 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4706 "registerRemoteAnimations");
4707 definition.setCallingPid(Binder.getCallingPid());
4708 synchronized (mGlobalLock) {
4709 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4710 if (display == null) {
4711 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4712 return;
4713 }
4714 final long origId = Binder.clearCallingIdentity();
4715 try {
4716 display.mDisplayContent.registerRemoteAnimations(definition);
4717 } finally {
4718 Binder.restoreCallingIdentity(origId);
4719 }
4720 }
4721 }
4722
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004723 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4724 @Override
4725 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4726 synchronized (mGlobalLock) {
4727 final long origId = Binder.clearCallingIdentity();
4728 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004729 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004730 } finally {
4731 Binder.restoreCallingIdentity(origId);
4732 }
4733 }
4734 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004735
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004736 @Override
4737 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004738 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004739 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004740 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004741 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004742 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 }
4744 }
4745
4746 @Override
4747 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004748 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 != PERMISSION_GRANTED) {
4750 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4751 + Binder.getCallingPid()
4752 + ", uid=" + Binder.getCallingUid()
4753 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4754 Slog.w(TAG, msg);
4755 throw new SecurityException(msg);
4756 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004758 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004759 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004760 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004761 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004762 }
4763 }
4764
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004765 @Override
4766 public void stopAppSwitches() {
4767 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4768 synchronized (mGlobalLock) {
4769 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004770 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004771 mDidAppSwitch = false;
4772 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4773 }
4774 }
4775
4776 @Override
4777 public void resumeAppSwitches() {
4778 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4779 synchronized (mGlobalLock) {
4780 // Note that we don't execute any pending app switches... we will
4781 // let those wait until either the timeout, or the next start
4782 // activity request.
4783 mAppSwitchesAllowedTime = 0;
4784 }
4785 }
4786
Ricky Wai906af482019-06-03 17:25:28 +01004787 long getLastStopAppSwitchesTime() {
4788 return mLastStopAppSwitchesTime;
4789 }
4790
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004791 void onStartActivitySetDidAppSwitch() {
4792 if (mDidAppSwitch) {
4793 // This is the second allowed switch since we stopped switches, so now just generally
4794 // allow switches. Use case:
4795 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4796 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4797 // anyone to switch again).
4798 mAppSwitchesAllowedTime = 0;
4799 } else {
4800 mDidAppSwitch = true;
4801 }
4802 }
4803
4804 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004805 boolean shouldDisableNonVrUiLocked() {
4806 return mVrController.shouldDisableNonVrUiLocked();
4807 }
4808
Wale Ogunwale53783742018-09-16 10:21:51 -07004809 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004810 // VR apps are expected to run in a main display. If an app is turning on VR for
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004811 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004812 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004813 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4814 + " to main display for VR");
4815 mRootActivityContainer.moveStackToDisplay(
4816 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004817 }
4818 mH.post(() -> {
4819 if (!mVrController.onVrModeChanged(r)) {
4820 return;
4821 }
4822 synchronized (mGlobalLock) {
4823 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4824 mWindowManager.disableNonVrUi(disableNonVrUi);
4825 if (disableNonVrUi) {
4826 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4827 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004828 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004829 }
4830 }
4831 });
4832 }
4833
Wale Ogunwale53783742018-09-16 10:21:51 -07004834 @Override
4835 public int getPackageScreenCompatMode(String packageName) {
4836 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4837 synchronized (mGlobalLock) {
4838 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4839 }
4840 }
4841
4842 @Override
4843 public void setPackageScreenCompatMode(String packageName, int mode) {
4844 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4845 "setPackageScreenCompatMode");
4846 synchronized (mGlobalLock) {
4847 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4848 }
4849 }
4850
4851 @Override
4852 public boolean getPackageAskScreenCompat(String packageName) {
4853 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4854 synchronized (mGlobalLock) {
4855 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4856 }
4857 }
4858
4859 @Override
4860 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4861 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4862 "setPackageAskScreenCompat");
4863 synchronized (mGlobalLock) {
4864 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4865 }
4866 }
4867
Wale Ogunwale64258362018-10-16 15:13:37 -07004868 public static String relaunchReasonToString(int relaunchReason) {
4869 switch (relaunchReason) {
4870 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4871 return "window_resize";
4872 case RELAUNCH_REASON_FREE_RESIZE:
4873 return "free_resize";
4874 default:
4875 return null;
4876 }
4877 }
4878
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004879 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004880 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004881 }
4882
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004883 /** Pokes the task persister. */
4884 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4885 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4886 }
4887
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004888 boolean isKeyguardLocked() {
4889 return mKeyguardController.isKeyguardLocked();
4890 }
4891
Garfield Tan01548632018-11-27 10:15:48 -08004892 /**
4893 * Clears launch params for the given package.
4894 * @param packageNames the names of the packages of which the launch params are to be cleared
4895 */
4896 @Override
4897 public void clearLaunchParamsForPackages(List<String> packageNames) {
4898 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4899 "clearLaunchParamsForPackages");
4900 synchronized (mGlobalLock) {
4901 for (int i = 0; i < packageNames.size(); ++i) {
4902 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4903 }
4904 }
4905 }
4906
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004907 /**
4908 * Makes the display with the given id a single task instance display. I.e the display can only
4909 * contain one task.
4910 */
4911 @Override
4912 public void setDisplayToSingleTaskInstance(int displayId) {
4913 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4914 "setDisplayToSingleTaskInstance");
4915 final long origId = Binder.clearCallingIdentity();
4916 try {
4917 final ActivityDisplay display =
4918 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4919 if (display != null) {
4920 display.setDisplayToSingleTaskInstance();
4921 }
4922 } finally {
4923 Binder.restoreCallingIdentity(origId);
4924 }
4925 }
4926
Wale Ogunwale31913b52018-10-13 08:29:31 -07004927 void dumpLastANRLocked(PrintWriter pw) {
4928 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4929 if (mLastANRState == null) {
4930 pw.println(" <no ANR has occurred since boot>");
4931 } else {
4932 pw.println(mLastANRState);
4933 }
4934 }
4935
4936 void dumpLastANRTracesLocked(PrintWriter pw) {
4937 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4938
4939 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4940 if (ArrayUtils.isEmpty(files)) {
4941 pw.println(" <no ANR has occurred since boot>");
4942 return;
4943 }
4944 // Find the latest file.
4945 File latest = null;
4946 for (File f : files) {
4947 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4948 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004949 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004950 }
4951 pw.print("File: ");
4952 pw.print(latest.getName());
4953 pw.println();
4954 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4955 String line;
4956 while ((line = in.readLine()) != null) {
4957 pw.println(line);
4958 }
4959 } catch (IOException e) {
4960 pw.print("Unable to read: ");
4961 pw.print(e);
4962 pw.println();
4963 }
4964 }
4965
4966 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4967 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4968 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4969 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4970 }
4971
4972 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4973 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4974 pw.println(header);
4975
Wale Ogunwaled32da472018-11-16 07:19:28 -08004976 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004977 dumpPackage);
4978 boolean needSep = printedAnything;
4979
4980 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004981 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 " ResumedActivity: ");
4983 if (printed) {
4984 printedAnything = true;
4985 needSep = false;
4986 }
4987
4988 if (dumpPackage == null) {
4989 if (needSep) {
4990 pw.println();
4991 }
4992 printedAnything = true;
4993 mStackSupervisor.dump(pw, " ");
4994 }
4995
4996 if (!printedAnything) {
4997 pw.println(" (nothing)");
4998 }
4999 }
5000
5001 void dumpActivityContainersLocked(PrintWriter pw) {
5002 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08005003 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 pw.println(" ");
5005 }
5006
5007 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5008 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5009 getActivityStartController().dump(pw, "", dumpPackage);
5010 }
5011
5012 /**
5013 * There are three things that cmd can be:
5014 * - a flattened component name that matches an existing activity
5015 * - the cmd arg isn't the flattened component name of an existing activity:
5016 * dump all activity whose component contains the cmd as a substring
5017 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005018 * <p>
5019 * The caller should not hold lock when calling this method because it will wait for the
5020 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005021 *
5022 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5023 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5024 */
5025 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5026 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5027 ArrayList<ActivityRecord> activities;
5028
5029 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005030 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005031 dumpFocusedStackOnly);
5032 }
5033
5034 if (activities.size() <= 0) {
5035 return false;
5036 }
5037
5038 String[] newArgs = new String[args.length - opti];
5039 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5040
5041 TaskRecord lastTask = null;
5042 boolean needSep = false;
5043 for (int i = activities.size() - 1; i >= 0; i--) {
5044 ActivityRecord r = activities.get(i);
5045 if (needSep) {
5046 pw.println();
5047 }
5048 needSep = true;
5049 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005050 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005051 if (lastTask != task) {
5052 lastTask = task;
5053 pw.print("TASK "); pw.print(lastTask.affinity);
5054 pw.print(" id="); pw.print(lastTask.taskId);
5055 pw.print(" userId="); pw.println(lastTask.userId);
5056 if (dumpAll) {
5057 lastTask.dump(pw, " ");
5058 }
5059 }
5060 }
5061 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5062 }
5063 return true;
5064 }
5065
5066 /**
5067 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5068 * there is a thread associated with the activity.
5069 */
5070 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5071 final ActivityRecord r, String[] args, boolean dumpAll) {
5072 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005073 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005074 synchronized (mGlobalLock) {
5075 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5076 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5077 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005078 if (r.hasProcess()) {
5079 pw.println(r.app.getPid());
5080 appThread = r.app.getThread();
5081 } else {
5082 pw.println("(not running)");
5083 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005084 if (dumpAll) {
5085 r.dump(pw, innerPrefix);
5086 }
5087 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005088 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005089 // flush anything that is already in the PrintWriter since the thread is going
5090 // to write to the file descriptor directly
5091 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005092 try (TransferPipe tp = new TransferPipe()) {
5093 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5094 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005095 } catch (IOException e) {
5096 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5097 } catch (RemoteException e) {
5098 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5099 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005101 }
5102
sanryhuang498e77e2018-12-06 14:57:01 +08005103 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5104 boolean testPssMode) {
5105 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5106 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5107 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005108 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005109 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5110 st.toString());
5111 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005112 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5113 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5114 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005115 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5116 testPssMode);
5117 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005118 }
5119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005120 int getCurrentUserId() {
5121 return mAmInternal.getCurrentUserId();
5122 }
5123
5124 private void enforceNotIsolatedCaller(String caller) {
5125 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5126 throw new SecurityException("Isolated process not allowed to call " + caller);
5127 }
5128 }
5129
Wale Ogunwalef6733932018-06-27 05:14:34 -07005130 public Configuration getConfiguration() {
5131 Configuration ci;
5132 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005133 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005134 ci.userSetLocale = false;
5135 }
5136 return ci;
5137 }
5138
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 /**
5140 * Current global configuration information. Contains general settings for the entire system,
5141 * also corresponds to the merged configuration of the default display.
5142 */
5143 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005144 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005145 }
5146
5147 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5148 boolean initLocale) {
5149 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5150 }
5151
5152 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5153 boolean initLocale, boolean deferResume) {
5154 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5155 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5156 UserHandle.USER_NULL, deferResume);
5157 }
5158
Wale Ogunwale59507092018-10-29 09:00:30 -07005159 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005160 final long origId = Binder.clearCallingIdentity();
5161 try {
5162 synchronized (mGlobalLock) {
5163 updateConfigurationLocked(values, null, false, true, userId,
5164 false /* deferResume */);
5165 }
5166 } finally {
5167 Binder.restoreCallingIdentity(origId);
5168 }
5169 }
5170
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5172 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5173 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5174 deferResume, null /* result */);
5175 }
5176
5177 /**
5178 * Do either or both things: (1) change the current configuration, and (2)
5179 * make sure the given activity is running with the (now) current
5180 * configuration. Returns true if the activity has been left running, or
5181 * false if <var>starting</var> is being destroyed to match the new
5182 * configuration.
5183 *
5184 * @param userId is only used when persistent parameter is set to true to persist configuration
5185 * for that particular user
5186 */
5187 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5188 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5189 ActivityTaskManagerService.UpdateConfigurationResult result) {
5190 int changes = 0;
5191 boolean kept = true;
5192
5193 if (mWindowManager != null) {
5194 mWindowManager.deferSurfaceLayout();
5195 }
5196 try {
5197 if (values != null) {
5198 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5199 deferResume);
5200 }
5201
5202 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5203 } finally {
5204 if (mWindowManager != null) {
5205 mWindowManager.continueSurfaceLayout();
5206 }
5207 }
5208
5209 if (result != null) {
5210 result.changes = changes;
5211 result.activityRelaunched = !kept;
5212 }
5213 return kept;
5214 }
5215
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216 /** Update default (global) configuration and notify listeners about changes. */
5217 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5218 boolean persistent, int userId, boolean deferResume) {
5219 mTempConfig.setTo(getGlobalConfiguration());
5220 final int changes = mTempConfig.updateFrom(values);
5221 if (changes == 0) {
5222 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5223 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5224 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5225 // (even if there are no actual changes) to unfreeze the window.
5226 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5227 return 0;
5228 }
5229
5230 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5231 "Updating global configuration to: " + values);
5232
5233 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5234 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5235 values.colorMode,
5236 values.densityDpi,
5237 values.fontScale,
5238 values.hardKeyboardHidden,
5239 values.keyboard,
5240 values.keyboardHidden,
5241 values.mcc,
5242 values.mnc,
5243 values.navigation,
5244 values.navigationHidden,
5245 values.orientation,
5246 values.screenHeightDp,
5247 values.screenLayout,
5248 values.screenWidthDp,
5249 values.smallestScreenWidthDp,
5250 values.touchscreen,
5251 values.uiMode);
5252
5253
5254 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5255 final LocaleList locales = values.getLocales();
5256 int bestLocaleIndex = 0;
5257 if (locales.size() > 1) {
5258 if (mSupportedSystemLocales == null) {
5259 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5260 }
5261 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5262 }
5263 SystemProperties.set("persist.sys.locale",
5264 locales.get(bestLocaleIndex).toLanguageTag());
5265 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005266
5267 final Message m = PooledLambda.obtainMessage(
5268 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5269 locales.get(bestLocaleIndex));
5270 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271 }
5272
Yunfan Chen75157d72018-07-27 14:47:21 +09005273 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274
5275 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005276 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005277
5278 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5279 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005280 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005281
5282 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005283 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284
5285 AttributeCache ac = AttributeCache.instance();
5286 if (ac != null) {
5287 ac.updateConfiguration(mTempConfig);
5288 }
5289
5290 // Make sure all resources in our process are updated right now, so that anyone who is going
5291 // to retrieve resource values after we return will be sure to get the new ones. This is
5292 // especially important during boot, where the first config change needs to guarantee all
5293 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005294 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295
5296 // We need another copy of global config because we're scheduling some calls instead of
5297 // running them in place. We need to be sure that object we send will be handled unchanged.
5298 final Configuration configCopy = new Configuration(mTempConfig);
5299 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005300 final Message msg = PooledLambda.obtainMessage(
5301 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5302 this, userId, configCopy);
5303 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005304 }
5305
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005306 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5307 for (int i = pidMap.size() - 1; i >= 0; i--) {
5308 final int pid = pidMap.keyAt(i);
5309 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005310 if (DEBUG_CONFIGURATION) {
5311 Slog.v(TAG_CONFIGURATION, "Update process config of "
5312 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005313 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005314 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005315 }
5316
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005317 final Message msg = PooledLambda.obtainMessage(
5318 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5319 mAmInternal, changes, initLocale);
5320 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005321
5322 // Override configuration of the default display duplicates global config, so we need to
5323 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005324 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005325 DEFAULT_DISPLAY);
5326
5327 return changes;
5328 }
5329
5330 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5331 boolean deferResume, int displayId) {
5332 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5333 displayId, null /* result */);
5334 }
5335
5336 /**
5337 * Updates override configuration specific for the selected display. If no config is provided,
5338 * new one will be computed in WM based on current display info.
5339 */
5340 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5341 ActivityRecord starting, boolean deferResume, int displayId,
5342 ActivityTaskManagerService.UpdateConfigurationResult result) {
5343 int changes = 0;
5344 boolean kept = true;
5345
5346 if (mWindowManager != null) {
5347 mWindowManager.deferSurfaceLayout();
5348 }
5349 try {
5350 if (values != null) {
5351 if (displayId == DEFAULT_DISPLAY) {
5352 // Override configuration of the default display duplicates global config, so
5353 // we're calling global config update instead for default display. It will also
5354 // apply the correct override config.
5355 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5356 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5357 } else {
5358 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5359 }
5360 }
5361
5362 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5363 } finally {
5364 if (mWindowManager != null) {
5365 mWindowManager.continueSurfaceLayout();
5366 }
5367 }
5368
5369 if (result != null) {
5370 result.changes = changes;
5371 result.activityRelaunched = !kept;
5372 }
5373 return kept;
5374 }
5375
5376 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5377 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005378 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005379 final int changes = mTempConfig.updateFrom(values);
5380 if (changes != 0) {
5381 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5382 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005383 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005384
5385 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5386 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005387 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005388
Wale Ogunwale5c918702018-10-18 11:06:33 -07005389 // Post message to start process to avoid possible deadlock of calling into AMS with
5390 // the ATMS lock held.
5391 final Message msg = PooledLambda.obtainMessage(
5392 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005393 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005394 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005395 }
5396 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005397 return changes;
5398 }
5399
Wale Ogunwalef6733932018-06-27 05:14:34 -07005400 private void updateEventDispatchingLocked(boolean booted) {
5401 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5402 }
5403
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005404 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5405 final ContentResolver resolver = mContext.getContentResolver();
5406 Settings.System.putConfigurationForUser(resolver, config, userId);
5407 }
5408
5409 private void sendLocaleToMountDaemonMsg(Locale l) {
5410 try {
5411 IBinder service = ServiceManager.getService("mount");
5412 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5413 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5414 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5415 } catch (RemoteException e) {
5416 Log.e(TAG, "Error storing locale for decryption UI", e);
5417 }
5418 }
5419
Alison Cichowlas3e340502018-08-07 17:15:01 -04005420 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5421 mStartActivitySources.remove(permissionToken);
5422 mExpiredStartAsCallerTokens.add(permissionToken);
5423 }
5424
5425 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5426 mExpiredStartAsCallerTokens.remove(permissionToken);
5427 }
5428
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005429 boolean isActivityStartsLoggingEnabled() {
5430 return mAmInternal.isActivityStartsLoggingEnabled();
5431 }
5432
Michal Karpinski8596ded2018-11-14 14:43:48 +00005433 boolean isBackgroundActivityStartsEnabled() {
5434 return mAmInternal.isBackgroundActivityStartsEnabled();
5435 }
5436
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 void enableScreenAfterBoot(boolean booted) {
5438 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5439 SystemClock.uptimeMillis());
5440 mWindowManager.enableScreenAfterBoot();
5441
5442 synchronized (mGlobalLock) {
5443 updateEventDispatchingLocked(booted);
5444 }
5445 }
5446
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005447 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5448 if (r == null || !r.hasProcess()) {
5449 return KEY_DISPATCHING_TIMEOUT_MS;
5450 }
5451 return getInputDispatchingTimeoutLocked(r.app);
5452 }
5453
5454 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005455 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005456 }
5457
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 /**
5459 * Decide based on the configuration whether we should show the ANR,
5460 * crash, etc dialogs. The idea is that if there is no affordance to
5461 * press the on-screen buttons, or the user experience would be more
5462 * greatly impacted than the crash itself, we shouldn't show the dialog.
5463 *
5464 * A thought: SystemUI might also want to get told about this, the Power
5465 * dialog / global actions also might want different behaviors.
5466 */
5467 private void updateShouldShowDialogsLocked(Configuration config) {
5468 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5469 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5470 && config.navigation == Configuration.NAVIGATION_NONAV);
5471 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5472 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5473 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5474 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5475 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5476 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5477 HIDE_ERROR_DIALOGS, 0) != 0;
5478 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5479 }
5480
5481 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5482 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5483 FONT_SCALE, 1.0f, userId);
5484
5485 synchronized (this) {
5486 if (getGlobalConfiguration().fontScale == scaleFactor) {
5487 return;
5488 }
5489
5490 final Configuration configuration
5491 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5492 configuration.fontScale = scaleFactor;
5493 updatePersistentConfiguration(configuration, userId);
5494 }
5495 }
5496
5497 // Actually is sleeping or shutting down or whatever else in the future
5498 // is an inactive state.
5499 boolean isSleepingOrShuttingDownLocked() {
5500 return isSleepingLocked() || mShuttingDown;
5501 }
5502
5503 boolean isSleepingLocked() {
5504 return mSleeping;
5505 }
5506
Riddle Hsu16567132018-08-16 21:37:47 +08005507 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005509 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005510 if (task.isActivityTypeStandard()) {
5511 if (mCurAppTimeTracker != r.appTimeTracker) {
5512 // We are switching app tracking. Complete the current one.
5513 if (mCurAppTimeTracker != null) {
5514 mCurAppTimeTracker.stop();
5515 mH.obtainMessage(
5516 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005517 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005518 mCurAppTimeTracker = null;
5519 }
5520 if (r.appTimeTracker != null) {
5521 mCurAppTimeTracker = r.appTimeTracker;
5522 startTimeTrackingFocusedActivityLocked();
5523 }
5524 } else {
5525 startTimeTrackingFocusedActivityLocked();
5526 }
5527 } else {
5528 r.appTimeTracker = null;
5529 }
5530 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5531 // TODO: Probably not, because we don't want to resume voice on switching
5532 // back to this activity
5533 if (task.voiceInteractor != null) {
5534 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5535 } else {
5536 finishRunningVoiceLocked();
5537
5538 if (mLastResumedActivity != null) {
5539 final IVoiceInteractionSession session;
5540
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 if (lastResumedActivityTask != null
5543 && lastResumedActivityTask.voiceSession != null) {
5544 session = lastResumedActivityTask.voiceSession;
5545 } else {
5546 session = mLastResumedActivity.voiceSession;
5547 }
5548
5549 if (session != null) {
5550 // We had been in a voice interaction session, but now focused has
5551 // move to something different. Just finish the session, we can't
5552 // return to it and retain the proper state and synchronization with
5553 // the voice interaction service.
5554 finishVoiceTask(session);
5555 }
5556 }
5557 }
5558
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005559 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5560 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005561 }
5562 updateResumedAppTrace(r);
5563 mLastResumedActivity = r;
5564
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005565 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005566
5567 applyUpdateLockStateLocked(r);
5568 applyUpdateVrModeLocked(r);
5569
5570 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005571 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 r == null ? "NULL" : r.shortComponentName,
5573 reason);
5574 }
5575
5576 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5577 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005578 final ActivityTaskManagerInternal.SleepToken token =
5579 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005580 updateSleepIfNeededLocked();
5581 return token;
5582 }
5583 }
5584
5585 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005586 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005587 final boolean wasSleeping = mSleeping;
5588 boolean updateOomAdj = false;
5589
5590 if (!shouldSleep) {
5591 // If wasSleeping is true, we need to wake up activity manager state from when
5592 // we started sleeping. In either case, we need to apply the sleep tokens, which
5593 // will wake up stacks or put them to sleep as appropriate.
5594 if (wasSleeping) {
5595 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005596 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5597 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005598 startTimeTrackingFocusedActivityLocked();
5599 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005600 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5602 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005603 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005604 if (wasSleeping) {
5605 updateOomAdj = true;
5606 }
5607 } else if (!mSleeping && shouldSleep) {
5608 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005609 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5610 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005611 if (mCurAppTimeTracker != null) {
5612 mCurAppTimeTracker.stop();
5613 }
5614 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005615 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005616 mStackSupervisor.goingToSleepLocked();
5617 updateResumedAppTrace(null /* resumed */);
5618 updateOomAdj = true;
5619 }
5620 if (updateOomAdj) {
5621 mH.post(mAmInternal::updateOomAdj);
5622 }
5623 }
5624
5625 void updateOomAdj() {
5626 mH.post(mAmInternal::updateOomAdj);
5627 }
5628
Wale Ogunwale53783742018-09-16 10:21:51 -07005629 void updateCpuStats() {
5630 mH.post(mAmInternal::updateCpuStats);
5631 }
5632
Hui Yu03d12402018-12-06 18:00:37 -08005633 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5634 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005635 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5636 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005637 mH.sendMessage(m);
5638 }
5639
Hui Yu03d12402018-12-06 18:00:37 -08005640 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005641 ComponentName taskRoot = null;
5642 final TaskRecord task = activity.getTaskRecord();
5643 if (task != null) {
5644 final ActivityRecord rootActivity = task.getRootActivity();
5645 if (rootActivity != null) {
5646 taskRoot = rootActivity.mActivityComponent;
5647 }
5648 }
5649
Hui Yu03d12402018-12-06 18:00:37 -08005650 final Message m = PooledLambda.obtainMessage(
5651 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005652 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005653 mH.sendMessage(m);
5654 }
5655
Wale Ogunwale53783742018-09-16 10:21:51 -07005656 void setBooting(boolean booting) {
5657 mAmInternal.setBooting(booting);
5658 }
5659
5660 boolean isBooting() {
5661 return mAmInternal.isBooting();
5662 }
5663
5664 void setBooted(boolean booted) {
5665 mAmInternal.setBooted(booted);
5666 }
5667
5668 boolean isBooted() {
5669 return mAmInternal.isBooted();
5670 }
5671
5672 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5673 mH.post(() -> {
5674 if (finishBooting) {
5675 mAmInternal.finishBooting();
5676 }
5677 if (enableScreen) {
5678 mInternal.enableScreenAfterBoot(isBooted());
5679 }
5680 });
5681 }
5682
5683 void setHeavyWeightProcess(ActivityRecord root) {
5684 mHeavyWeightProcess = root.app;
5685 final Message m = PooledLambda.obtainMessage(
5686 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005687 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005688 mH.sendMessage(m);
5689 }
5690
5691 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5692 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5693 return;
5694 }
5695
5696 mHeavyWeightProcess = null;
5697 final Message m = PooledLambda.obtainMessage(
5698 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5699 proc.mUserId);
5700 mH.sendMessage(m);
5701 }
5702
5703 private void cancelHeavyWeightProcessNotification(int userId) {
5704 final INotificationManager inm = NotificationManager.getService();
5705 if (inm == null) {
5706 return;
5707 }
5708 try {
5709 inm.cancelNotificationWithTag("android", null,
5710 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5711 } catch (RuntimeException e) {
5712 Slog.w(TAG, "Error canceling notification for service", e);
5713 } catch (RemoteException e) {
5714 }
5715
5716 }
5717
5718 private void postHeavyWeightProcessNotification(
5719 WindowProcessController proc, Intent intent, int userId) {
5720 if (proc == null) {
5721 return;
5722 }
5723
5724 final INotificationManager inm = NotificationManager.getService();
5725 if (inm == null) {
5726 return;
5727 }
5728
5729 try {
5730 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5731 String text = mContext.getString(R.string.heavy_weight_notification,
5732 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5733 Notification notification =
5734 new Notification.Builder(context,
5735 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5736 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5737 .setWhen(0)
5738 .setOngoing(true)
5739 .setTicker(text)
5740 .setColor(mContext.getColor(
5741 com.android.internal.R.color.system_notification_accent_color))
5742 .setContentTitle(text)
5743 .setContentText(
5744 mContext.getText(R.string.heavy_weight_notification_detail))
5745 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5746 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5747 new UserHandle(userId)))
5748 .build();
5749 try {
5750 inm.enqueueNotificationWithTag("android", "android", null,
5751 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5752 } catch (RuntimeException e) {
5753 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5754 } catch (RemoteException e) {
5755 }
5756 } catch (PackageManager.NameNotFoundException e) {
5757 Slog.w(TAG, "Unable to create context for heavy notification", e);
5758 }
5759
5760 }
5761
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005762 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5763 IBinder token, String resultWho, int requestCode, Intent[] intents,
5764 String[] resolvedTypes, int flags, Bundle bOptions) {
5765
5766 ActivityRecord activity = null;
5767 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5768 activity = ActivityRecord.isInStackLocked(token);
5769 if (activity == null) {
5770 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5771 return null;
5772 }
5773 if (activity.finishing) {
5774 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5775 return null;
5776 }
5777 }
5778
5779 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5780 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5781 bOptions);
5782 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5783 if (noCreate) {
5784 return rec;
5785 }
5786 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5787 if (activity.pendingResults == null) {
5788 activity.pendingResults = new HashSet<>();
5789 }
5790 activity.pendingResults.add(rec.ref);
5791 }
5792 return rec;
5793 }
5794
Andrii Kulian52d255c2018-07-13 11:32:19 -07005795 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005796 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005797 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005798 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5799 mCurAppTimeTracker.start(resumedActivity.packageName);
5800 }
5801 }
5802
5803 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5804 if (mTracedResumedActivity != null) {
5805 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5806 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5807 }
5808 if (resumed != null) {
5809 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5810 constructResumedTraceName(resumed.packageName), 0);
5811 }
5812 mTracedResumedActivity = resumed;
5813 }
5814
5815 private String constructResumedTraceName(String packageName) {
5816 return "focused app: " + packageName;
5817 }
5818
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005819 /** Applies latest configuration and/or visibility updates if needed. */
5820 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5821 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005822 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005823 // mainStack is null during startup.
5824 if (mainStack != null) {
5825 if (changes != 0 && starting == null) {
5826 // If the configuration changed, and the caller is not already
5827 // in the process of starting an activity, then find the top
5828 // activity to check if its configuration needs to change.
5829 starting = mainStack.topRunningActivityLocked();
5830 }
5831
5832 if (starting != null) {
5833 kept = starting.ensureActivityConfiguration(changes,
5834 false /* preserveWindow */);
5835 // And we need to make sure at this point that all other activities
5836 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005837 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005838 !PRESERVE_WINDOWS);
5839 }
5840 }
5841
5842 return kept;
5843 }
5844
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005845 void scheduleAppGcsLocked() {
5846 mH.post(() -> mAmInternal.scheduleAppGcs());
5847 }
5848
Wale Ogunwale53783742018-09-16 10:21:51 -07005849 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5850 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5851 }
5852
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005853 /**
5854 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5855 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5856 * on demand.
5857 */
5858 IPackageManager getPackageManager() {
5859 return AppGlobals.getPackageManager();
5860 }
5861
5862 PackageManagerInternal getPackageManagerInternalLocked() {
5863 if (mPmInternal == null) {
5864 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5865 }
5866 return mPmInternal;
5867 }
5868
Hai Zhangf4da9be2019-05-01 13:46:06 +08005869 PermissionPolicyInternal getPermissionPolicyInternal() {
5870 if (mPermissionPolicyInternal == null) {
5871 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5872 }
5873 return mPermissionPolicyInternal;
5874 }
5875
Wale Ogunwale008163e2018-07-23 23:11:08 -07005876 AppWarnings getAppWarningsLocked() {
5877 return mAppWarnings;
5878 }
5879
Wale Ogunwale214f3482018-10-04 11:00:47 -07005880 Intent getHomeIntent() {
5881 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5882 intent.setComponent(mTopComponent);
5883 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5884 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5885 intent.addCategory(Intent.CATEGORY_HOME);
5886 }
5887 return intent;
5888 }
5889
Chilun2ef71f72018-11-16 17:57:15 +08005890 /**
5891 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5892 * activities.
5893 *
5894 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5895 * component defined in config_secondaryHomeComponent.
5896 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5897 */
5898 Intent getSecondaryHomeIntent(String preferredPackage) {
5899 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005900 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5901 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5902 if (preferredPackage == null || useSystemProvidedLauncher) {
5903 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005904 final String secondaryHomeComponent = mContext.getResources().getString(
5905 com.android.internal.R.string.config_secondaryHomeComponent);
5906 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5907 } else {
5908 intent.setPackage(preferredPackage);
5909 }
5910 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5911 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5912 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5913 }
5914 return intent;
5915 }
5916
Wale Ogunwale214f3482018-10-04 11:00:47 -07005917 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5918 if (info == null) return null;
5919 ApplicationInfo newInfo = new ApplicationInfo(info);
5920 newInfo.initForUser(userId);
5921 return newInfo;
5922 }
5923
Wale Ogunwale9c103022018-10-18 07:44:54 -07005924 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005925 if (uid == SYSTEM_UID) {
5926 // The system gets to run in any process. If there are multiple processes with the same
5927 // uid, just pick the first (this should never happen).
5928 final SparseArray<WindowProcessController> procs =
5929 mProcessNames.getMap().get(processName);
5930 if (procs == null) return null;
5931 final int procCount = procs.size();
5932 for (int i = 0; i < procCount; i++) {
5933 final int procUid = procs.keyAt(i);
5934 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5935 // Don't use an app process or different user process for system component.
5936 continue;
5937 }
5938 return procs.valueAt(i);
5939 }
5940 }
5941
5942 return mProcessNames.get(processName, uid);
5943 }
5944
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005945 WindowProcessController getProcessController(IApplicationThread thread) {
5946 if (thread == null) {
5947 return null;
5948 }
5949
5950 final IBinder threadBinder = thread.asBinder();
5951 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5952 for (int i = pmap.size()-1; i >= 0; i--) {
5953 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5954 for (int j = procs.size() - 1; j >= 0; j--) {
5955 final WindowProcessController proc = procs.valueAt(j);
5956 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5957 return proc;
5958 }
5959 }
5960 }
5961
5962 return null;
5963 }
5964
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005965 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005966 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005967 if (proc == null) return null;
5968 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5969 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005970 }
5971 return null;
5972 }
5973
Riddle Hsua0536432019-02-16 00:38:59 +08005974 int getUidState(int uid) {
5975 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005976 }
5977
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005978 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005979 // A uid is considered to be foreground if it has a visible non-toast window.
5980 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005981 }
5982
Ricky Wai96f5c352019-04-10 18:40:17 +01005983 boolean isDeviceOwner(int uid) {
5984 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005985 }
5986
Ricky Wai96f5c352019-04-10 18:40:17 +01005987 void setDeviceOwnerUid(int uid) {
5988 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005989 }
5990
Wale Ogunwale9de19442018-10-18 19:05:03 -07005991 /**
5992 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5993 * the whitelist
5994 */
5995 String getPendingTempWhitelistTagForUidLocked(int uid) {
5996 return mPendingTempWhitelist.get(uid);
5997 }
5998
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005999 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6000 if (true || Build.IS_USER) {
6001 return;
6002 }
6003
6004 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6005 StrictMode.allowThreadDiskWrites();
6006 try {
6007 File tracesDir = new File("/data/anr");
6008 File tracesFile = null;
6009 try {
6010 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6011
6012 StringBuilder sb = new StringBuilder();
6013 Time tobj = new Time();
6014 tobj.set(System.currentTimeMillis());
6015 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
6016 sb.append(": ");
6017 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6018 sb.append(" since ");
6019 sb.append(msg);
6020 FileOutputStream fos = new FileOutputStream(tracesFile);
6021 fos.write(sb.toString().getBytes());
6022 if (app == null) {
6023 fos.write("\n*** No application process!".getBytes());
6024 }
6025 fos.close();
6026 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6027 } catch (IOException e) {
6028 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6029 return;
6030 }
6031
6032 if (app != null && app.getPid() > 0) {
6033 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6034 firstPids.add(app.getPid());
6035 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6036 }
6037
6038 File lastTracesFile = null;
6039 File curTracesFile = null;
6040 for (int i=9; i>=0; i--) {
6041 String name = String.format(Locale.US, "slow%02d.txt", i);
6042 curTracesFile = new File(tracesDir, name);
6043 if (curTracesFile.exists()) {
6044 if (lastTracesFile != null) {
6045 curTracesFile.renameTo(lastTracesFile);
6046 } else {
6047 curTracesFile.delete();
6048 }
6049 }
6050 lastTracesFile = curTracesFile;
6051 }
6052 tracesFile.renameTo(curTracesFile);
6053 } finally {
6054 StrictMode.setThreadPolicy(oldPolicy);
6055 }
6056 }
6057
Michal Karpinskida34cd42019-04-02 19:46:52 +01006058 boolean isAssociatedCompanionApp(int userId, int uid) {
6059 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6060 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006061 return false;
6062 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006063 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006064 }
6065
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006066 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006067 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006068
6069
Wale Ogunwale98875612018-10-12 07:53:02 -07006070 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6071 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006072
Riddle Hsud93a6c42018-11-29 21:50:06 +08006073 H(Looper looper) {
6074 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006075 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006076
6077 @Override
6078 public void handleMessage(Message msg) {
6079 switch (msg.what) {
6080 case REPORT_TIME_TRACKER_MSG: {
6081 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6082 tracker.deliverResult(mContext);
6083 } break;
6084 }
6085 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006086 }
6087
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006088 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006089 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006090
6091 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006092 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006093 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006094
6095 @Override
6096 public void handleMessage(Message msg) {
6097 switch (msg.what) {
6098 case DISMISS_DIALOG_UI_MSG: {
6099 final Dialog d = (Dialog) msg.obj;
6100 d.dismiss();
6101 break;
6102 }
6103 }
6104 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006105 }
6106
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006107 final class LocalService extends ActivityTaskManagerInternal {
6108 @Override
6109 public SleepToken acquireSleepToken(String tag, int displayId) {
6110 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006111 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006112 }
6113
6114 @Override
6115 public ComponentName getHomeActivityForUser(int userId) {
6116 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006117 final ActivityRecord homeActivity =
6118 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006119 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 }
6121 }
6122
6123 @Override
6124 public void onLocalVoiceInteractionStarted(IBinder activity,
6125 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6126 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006127 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 }
6129 }
6130
6131 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006132 public void notifyAppTransitionStarting(SparseIntArray reasons,
6133 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 synchronized (mGlobalLock) {
6135 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6136 reasons, timestamp);
6137 }
6138 }
6139
6140 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006141 public void notifySingleTaskDisplayDrawn(int displayId) {
6142 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6143 }
6144
6145 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 public void notifyAppTransitionFinished() {
6147 synchronized (mGlobalLock) {
6148 mStackSupervisor.notifyAppTransitionDone();
6149 }
6150 }
6151
6152 @Override
6153 public void notifyAppTransitionCancelled() {
6154 synchronized (mGlobalLock) {
6155 mStackSupervisor.notifyAppTransitionDone();
6156 }
6157 }
6158
6159 @Override
6160 public List<IBinder> getTopVisibleActivities() {
6161 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006162 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006163 }
6164 }
6165
6166 @Override
6167 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6168 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006169 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006170 }
6171 }
6172
6173 @Override
6174 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6175 Bundle bOptions) {
6176 Preconditions.checkNotNull(intents, "intents");
6177 final String[] resolvedTypes = new String[intents.length];
6178
6179 // UID of the package on user userId.
6180 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6181 // packageUid may not be initialized.
6182 int packageUid = 0;
6183 final long ident = Binder.clearCallingIdentity();
6184
6185 try {
6186 for (int i = 0; i < intents.length; i++) {
6187 resolvedTypes[i] =
6188 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6189 }
6190
6191 packageUid = AppGlobals.getPackageManager().getPackageUid(
6192 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6193 } catch (RemoteException e) {
6194 // Shouldn't happen.
6195 } finally {
6196 Binder.restoreCallingIdentity(ident);
6197 }
6198
Riddle Hsu591bf612019-02-14 17:55:31 +08006199 return getActivityStartController().startActivitiesInPackage(
6200 packageUid, packageName,
6201 intents, resolvedTypes, null /* resultTo */,
6202 SafeActivityOptions.fromBundle(bOptions), userId,
6203 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6204 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 }
6206
6207 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006208 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6209 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6210 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6211 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006212 boolean allowBackgroundActivityStart) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07006213 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006214 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006215 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6216 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6217 userId, validateIncomingUser, originatingPendingIntent,
6218 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006219 }
6220 }
6221
6222 @Override
6223 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6224 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6225 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6226 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006227 PendingIntentRecord originatingPendingIntent,
6228 boolean allowBackgroundActivityStart) {
Andrii Kulianfbc35b92019-07-16 11:24:45 -07006229 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006230 synchronized (mGlobalLock) {
6231 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6232 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6233 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006234 validateIncomingUser, originatingPendingIntent,
6235 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006236 }
6237 }
6238
6239 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6241 Intent intent, Bundle options, int userId) {
6242 return ActivityTaskManagerService.this.startActivityAsUser(
6243 caller, callerPacakge, intent,
6244 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6245 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6246 false /*validateIncomingUser*/);
6247 }
6248
6249 @Override
lumark588a3e82018-07-20 18:53:54 +08006250 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006251 synchronized (mGlobalLock) {
6252
6253 // We might change the visibilities here, so prepare an empty app transition which
6254 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006255 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006256 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006257 if (activityDisplay == null) {
6258 return;
6259 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006260 final DisplayContent dc = activityDisplay.mDisplayContent;
6261 final boolean wasTransitionSet =
6262 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006264 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006266 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267
6268 // If there was a transition set already we don't want to interfere with it as we
6269 // might be starting it too early.
6270 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006271 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 }
6273 }
6274 if (callback != null) {
6275 callback.run();
6276 }
6277 }
6278
6279 @Override
6280 public void notifyKeyguardTrustedChanged() {
6281 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006282 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006283 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284 }
6285 }
6286 }
6287
6288 /**
6289 * Called after virtual display Id is updated by
6290 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6291 * {@param vrVr2dDisplayId}.
6292 */
6293 @Override
6294 public void setVr2dDisplayId(int vr2dDisplayId) {
6295 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6296 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006297 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 }
6299 }
6300
6301 @Override
6302 public void setFocusedActivity(IBinder token) {
6303 synchronized (mGlobalLock) {
6304 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6305 if (r == null) {
6306 throw new IllegalArgumentException(
6307 "setFocusedActivity: No activity record matching token=" + token);
6308 }
Louis Chang19443452018-10-09 12:10:21 +08006309 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006310 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006311 }
6312 }
6313 }
6314
6315 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006316 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006317 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006318 }
6319
6320 @Override
6321 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006322 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006323 }
6324
6325 @Override
6326 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006327 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006328 }
6329
6330 @Override
6331 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6332 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6333 }
6334
6335 @Override
6336 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006337 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006338 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006339
6340 @Override
6341 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6342 synchronized (mGlobalLock) {
6343 mActiveVoiceInteractionServiceComponent = component;
6344 }
6345 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006346
6347 @Override
6348 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6349 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6350 return;
6351 }
6352 synchronized (mGlobalLock) {
6353 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6354 if (types == null) {
6355 if (uid < 0) {
6356 return;
6357 }
6358 types = new ArrayMap<>();
6359 mAllowAppSwitchUids.put(userId, types);
6360 }
6361 if (uid < 0) {
6362 types.remove(type);
6363 } else {
6364 types.put(type, uid);
6365 }
6366 }
6367 }
6368
6369 @Override
6370 public void onUserStopped(int userId) {
6371 synchronized (mGlobalLock) {
6372 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6373 mAllowAppSwitchUids.remove(userId);
6374 }
6375 }
6376
6377 @Override
6378 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6379 synchronized (mGlobalLock) {
6380 return ActivityTaskManagerService.this.isGetTasksAllowed(
6381 caller, callingPid, callingUid);
6382 }
6383 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006386 @Override
6387 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006389 mProcessNames.put(proc.mName, proc.mUid, proc);
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006394 @Override
6395 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006397 mProcessNames.remove(name, uid);
6398 }
6399 }
6400
Riddle Hsua0536432019-02-16 00:38:59 +08006401 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006402 @Override
6403 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006404 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006405 if (proc == mHomeProcess) {
6406 mHomeProcess = null;
6407 }
6408 if (proc == mPreviousProcess) {
6409 mPreviousProcess = null;
6410 }
6411 }
6412 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006413
Riddle Hsua0536432019-02-16 00:38:59 +08006414 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006415 @Override
6416 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006417 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006418 return mTopProcessState;
6419 }
6420 }
6421
Riddle Hsua0536432019-02-16 00:38:59 +08006422 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006423 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006424 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006425 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006426 return proc == mHeavyWeightProcess;
6427 }
6428 }
6429
Riddle Hsua0536432019-02-16 00:38:59 +08006430 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006431 @Override
6432 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006433 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006434 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6435 }
6436 }
6437
6438 @Override
6439 public void finishHeavyWeightApp() {
6440 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006441 if (mHeavyWeightProcess != null) {
6442 mHeavyWeightProcess.finishActivities();
6443 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006444 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6445 mHeavyWeightProcess);
6446 }
6447 }
6448
Riddle Hsua0536432019-02-16 00:38:59 +08006449 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006450 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006451 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006452 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006453 return isSleepingLocked();
6454 }
6455 }
6456
6457 @Override
6458 public boolean isShuttingDown() {
6459 synchronized (mGlobalLock) {
6460 return mShuttingDown;
6461 }
6462 }
6463
6464 @Override
6465 public boolean shuttingDown(boolean booted, int timeout) {
6466 synchronized (mGlobalLock) {
6467 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006468 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006469 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006470 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006471 return mStackSupervisor.shutdownLocked(timeout);
6472 }
6473 }
6474
6475 @Override
6476 public void enableScreenAfterBoot(boolean booted) {
6477 synchronized (mGlobalLock) {
6478 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6479 SystemClock.uptimeMillis());
6480 mWindowManager.enableScreenAfterBoot();
6481 updateEventDispatchingLocked(booted);
6482 }
6483 }
6484
6485 @Override
6486 public boolean showStrictModeViolationDialog() {
6487 synchronized (mGlobalLock) {
6488 return mShowDialogs && !mSleeping && !mShuttingDown;
6489 }
6490 }
6491
6492 @Override
6493 public void showSystemReadyErrorDialogsIfNeeded() {
6494 synchronized (mGlobalLock) {
6495 try {
6496 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6497 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6498 + " data partition or your device will be unstable.");
6499 mUiHandler.post(() -> {
6500 if (mShowDialogs) {
6501 AlertDialog d = new BaseErrorDialog(mUiContext);
6502 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6503 d.setCancelable(false);
6504 d.setTitle(mUiContext.getText(R.string.android_system_label));
6505 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6506 d.setButton(DialogInterface.BUTTON_POSITIVE,
6507 mUiContext.getText(R.string.ok),
6508 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6509 d.show();
6510 }
6511 });
6512 }
6513 } catch (RemoteException e) {
6514 }
6515
6516 if (!Build.isBuildConsistent()) {
6517 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6518 mUiHandler.post(() -> {
6519 if (mShowDialogs) {
6520 AlertDialog d = new BaseErrorDialog(mUiContext);
6521 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6522 d.setCancelable(false);
6523 d.setTitle(mUiContext.getText(R.string.android_system_label));
6524 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6525 d.setButton(DialogInterface.BUTTON_POSITIVE,
6526 mUiContext.getText(R.string.ok),
6527 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6528 d.show();
6529 }
6530 });
6531 }
6532 }
6533 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006534
6535 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006536 public void onProcessMapped(int pid, WindowProcessController proc) {
6537 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006538 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006539 }
6540 }
6541
6542 @Override
6543 public void onProcessUnMapped(int pid) {
6544 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006545 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006546 }
6547 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006548
6549 @Override
6550 public void onPackageDataCleared(String name) {
6551 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006552 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006553 mAppWarnings.onPackageDataCleared(name);
6554 }
6555 }
6556
6557 @Override
6558 public void onPackageUninstalled(String name) {
6559 synchronized (mGlobalLock) {
6560 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006561 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006562 }
6563 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006564
6565 @Override
6566 public void onPackageAdded(String name, boolean replacing) {
6567 synchronized (mGlobalLock) {
6568 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6569 }
6570 }
6571
6572 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006573 public void onPackageReplaced(ApplicationInfo aInfo) {
6574 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006575 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006576 }
6577 }
6578
6579 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006580 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6581 synchronized (mGlobalLock) {
6582 return compatibilityInfoForPackageLocked(ai);
6583 }
6584 }
6585
Yunfan Chen75157d72018-07-27 14:47:21 +09006586 /**
6587 * Set the corresponding display information for the process global configuration. To be
6588 * called when we need to show IME on a different display.
6589 *
6590 * @param pid The process id associated with the IME window.
6591 * @param displayId The ID of the display showing the IME.
6592 */
6593 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006594 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006595 // Don't update process-level configuration for Multi-Client IME process since other
6596 // IMEs on other displays will also receive this configuration change due to IME
6597 // services use the same application config/context.
6598 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006599
Yunfan Chen75157d72018-07-27 14:47:21 +09006600 if (pid == MY_PID || pid < 0) {
6601 if (DEBUG_CONFIGURATION) {
6602 Slog.w(TAG,
6603 "Trying to update display configuration for system/invalid process.");
6604 }
6605 return;
6606 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006607 synchronized (mGlobalLock) {
6608 final ActivityDisplay activityDisplay =
6609 mRootActivityContainer.getActivityDisplay(displayId);
6610 if (activityDisplay == null) {
6611 // Call might come when display is not yet added or has been removed.
6612 if (DEBUG_CONFIGURATION) {
6613 Slog.w(TAG, "Trying to update display configuration for non-existing "
6614 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006615 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006616 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006617 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006618 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006619 if (process == null) {
6620 if (DEBUG_CONFIGURATION) {
6621 Slog.w(TAG, "Trying to update display configuration for invalid "
6622 + "process, pid=" + pid);
6623 }
6624 return;
6625 }
6626 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6627 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006628 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006629
6630 @Override
6631 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006632 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006633 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006634 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6635 if (r != null && r.getActivityStack() != null) {
6636 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6637 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006638 }
6639 }
6640 }
6641
6642 @Override
6643 public void clearPendingResultForActivity(IBinder activityToken,
6644 WeakReference<PendingIntentRecord> pir) {
6645 synchronized (mGlobalLock) {
6646 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6647 if (r != null && r.pendingResults != null) {
6648 r.pendingResults.remove(pir);
6649 }
6650 }
6651 }
6652
6653 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006654 public ActivityTokens getTopActivityForTask(int taskId) {
6655 synchronized (mGlobalLock) {
6656 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6657 if (taskRecord == null) {
6658 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6659 + " Requested task not found");
6660 return null;
6661 }
6662 final ActivityRecord activity = taskRecord.getTopActivity();
6663 if (activity == null) {
6664 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6665 + " Requested activity not found");
6666 return null;
6667 }
6668 if (!activity.attachedToProcess()) {
6669 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6670 + activity);
6671 return null;
6672 }
6673 return new ActivityTokens(activity.appToken, activity.assistToken,
6674 activity.app.getThread());
6675 }
6676 }
6677
6678 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006679 public IIntentSender getIntentSender(int type, String packageName,
6680 int callingUid, int userId, IBinder token, String resultWho,
6681 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6682 Bundle bOptions) {
6683 synchronized (mGlobalLock) {
6684 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6685 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6686 }
6687 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006688
6689 @Override
6690 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6691 synchronized (mGlobalLock) {
6692 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6693 if (r == null) {
6694 return null;
6695 }
6696 if (r.mServiceConnectionsHolder == null) {
6697 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6698 ActivityTaskManagerService.this, r);
6699 }
6700
6701 return r.mServiceConnectionsHolder;
6702 }
6703 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006704
6705 @Override
6706 public Intent getHomeIntent() {
6707 synchronized (mGlobalLock) {
6708 return ActivityTaskManagerService.this.getHomeIntent();
6709 }
6710 }
6711
6712 @Override
6713 public boolean startHomeActivity(int userId, String reason) {
6714 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006715 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006716 }
6717 }
6718
6719 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006720 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006721 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006722 synchronized (mGlobalLock) {
6723 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006724 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006725 }
Chilun8b1f1be2019-03-13 17:14:36 +08006726 }
6727
6728 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006729 public boolean startHomeOnAllDisplays(int userId, String reason) {
6730 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006731 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006732 }
6733 }
6734
Riddle Hsua0536432019-02-16 00:38:59 +08006735 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006736 @Override
6737 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006738 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006739 if (mFactoryTest == FACTORY_TEST_OFF) {
6740 return false;
6741 }
6742 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6743 && wpc.mName.equals(mTopComponent.getPackageName())) {
6744 return true;
6745 }
6746 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6747 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6748 }
6749 }
6750
6751 @Override
6752 public void updateTopComponentForFactoryTest() {
6753 synchronized (mGlobalLock) {
6754 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6755 return;
6756 }
6757 final ResolveInfo ri = mContext.getPackageManager()
6758 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6759 final CharSequence errorMsg;
6760 if (ri != null) {
6761 final ActivityInfo ai = ri.activityInfo;
6762 final ApplicationInfo app = ai.applicationInfo;
6763 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6764 mTopAction = Intent.ACTION_FACTORY_TEST;
6765 mTopData = null;
6766 mTopComponent = new ComponentName(app.packageName, ai.name);
6767 errorMsg = null;
6768 } else {
6769 errorMsg = mContext.getResources().getText(
6770 com.android.internal.R.string.factorytest_not_system);
6771 }
6772 } else {
6773 errorMsg = mContext.getResources().getText(
6774 com.android.internal.R.string.factorytest_no_action);
6775 }
6776 if (errorMsg == null) {
6777 return;
6778 }
6779
6780 mTopAction = null;
6781 mTopData = null;
6782 mTopComponent = null;
6783 mUiHandler.post(() -> {
6784 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6785 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006786 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006787 });
6788 }
6789 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790
Riddle Hsua0536432019-02-16 00:38:59 +08006791 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 @Override
6793 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6794 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006795 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006797 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798
6799 wpc.clearRecentTasks();
6800 wpc.clearActivities();
6801
6802 if (wpc.isInstrumenting()) {
6803 finishInstrumentationCallback.run();
6804 }
6805
Jorim Jaggid0752812018-10-16 16:07:20 +02006806 if (!restarting && hasVisibleActivities) {
6807 mWindowManager.deferSurfaceLayout();
6808 try {
6809 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6810 // If there was nothing to resume, and we are not already restarting
6811 // this process, but there is a visible activity that is hosted by the
6812 // process...then make sure all visible activities are running, taking
6813 // care of restarting this process.
6814 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6815 !PRESERVE_WINDOWS);
6816 }
6817 } finally {
6818 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 }
6821 }
6822 }
6823
6824 @Override
6825 public void closeSystemDialogs(String reason) {
6826 enforceNotIsolatedCaller("closeSystemDialogs");
6827
6828 final int pid = Binder.getCallingPid();
6829 final int uid = Binder.getCallingUid();
6830 final long origId = Binder.clearCallingIdentity();
6831 try {
6832 synchronized (mGlobalLock) {
6833 // Only allow this from foreground processes, so that background
6834 // applications can't abuse it to prevent system UI from being shown.
6835 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006836 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 if (!proc.isPerceptible()) {
6838 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6839 + " from background process " + proc);
6840 return;
6841 }
6842 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 mWindowManager.closeSystemDialogs(reason);
6844
Wale Ogunwaled32da472018-11-16 07:19:28 -08006845 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006847 // Call into AM outside the synchronized block.
6848 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 } finally {
6850 Binder.restoreCallingIdentity(origId);
6851 }
6852 }
6853
6854 @Override
6855 public void cleanupDisabledPackageComponents(
6856 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6857 synchronized (mGlobalLock) {
6858 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006859 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006861 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 mStackSupervisor.scheduleIdleLocked();
6863 }
6864
6865 // Clean-up disabled tasks
6866 getRecentTasks().cleanupDisabledPackageTasksLocked(
6867 packageName, disabledClasses, userId);
6868 }
6869 }
6870
6871 @Override
6872 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6873 int userId) {
6874 synchronized (mGlobalLock) {
6875
6876 boolean didSomething =
6877 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006878 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 null, doit, evenPersistent, userId);
6880 return didSomething;
6881 }
6882 }
6883
6884 @Override
6885 public void resumeTopActivities(boolean scheduleIdle) {
6886 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006887 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 if (scheduleIdle) {
6889 mStackSupervisor.scheduleIdleLocked();
6890 }
6891 }
6892 }
6893
Riddle Hsua0536432019-02-16 00:38:59 +08006894 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 @Override
6896 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006897 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6899 }
6900 }
6901
Riddle Hsua0536432019-02-16 00:38:59 +08006902 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 @Override
6904 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006905 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006906 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 }
6908 }
6909
6910 @Override
6911 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6912 try {
6913 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6914 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6915 }
6916 } catch (RemoteException ex) {
6917 throw new SecurityException("Fail to check is caller a privileged app", ex);
6918 }
6919
6920 synchronized (mGlobalLock) {
6921 final long ident = Binder.clearCallingIdentity();
6922 try {
6923 if (mAmInternal.shouldConfirmCredentials(userId)) {
6924 if (mKeyguardController.isKeyguardLocked()) {
6925 // Showing launcher to avoid user entering credential twice.
6926 startHomeActivity(currentUserId, "notifyLockedProfile");
6927 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006928 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 }
6930 } finally {
6931 Binder.restoreCallingIdentity(ident);
6932 }
6933 }
6934 }
6935
6936 @Override
6937 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6938 mAmInternal.enforceCallingPermission(
6939 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6940
6941 synchronized (mGlobalLock) {
6942 final long ident = Binder.clearCallingIdentity();
6943 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006944 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6945 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006946 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6948 UserHandle.CURRENT);
6949 } finally {
6950 Binder.restoreCallingIdentity(ident);
6951 }
6952 }
6953 }
6954
6955 @Override
6956 public void writeActivitiesToProto(ProtoOutputStream proto) {
6957 synchronized (mGlobalLock) {
6958 // The output proto of "activity --proto activities"
6959 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006960 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006961 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6962 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 }
6964 }
6965
6966 @Override
6967 public void saveANRState(String reason) {
6968 synchronized (mGlobalLock) {
6969 final StringWriter sw = new StringWriter();
6970 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6971 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6972 if (reason != null) {
6973 pw.println(" Reason: " + reason);
6974 }
6975 pw.println();
6976 getActivityStartController().dump(pw, " ", null);
6977 pw.println();
6978 pw.println("-------------------------------------------------------------------------------");
6979 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6980 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6981 "" /* header */);
6982 pw.println();
6983 pw.close();
6984
6985 mLastANRState = sw.toString();
6986 }
6987 }
6988
6989 @Override
6990 public void clearSavedANRState() {
6991 synchronized (mGlobalLock) {
6992 mLastANRState = null;
6993 }
6994 }
6995
6996 @Override
6997 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6998 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6999 synchronized (mGlobalLock) {
7000 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7001 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7002 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7003 dumpLastANRLocked(pw);
7004 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7005 dumpLastANRTracesLocked(pw);
7006 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7007 dumpActivityStarterLocked(pw, dumpPackage);
7008 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7009 dumpActivityContainersLocked(pw);
7010 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7011 if (getRecentTasks() != null) {
7012 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7013 }
7014 }
7015 }
7016 }
7017
7018 @Override
7019 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7020 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7021 int wakefulness) {
7022 synchronized (mGlobalLock) {
7023 if (mHomeProcess != null && (dumpPackage == null
7024 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7025 if (needSep) {
7026 pw.println();
7027 needSep = false;
7028 }
7029 pw.println(" mHomeProcess: " + mHomeProcess);
7030 }
7031 if (mPreviousProcess != null && (dumpPackage == null
7032 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7033 if (needSep) {
7034 pw.println();
7035 needSep = false;
7036 }
7037 pw.println(" mPreviousProcess: " + mPreviousProcess);
7038 }
7039 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7040 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7041 StringBuilder sb = new StringBuilder(128);
7042 sb.append(" mPreviousProcessVisibleTime: ");
7043 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7044 pw.println(sb);
7045 }
7046 if (mHeavyWeightProcess != null && (dumpPackage == null
7047 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7048 if (needSep) {
7049 pw.println();
7050 needSep = false;
7051 }
7052 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7053 }
7054 if (dumpPackage == null) {
7055 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007056 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007057 }
7058 if (dumpAll) {
7059 if (dumpPackage == null) {
7060 pw.println(" mConfigWillChange: "
7061 + getTopDisplayFocusedStack().mConfigWillChange);
7062 }
7063 if (mCompatModePackages.getPackages().size() > 0) {
7064 boolean printed = false;
7065 for (Map.Entry<String, Integer> entry
7066 : mCompatModePackages.getPackages().entrySet()) {
7067 String pkg = entry.getKey();
7068 int mode = entry.getValue();
7069 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7070 continue;
7071 }
7072 if (!printed) {
7073 pw.println(" mScreenCompatPackages:");
7074 printed = true;
7075 }
7076 pw.println(" " + pkg + ": " + mode);
7077 }
7078 }
7079 }
7080
7081 if (dumpPackage == null) {
7082 pw.println(" mWakefulness="
7083 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007084 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007085 if (mRunningVoice != null) {
7086 pw.println(" mRunningVoice=" + mRunningVoice);
7087 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7088 }
7089 pw.println(" mSleeping=" + mSleeping);
7090 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7091 pw.println(" mVrController=" + mVrController);
7092 }
7093 if (mCurAppTimeTracker != null) {
7094 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7095 }
7096 if (mAllowAppSwitchUids.size() > 0) {
7097 boolean printed = false;
7098 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7099 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7100 for (int j = 0; j < types.size(); j++) {
7101 if (dumpPackage == null ||
7102 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7103 if (needSep) {
7104 pw.println();
7105 needSep = false;
7106 }
7107 if (!printed) {
7108 pw.println(" mAllowAppSwitchUids:");
7109 printed = true;
7110 }
7111 pw.print(" User ");
7112 pw.print(mAllowAppSwitchUids.keyAt(i));
7113 pw.print(": Type ");
7114 pw.print(types.keyAt(j));
7115 pw.print(" = ");
7116 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7117 pw.println();
7118 }
7119 }
7120 }
7121 }
7122 if (dumpPackage == null) {
7123 if (mController != null) {
7124 pw.println(" mController=" + mController
7125 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7126 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007127 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7128 pw.println(" mLaunchingActivityWakeLock="
7129 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007130 }
7131
7132 return needSep;
7133 }
7134 }
7135
7136 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007137 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7138 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007139 synchronized (mGlobalLock) {
7140 if (dumpPackage == null) {
7141 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7142 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007143 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7144 if (mRunningVoice != null) {
7145 final long vrToken = proto.start(
7146 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7147 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7148 mRunningVoice.toString());
7149 mVoiceWakeLock.writeToProto(
7150 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7151 proto.end(vrToken);
7152 }
7153 mVrController.writeToProto(proto,
7154 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 if (mController != null) {
7156 final long token = proto.start(CONTROLLER);
7157 proto.write(CONTROLLER, mController.toString());
7158 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7159 proto.end(token);
7160 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007161 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7162 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7163 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 }
7165
7166 if (mHomeProcess != null && (dumpPackage == null
7167 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007168 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 }
7170
7171 if (mPreviousProcess != null && (dumpPackage == null
7172 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007173 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7175 }
7176
7177 if (mHeavyWeightProcess != null && (dumpPackage == null
7178 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007179 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181
7182 for (Map.Entry<String, Integer> entry
7183 : mCompatModePackages.getPackages().entrySet()) {
7184 String pkg = entry.getKey();
7185 int mode = entry.getValue();
7186 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7187 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7188 proto.write(PACKAGE, pkg);
7189 proto.write(MODE, mode);
7190 proto.end(compatToken);
7191 }
7192 }
7193
7194 if (mCurAppTimeTracker != null) {
7195 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7196 }
7197
7198 }
7199 }
7200
7201 @Override
7202 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7203 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7204 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007205 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7206 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007207 }
7208
7209 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007210 public void dumpForOom(PrintWriter pw) {
7211 synchronized (mGlobalLock) {
7212 pw.println(" mHomeProcess: " + mHomeProcess);
7213 pw.println(" mPreviousProcess: " + mPreviousProcess);
7214 if (mHeavyWeightProcess != null) {
7215 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7216 }
7217 }
7218 }
7219
7220 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 public boolean canGcNow() {
7222 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007223 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007224 }
7225 }
7226
Riddle Hsua0536432019-02-16 00:38:59 +08007227 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007228 @Override
7229 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007230 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007231 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 return top != null ? top.app : null;
7233 }
7234 }
7235
Riddle Hsua0536432019-02-16 00:38:59 +08007236 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 @Override
7238 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007239 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007240 if (mRootActivityContainer != null) {
7241 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007242 }
7243 }
7244 }
7245
7246 @Override
7247 public void scheduleDestroyAllActivities(String reason) {
7248 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007249 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007250 }
7251 }
7252
7253 @Override
7254 public void removeUser(int userId) {
7255 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007256 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007257 }
7258 }
7259
7260 @Override
7261 public boolean switchUser(int userId, UserState userState) {
7262 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007263 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007264 }
7265 }
7266
7267 @Override
7268 public void onHandleAppCrash(WindowProcessController wpc) {
7269 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007270 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007271 }
7272 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007273
7274 @Override
7275 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7276 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007277 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007278 }
7279 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007280
Riddle Hsua0536432019-02-16 00:38:59 +08007281 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007282 @Override
7283 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007284 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007285 }
7286
Riddle Hsua0536432019-02-16 00:38:59 +08007287 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007288 @Override
7289 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007290 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007291 }
7292
Riddle Hsua0536432019-02-16 00:38:59 +08007293 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007294 @Override
7295 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007296 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007297 }
7298
Riddle Hsua0536432019-02-16 00:38:59 +08007299 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007300 @Override
7301 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007302 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007303 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007304
7305 @Override
7306 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007308 mPendingTempWhitelist.put(uid, tag);
7309 }
7310 }
7311
7312 @Override
7313 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007314 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007315 mPendingTempWhitelist.remove(uid);
7316 }
7317 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007318
7319 @Override
7320 public boolean handleAppCrashInActivityController(String processName, int pid,
7321 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7322 Runnable killCrashingAppCallback) {
7323 synchronized (mGlobalLock) {
7324 if (mController == null) {
7325 return false;
7326 }
7327
7328 try {
7329 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7330 stackTrace)) {
7331 killCrashingAppCallback.run();
7332 return true;
7333 }
7334 } catch (RemoteException e) {
7335 mController = null;
7336 Watchdog.getInstance().setActivityController(null);
7337 }
7338 return false;
7339 }
7340 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007341
7342 @Override
7343 public void removeRecentTasksByPackageName(String packageName, int userId) {
7344 synchronized (mGlobalLock) {
7345 mRecentTasks.removeTasksByPackageName(packageName, userId);
7346 }
7347 }
7348
7349 @Override
7350 public void cleanupRecentTasksForUser(int userId) {
7351 synchronized (mGlobalLock) {
7352 mRecentTasks.cleanupLocked(userId);
7353 }
7354 }
7355
7356 @Override
7357 public void loadRecentTasksForUser(int userId) {
7358 synchronized (mGlobalLock) {
7359 mRecentTasks.loadUserRecentsLocked(userId);
7360 }
7361 }
7362
7363 @Override
7364 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7365 synchronized (mGlobalLock) {
7366 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7367 }
7368 }
7369
7370 @Override
7371 public void flushRecentTasks() {
7372 mRecentTasks.flush();
7373 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007374
7375 @Override
7376 public WindowProcessController getHomeProcess() {
7377 synchronized (mGlobalLock) {
7378 return mHomeProcess;
7379 }
7380 }
7381
7382 @Override
7383 public WindowProcessController getPreviousProcess() {
7384 synchronized (mGlobalLock) {
7385 return mPreviousProcess;
7386 }
7387 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007388
7389 @Override
7390 public void clearLockedTasks(String reason) {
7391 synchronized (mGlobalLock) {
7392 getLockTaskController().clearLockedTasks(reason);
7393 }
7394 }
7395
7396 @Override
7397 public void updateUserConfiguration() {
7398 synchronized (mGlobalLock) {
7399 final Configuration configuration = new Configuration(getGlobalConfiguration());
7400 final int currentUserId = mAmInternal.getCurrentUserId();
7401 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7402 configuration, currentUserId, Settings.System.canWrite(mContext));
7403 updateConfigurationLocked(configuration, null /* starting */,
7404 false /* initLocale */, false /* persistent */, currentUserId,
7405 false /* deferResume */);
7406 }
7407 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007408
7409 @Override
7410 public boolean canShowErrorDialogs() {
7411 synchronized (mGlobalLock) {
7412 return mShowDialogs && !mSleeping && !mShuttingDown
7413 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7414 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7415 mAmInternal.getCurrentUserId())
7416 && !(UserManager.isDeviceInDemoMode(mContext)
7417 && mAmInternal.getCurrentUser().isDemo());
7418 }
7419 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007420
7421 @Override
7422 public void setProfileApp(String profileApp) {
7423 synchronized (mGlobalLock) {
7424 mProfileApp = profileApp;
7425 }
7426 }
7427
7428 @Override
7429 public void setProfileProc(WindowProcessController wpc) {
7430 synchronized (mGlobalLock) {
7431 mProfileProc = wpc;
7432 }
7433 }
7434
7435 @Override
7436 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7437 synchronized (mGlobalLock) {
7438 mProfilerInfo = profilerInfo;
7439 }
7440 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007441
7442 @Override
7443 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7444 synchronized (mGlobalLock) {
7445 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7446 }
7447 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007448
7449 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007450 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7451 boolean reducedResolution) {
7452 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7453 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007454 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007455
7456 @Override
7457 public boolean isUidForeground(int uid) {
7458 synchronized (mGlobalLock) {
7459 return ActivityTaskManagerService.this.isUidForeground(uid);
7460 }
7461 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007462
7463 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007464 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007465 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007466 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007467 }
7468 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007469
7470 @Override
7471 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007472 // Translate package names into UIDs
7473 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007474 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007475 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7476 if (uid >= 0) {
7477 result.add(uid);
7478 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007479 }
7480 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007481 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007482 }
7483 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007484 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007485}