blob: 89962a5418c11e6f6864b3f55c58c479b8516bac [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100137import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400144import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.Notification;
147import android.app.NotificationManager;
148import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.PictureInPictureParams;
150import android.app.ProfilerInfo;
151import android.app.RemoteAction;
152import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700153import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.admin.DevicePolicyCache;
155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100196import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900212import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800229import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100250import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800268import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315
Wale Ogunwale98875612018-10-12 07:53:02 -0700316 /** Used to indicate that an app transition should be animated. */
317 static final boolean ANIMATE = true;
318
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700319 /** Hardware-reported OpenGLES version. */
320 final int GL_ES_VERSION;
321
Wale Ogunwale31913b52018-10-13 08:29:31 -0700322 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
323 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
324 public static final String DUMP_LASTANR_CMD = "lastanr" ;
325 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
326 public static final String DUMP_STARTER_CMD = "starter" ;
327 public static final String DUMP_CONTAINERS_CMD = "containers" ;
328 public static final String DUMP_RECENTS_CMD = "recents" ;
329 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
330
Wale Ogunwale64258362018-10-16 15:13:37 -0700331 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
332 public static final int RELAUNCH_REASON_NONE = 0;
333 /** This activity is being relaunched due to windowing mode change. */
334 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
335 /** This activity is being relaunched due to a free-resize operation. */
336 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
337
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700338 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700339
Wale Ogunwalef6733932018-06-27 05:14:34 -0700340 /**
341 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
342 * change at runtime. Use mContext for non-UI purposes.
343 */
344 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700346 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700349 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700350 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800351 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800352 @VisibleForTesting
353 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 PowerManagerInternal mPowerManagerInternal;
355 private UsageStatsManagerInternal mUsageStatsInternal;
356
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700357 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 IntentFirewall mIntentFirewall;
359
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700360 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800361 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800362 /**
363 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
364 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
365 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
366 *
367 * @see WindowManagerThreadPriorityBooster
368 */
369 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700370 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800371 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700372 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700373 private UserManagerService mUserManager;
374 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700375 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800376 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700377 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700378 /** All processes currently running that might have a window organized by name. */
379 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100380 /** All processes we currently have running mapped by pid and uid */
381 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /** This is the process holding what we currently consider to be the "home" activity. */
383 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700384 /** The currently running heavy-weight process, if any. */
385 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700386 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /**
388 * This is the process holding the activity the user last visited that is in a different process
389 * from the one they are currently in.
390 */
391 WindowProcessController mPreviousProcess;
392 /** The time at which the previous process was last visible. */
393 long mPreviousProcessVisibleTime;
394
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700395 /** List of intents that were used to start the most recent tasks. */
396 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700397 /** State of external calls telling us if the device is awake or asleep. */
398 private boolean mKeyguardShown = false;
399
400 // Wrapper around VoiceInteractionServiceManager
401 private AssistUtils mAssistUtils;
402
403 // VoiceInteraction session ID that changes for each new request except when
404 // being called for multi-window assist in a single session.
405 private int mViSessionId = 1000;
406
407 // How long to wait in getAssistContextExtras for the activity and foreground services
408 // to respond with the result.
409 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
410
411 // How long top wait when going through the modern assist (which doesn't need to block
412 // on getting this result before starting to launch its UI).
413 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
414
415 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
416 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
417
Alison Cichowlas3e340502018-08-07 17:15:01 -0400418 // Permission tokens are used to temporarily granted a trusted app the ability to call
419 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
420 // showing any appropriate error messages to the user.
421 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
422 10 * MINUTE_IN_MILLIS;
423
424 // How long before the service actually expires a token. This is slightly longer than
425 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
426 // expiration exception.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
428 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
429
430 // How long the service will remember expired tokens, for the purpose of providing error
431 // messaging when a client uses an expired token.
432 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
433 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
434
Marvin Ramin830d4e32019-03-12 13:16:58 +0100435 // How long to whitelist the Services for when requested.
436 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
437
Alison Cichowlas3e340502018-08-07 17:15:01 -0400438 // Activity tokens of system activities that are delegating their call to
439 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
440 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
441
442 // Permission tokens that have expired, but we remember for error reporting.
443 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
444
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700445 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
446
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447 // Keeps track of the active voice interaction service component, notified from
448 // VoiceInteractionManagerService
449 ComponentName mActiveVoiceInteractionServiceComponent;
450
Michal Karpinskida34cd42019-04-02 19:46:52 +0100451 // A map userId and all its companion app uids
452 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000453
Wale Ogunwalee2172292018-10-25 10:11:10 -0700454 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 KeyguardController mKeyguardController;
456 private final ClientLifecycleManager mLifecycleManager;
457 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700458 /** The controller for all operations related to locktask. */
459 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700460 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700462 boolean mSuppressResizeConfigChanges;
463
464 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
465 new UpdateConfigurationResult();
466
467 static final class UpdateConfigurationResult {
468 // Configuration changes that were updated.
469 int changes;
470 // If the activity was relaunched to match the new configuration.
471 boolean activityRelaunched;
472
473 void reset() {
474 changes = 0;
475 activityRelaunched = false;
476 }
477 }
478
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700479 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 private int mConfigurationSeq;
481 // To cache the list of supported system locales
482 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483
484 /**
485 * Temp object used when global and/or display override configuration is updated. It is also
486 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
487 * anyone...
488 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 private Configuration mTempConfig = new Configuration();
490
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 /** Temporary to avoid allocations. */
492 final StringBuilder mStringBuilder = new StringBuilder(256);
493
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 // Amount of time after a call to stopAppSwitches() during which we will
495 // prevent further untrusted switches from happening.
496 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
497
498 /**
499 * The time at which we will allow normal application switches again,
500 * after a call to {@link #stopAppSwitches()}.
501 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700502 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503 /**
504 * This is set to true after the first switch after mAppSwitchesAllowedTime
505 * is set; any switches after that will clear the time.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508
509 IActivityController mController = null;
510 boolean mControllerIsAMonkey = false;
511
Wale Ogunwale214f3482018-10-04 11:00:47 -0700512 final int mFactoryTest;
513
514 /** Used to control how we initialize the service. */
515 ComponentName mTopComponent;
516 String mTopAction = Intent.ACTION_MAIN;
517 String mTopData;
518
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800519 /** Profiling app information. */
520 String mProfileApp = null;
521 WindowProcessController mProfileProc = null;
522 ProfilerInfo mProfilerInfo = null;
523
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700524 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700525 * Dump of the activity state at the time of the last ANR. Cleared after
526 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
527 */
528 String mLastANRState;
529
530 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700531 * Used to retain an update lock when the foreground activity is in
532 * immersive mode.
533 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700534 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535
536 /**
537 * Packages that are being allowed to perform unrestricted app switches. Mapping is
538 * User -> Type -> uid.
539 */
540 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
541
542 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private int mThumbnailWidth;
544 private int mThumbnailHeight;
545 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700546
547 /**
548 * Flag that indicates if multi-window is enabled.
549 *
550 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
551 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
552 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
553 * At least one of the forms of multi-window must be enabled in order for this flag to be
554 * initialized to 'true'.
555 *
556 * @see #mSupportsSplitScreenMultiWindow
557 * @see #mSupportsFreeformWindowManagement
558 * @see #mSupportsPictureInPicture
559 * @see #mSupportsMultiDisplay
560 */
561 boolean mSupportsMultiWindow;
562 boolean mSupportsSplitScreenMultiWindow;
563 boolean mSupportsFreeformWindowManagement;
564 boolean mSupportsPictureInPicture;
565 boolean mSupportsMultiDisplay;
566 boolean mForceResizableActivities;
567
568 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
569
570 // VR Vr2d Display Id.
571 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700572
Wale Ogunwalef6733932018-06-27 05:14:34 -0700573 /**
574 * Set while we are wanting to sleep, to prevent any
575 * activities from being started/resumed.
576 *
577 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
578 *
579 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
580 * while in the sleep state until there is a pending transition out of sleep, in which case
581 * mSleeping is set to false, and remains false while awake.
582 *
583 * Whether mSleeping can quickly toggled between true/false without the device actually
584 * display changing states is undefined.
585 */
586 private boolean mSleeping = false;
587
588 /**
589 * The process state used for processes that are running the top activities.
590 * This changes between TOP and TOP_SLEEPING to following mSleeping.
591 */
592 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
593
594 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
595 // automatically. Important for devices without direct input devices.
596 private boolean mShowDialogs = true;
597
598 /** Set if we are shutting down the system, similar to sleeping. */
599 boolean mShuttingDown = false;
600
601 /**
602 * We want to hold a wake lock while running a voice interaction session, since
603 * this may happen with the screen off and we need to keep the CPU running to
604 * be able to continue to interact with the user.
605 */
606 PowerManager.WakeLock mVoiceWakeLock;
607
608 /**
609 * Set while we are running a voice interaction. This overrides sleeping while it is active.
610 */
611 IVoiceInteractionSession mRunningVoice;
612
613 /**
614 * The last resumed activity. This is identical to the current resumed activity most
615 * of the time but could be different when we're pausing one activity before we resume
616 * another activity.
617 */
618 ActivityRecord mLastResumedActivity;
619
620 /**
621 * The activity that is currently being traced as the active resumed activity.
622 *
623 * @see #updateResumedAppTrace
624 */
625 private @Nullable ActivityRecord mTracedResumedActivity;
626
627 /** If non-null, we are tracking the time the user spends in the currently focused app. */
628 AppTimeTracker mCurAppTimeTracker;
629
Wale Ogunwale008163e2018-07-23 23:11:08 -0700630 private AppWarnings mAppWarnings;
631
Wale Ogunwale53783742018-09-16 10:21:51 -0700632 /**
633 * Packages that the user has asked to have run in screen size
634 * compatibility mode instead of filling the screen.
635 */
636 CompatModePackages mCompatModePackages;
637
Wale Ogunwalef6733932018-06-27 05:14:34 -0700638 private FontScaleSettingObserver mFontScaleSettingObserver;
639
Ricky Wai96f5c352019-04-10 18:40:17 +0100640 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000641
Wale Ogunwalef6733932018-06-27 05:14:34 -0700642 private final class FontScaleSettingObserver extends ContentObserver {
643 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
644 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
645
646 public FontScaleSettingObserver() {
647 super(mH);
648 final ContentResolver resolver = mContext.getContentResolver();
649 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
650 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
651 UserHandle.USER_ALL);
652 }
653
654 @Override
655 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
656 if (mFontScaleUri.equals(uri)) {
657 updateFontScaleIfNeeded(userId);
658 } else if (mHideErrorDialogsUri.equals(uri)) {
659 synchronized (mGlobalLock) {
660 updateShouldShowDialogsLocked(getGlobalConfiguration());
661 }
662 }
663 }
664 }
665
Riddle Hsua0536432019-02-16 00:38:59 +0800666 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
667 @Target(ElementType.METHOD)
668 @Retention(RetentionPolicy.SOURCE)
669 @interface HotPath {
670 int NONE = 0;
671 int OOM_ADJUSTMENT = 1;
672 int LRU_UPDATE = 2;
673 int PROCESS_CHANGE = 3;
674 int caller() default NONE;
675 }
676
Charles Chen8d98dd22018-12-26 17:36:54 +0800677 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
678 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700679 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700680 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700681 mSystemThread = ActivityThread.currentActivityThread();
682 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700683 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800684 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700685 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700686 }
687
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700688 public void onSystemReady() {
689 synchronized (mGlobalLock) {
690 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
691 PackageManager.FEATURE_CANT_SAVE_STATE);
692 mAssistUtils = new AssistUtils(mContext);
693 mVrController.onSystemReady();
694 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700695 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700697 }
698
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700699 public void onInitPowerManagement() {
700 synchronized (mGlobalLock) {
701 mStackSupervisor.initPowerManagement();
702 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
703 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
704 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
705 mVoiceWakeLock.setReferenceCounted(false);
706 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700707 }
708
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700709 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700710 mFontScaleSettingObserver = new FontScaleSettingObserver();
711 }
712
Wale Ogunwale59507092018-10-29 09:00:30 -0700713 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700714 final boolean freeformWindowManagement =
715 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
716 || Settings.Global.getInt(
717 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
718
719 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
720 final boolean supportsPictureInPicture = supportsMultiWindow &&
721 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
722 final boolean supportsSplitScreenMultiWindow =
723 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
724 final boolean supportsMultiDisplay = mContext.getPackageManager()
725 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700726 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
727 final boolean forceResizable = Settings.Global.getInt(
728 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700729 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730
731 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900732 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700733
734 final Configuration configuration = new Configuration();
735 Settings.System.getConfiguration(resolver, configuration);
736 if (forceRtl) {
737 // This will take care of setting the correct layout direction flags
738 configuration.setLayoutDirection(configuration.locale);
739 }
740
741 synchronized (mGlobalLock) {
742 mForceResizableActivities = forceResizable;
743 final boolean multiWindowFormEnabled = freeformWindowManagement
744 || supportsSplitScreenMultiWindow
745 || supportsPictureInPicture
746 || supportsMultiDisplay;
747 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
748 mSupportsMultiWindow = true;
749 mSupportsFreeformWindowManagement = freeformWindowManagement;
750 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
751 mSupportsPictureInPicture = supportsPictureInPicture;
752 mSupportsMultiDisplay = supportsMultiDisplay;
753 } else {
754 mSupportsMultiWindow = false;
755 mSupportsFreeformWindowManagement = false;
756 mSupportsSplitScreenMultiWindow = false;
757 mSupportsPictureInPicture = false;
758 mSupportsMultiDisplay = false;
759 }
760 mWindowManager.setForceResizableTasks(mForceResizableActivities);
761 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700762 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
763 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700764 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765 // This happens before any activities are started, so we can change global configuration
766 // in-place.
767 updateConfigurationLocked(configuration, null, true);
768 final Configuration globalConfig = getGlobalConfiguration();
769 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
770
771 // Load resources only after the current configuration has been set.
772 final Resources res = mContext.getResources();
773 mThumbnailWidth = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_width);
775 mThumbnailHeight = res.getDimensionPixelSize(
776 com.android.internal.R.dimen.thumbnail_height);
777
778 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
779 mFullscreenThumbnailScale = (float) res
780 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
781 (float) globalConfig.screenWidthDp;
782 } else {
783 mFullscreenThumbnailScale = res.getFraction(
784 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
785 }
786 }
787 }
788
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800789 public WindowManagerGlobalLock getGlobalLock() {
790 return mGlobalLock;
791 }
792
Yunfan Chen585f2932019-01-29 16:04:45 +0900793 /** For test purpose only. */
794 @VisibleForTesting
795 public ActivityTaskManagerInternal getAtmInternal() {
796 return mInternal;
797 }
798
Riddle Hsud93a6c42018-11-29 21:50:06 +0800799 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
800 Looper looper) {
801 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700802 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700803 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700804 final File systemDir = SystemServiceManager.ensureSystemDir();
805 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
806 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700808
809 mTempConfig.setToDefaults();
810 mTempConfig.setLocales(LocaleList.getDefault());
811 mConfigurationSeq = mTempConfig.seq = 1;
812 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800813 mRootActivityContainer = new RootActivityContainer(this);
814 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700815
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700816 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700818 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700820 mRecentTasks = createRecentTasks();
821 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700823 mKeyguardController = mStackSupervisor.getKeyguardController();
824 }
825
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700826 public void onActivityManagerInternalAdded() {
827 synchronized (mGlobalLock) {
828 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
829 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
830 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700831 }
832
Yunfan Chen75157d72018-07-27 14:47:21 +0900833 int increaseConfigurationSeqLocked() {
834 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
835 return mConfigurationSeq;
836 }
837
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700838 protected ActivityStackSupervisor createStackSupervisor() {
839 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
840 supervisor.initialize();
841 return supervisor;
842 }
843
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700844 public void setWindowManager(WindowManagerService wm) {
845 synchronized (mGlobalLock) {
846 mWindowManager = wm;
847 mLockTaskController.setWindowManager(wm);
848 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800849 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700851 }
852
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700853 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
854 synchronized (mGlobalLock) {
855 mUsageStatsInternal = usageStatsManager;
856 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700857 }
858
Wale Ogunwalef6733932018-06-27 05:14:34 -0700859 UserManagerService getUserManager() {
860 if (mUserManager == null) {
861 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
862 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
863 }
864 return mUserManager;
865 }
866
867 AppOpsService getAppOpsService() {
868 if (mAppOpsService == null) {
869 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
870 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
871 }
872 return mAppOpsService;
873 }
874
875 boolean hasUserRestriction(String restriction, int userId) {
876 return getUserManager().hasUserRestriction(restriction, userId);
877 }
878
Michal Karpinski15486842019-04-25 17:33:42 +0100879 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
880 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
881 callingUid, callingPackage);
882 if (mode == AppOpsManager.MODE_DEFAULT) {
883 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
884 == PERMISSION_GRANTED;
885 }
886 return mode == AppOpsManager.MODE_ALLOWED;
887 }
888
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700889 protected RecentTasks createRecentTasks() {
890 return new RecentTasks(this, mStackSupervisor);
891 }
892
893 RecentTasks getRecentTasks() {
894 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700895 }
896
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700897 ClientLifecycleManager getLifecycleManager() {
898 return mLifecycleManager;
899 }
900
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700901 ActivityStartController getActivityStartController() {
902 return mActivityStartController;
903 }
904
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700905 TaskChangeNotificationController getTaskChangeNotificationController() {
906 return mTaskChangeNotificationController;
907 }
908
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700909 LockTaskController getLockTaskController() {
910 return mLockTaskController;
911 }
912
Yunfan Chen75157d72018-07-27 14:47:21 +0900913 /**
914 * Return the global configuration used by the process corresponding to the input pid. This is
915 * usually the global configuration with some overrides specific to that process.
916 */
917 Configuration getGlobalConfigurationForCallingPid() {
918 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800919 return getGlobalConfigurationForPid(pid);
920 }
921
922 /**
923 * Return the global configuration used by the process corresponding to the given pid.
924 */
925 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900926 if (pid == MY_PID || pid < 0) {
927 return getGlobalConfiguration();
928 }
929 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100930 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900931 return app != null ? app.getConfiguration() : getGlobalConfiguration();
932 }
933 }
934
935 /**
936 * Return the device configuration info used by the process corresponding to the input pid.
937 * The value is consistent with the global configuration for the process.
938 */
939 @Override
940 public ConfigurationInfo getDeviceConfigurationInfo() {
941 ConfigurationInfo config = new ConfigurationInfo();
942 synchronized (mGlobalLock) {
943 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
944 config.reqTouchScreen = globalConfig.touchscreen;
945 config.reqKeyboardType = globalConfig.keyboard;
946 config.reqNavigation = globalConfig.navigation;
947 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
948 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
949 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
950 }
951 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
952 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
954 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700955 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900956 }
957 return config;
958 }
959
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700961 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700962 }
963
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700964 public static final class Lifecycle extends SystemService {
965 private final ActivityTaskManagerService mService;
966
967 public Lifecycle(Context context) {
968 super(context);
969 mService = new ActivityTaskManagerService(context);
970 }
971
972 @Override
973 public void onStart() {
974 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700975 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700976 }
977
Garfield Tan891146c2018-10-09 12:14:00 -0700978 @Override
979 public void onUnlockUser(int userId) {
980 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800981 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700982 }
983 }
984
985 @Override
986 public void onCleanupUser(int userId) {
987 synchronized (mService.getGlobalLock()) {
988 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
989 }
990 }
991
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 public ActivityTaskManagerService getService() {
993 return mService;
994 }
995 }
996
997 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 public final int startActivity(IApplicationThread caller, String callingPackage,
999 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1000 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1001 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1002 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1003 UserHandle.getCallingUserId());
1004 }
1005
1006 @Override
1007 public final int startActivities(IApplicationThread caller, String callingPackage,
1008 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1009 int userId) {
1010 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001011 enforceNotIsolatedCaller(reason);
1012 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001014 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1015 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1016 reason, null /* originatingPendingIntent */,
1017 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001018 }
1019
1020 @Override
1021 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1022 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1023 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1024 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1025 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1026 true /*validateIncomingUser*/);
1027 }
1028
1029 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1030 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1031 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1032 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001033 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001035 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1037
1038 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001039 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 .setCaller(caller)
1041 .setCallingPackage(callingPackage)
1042 .setResolvedType(resolvedType)
1043 .setResultTo(resultTo)
1044 .setResultWho(resultWho)
1045 .setRequestCode(requestCode)
1046 .setStartFlags(startFlags)
1047 .setProfilerInfo(profilerInfo)
1048 .setActivityOptions(bOptions)
1049 .setMayWait(userId)
1050 .execute();
1051
1052 }
1053
1054 @Override
1055 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1056 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1058 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059 // Refuse possible leaked file descriptors
1060 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1061 throw new IllegalArgumentException("File descriptors passed in Intent");
1062 }
1063
1064 if (!(target instanceof PendingIntentRecord)) {
1065 throw new IllegalArgumentException("Bad PendingIntent object");
1066 }
1067
1068 PendingIntentRecord pir = (PendingIntentRecord)target;
1069
1070 synchronized (mGlobalLock) {
1071 // If this is coming from the currently resumed activity, it is
1072 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001073 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 if (stack.mResumedActivity != null &&
1075 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001076 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001077 }
1078 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001079 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 }
1082
1083 @Override
1084 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1085 Bundle bOptions) {
1086 // Refuse possible leaked file descriptors
1087 if (intent != null && intent.hasFileDescriptors()) {
1088 throw new IllegalArgumentException("File descriptors passed in Intent");
1089 }
1090 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1091
1092 synchronized (mGlobalLock) {
1093 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1094 if (r == null) {
1095 SafeActivityOptions.abort(options);
1096 return false;
1097 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001098 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 // The caller is not running... d'oh!
1100 SafeActivityOptions.abort(options);
1101 return false;
1102 }
1103 intent = new Intent(intent);
1104 // The caller is not allowed to change the data.
1105 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1106 // And we are resetting to find the next component...
1107 intent.setComponent(null);
1108
1109 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1110
1111 ActivityInfo aInfo = null;
1112 try {
1113 List<ResolveInfo> resolves =
1114 AppGlobals.getPackageManager().queryIntentActivities(
1115 intent, r.resolvedType,
1116 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1117 UserHandle.getCallingUserId()).getList();
1118
1119 // Look for the original activity in the list...
1120 final int N = resolves != null ? resolves.size() : 0;
1121 for (int i=0; i<N; i++) {
1122 ResolveInfo rInfo = resolves.get(i);
1123 if (rInfo.activityInfo.packageName.equals(r.packageName)
1124 && rInfo.activityInfo.name.equals(r.info.name)) {
1125 // We found the current one... the next matching is
1126 // after it.
1127 i++;
1128 if (i<N) {
1129 aInfo = resolves.get(i).activityInfo;
1130 }
1131 if (debug) {
1132 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1133 + "/" + r.info.name);
1134 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1135 ? "null" : aInfo.packageName + "/" + aInfo.name));
1136 }
1137 break;
1138 }
1139 }
1140 } catch (RemoteException e) {
1141 }
1142
1143 if (aInfo == null) {
1144 // Nobody who is next!
1145 SafeActivityOptions.abort(options);
1146 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1147 return false;
1148 }
1149
1150 intent.setComponent(new ComponentName(
1151 aInfo.applicationInfo.packageName, aInfo.name));
1152 intent.setFlags(intent.getFlags()&~(
1153 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1154 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1155 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1156 FLAG_ACTIVITY_NEW_TASK));
1157
1158 // Okay now we need to start the new activity, replacing the currently running activity.
1159 // This is a little tricky because we want to start the new one as if the current one is
1160 // finished, but not finish the current one first so that there is no flicker.
1161 // And thus...
1162 final boolean wasFinishing = r.finishing;
1163 r.finishing = true;
1164
1165 // Propagate reply information over to the new activity.
1166 final ActivityRecord resultTo = r.resultTo;
1167 final String resultWho = r.resultWho;
1168 final int requestCode = r.requestCode;
1169 r.resultTo = null;
1170 if (resultTo != null) {
1171 resultTo.removeResultsLocked(r, resultWho, requestCode);
1172 }
1173
1174 final long origId = Binder.clearCallingIdentity();
1175 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001176 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001178 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001179 .setResolvedType(r.resolvedType)
1180 .setActivityInfo(aInfo)
1181 .setResultTo(resultTo != null ? resultTo.appToken : null)
1182 .setResultWho(resultWho)
1183 .setRequestCode(requestCode)
1184 .setCallingPid(-1)
1185 .setCallingUid(r.launchedFromUid)
1186 .setCallingPackage(r.launchedFromPackage)
1187 .setRealCallingPid(-1)
1188 .setRealCallingUid(r.launchedFromUid)
1189 .setActivityOptions(options)
1190 .execute();
1191 Binder.restoreCallingIdentity(origId);
1192
1193 r.finishing = wasFinishing;
1194 if (res != ActivityManager.START_SUCCESS) {
1195 return false;
1196 }
1197 return true;
1198 }
1199 }
1200
1201 @Override
1202 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1203 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1204 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1205 final WaitResult res = new WaitResult();
1206 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001207 enforceNotIsolatedCaller("startActivityAndWait");
1208 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1209 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001211 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 .setCaller(caller)
1213 .setCallingPackage(callingPackage)
1214 .setResolvedType(resolvedType)
1215 .setResultTo(resultTo)
1216 .setResultWho(resultWho)
1217 .setRequestCode(requestCode)
1218 .setStartFlags(startFlags)
1219 .setActivityOptions(bOptions)
1220 .setMayWait(userId)
1221 .setProfilerInfo(profilerInfo)
1222 .setWaitResult(res)
1223 .execute();
1224 }
1225 return res;
1226 }
1227
1228 @Override
1229 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1230 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1231 int startFlags, Configuration config, Bundle bOptions, int userId) {
1232 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001233 enforceNotIsolatedCaller("startActivityWithConfig");
1234 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1235 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001237 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 .setCaller(caller)
1239 .setCallingPackage(callingPackage)
1240 .setResolvedType(resolvedType)
1241 .setResultTo(resultTo)
1242 .setResultWho(resultWho)
1243 .setRequestCode(requestCode)
1244 .setStartFlags(startFlags)
1245 .setGlobalConfiguration(config)
1246 .setActivityOptions(bOptions)
1247 .setMayWait(userId)
1248 .execute();
1249 }
1250 }
1251
Alison Cichowlas3e340502018-08-07 17:15:01 -04001252
1253 @Override
1254 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1255 int callingUid = Binder.getCallingUid();
1256 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1257 throw new SecurityException("Only the system process can request a permission token, "
1258 + "received request from uid: " + callingUid);
1259 }
1260 IBinder permissionToken = new Binder();
1261 synchronized (mGlobalLock) {
1262 mStartActivitySources.put(permissionToken, delegatorToken);
1263 }
1264
1265 Message expireMsg = PooledLambda.obtainMessage(
1266 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1267 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1268
1269 Message forgetMsg = PooledLambda.obtainMessage(
1270 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1271 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1272
1273 return permissionToken;
1274 }
1275
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 @Override
1277 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1278 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1280 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 // permission grants) as any app that may launch one of your own activities. So we only
1283 // allow this in two cases:
1284 // 1) The caller is an activity that is part of the core framework, and then only when it
1285 // is running as the system.
1286 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1287 // can only be requested by a system activity, which may then delegate this call to
1288 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 final ActivityRecord sourceRecord;
1290 final int targetUid;
1291 final String targetPackage;
1292 final boolean isResolver;
1293 synchronized (mGlobalLock) {
1294 if (resultTo == null) {
1295 throw new SecurityException("Must be called from an activity");
1296 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001297 final IBinder sourceToken;
1298 if (permissionToken != null) {
1299 // To even attempt to use a permissionToken, an app must also have this signature
1300 // permission.
1301 mAmInternal.enforceCallingPermission(
1302 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1303 "startActivityAsCaller");
1304 // If called with a permissionToken, we want the sourceRecord from the delegator
1305 // activity that requested this token.
1306 sourceToken = mStartActivitySources.remove(permissionToken);
1307 if (sourceToken == null) {
1308 // Invalid permissionToken, check if it recently expired.
1309 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1310 throw new SecurityException("Called with expired permission token: "
1311 + permissionToken);
1312 } else {
1313 throw new SecurityException("Called with invalid permission token: "
1314 + permissionToken);
1315 }
1316 }
1317 } else {
1318 // This method was called directly by the source.
1319 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001321
Wale Ogunwaled32da472018-11-16 07:19:28 -08001322 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001323 if (sourceRecord == null) {
1324 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 }
1326 if (sourceRecord.app == null) {
1327 throw new SecurityException("Called without a process attached to activity");
1328 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001329
1330 // Whether called directly or from a delegate, the source activity must be from the
1331 // android package.
1332 if (!sourceRecord.info.packageName.equals("android")) {
1333 throw new SecurityException("Must be called from an activity that is "
1334 + "declared in the android package");
1335 }
1336
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001337 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 // This is still okay, as long as this activity is running under the
1339 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001342 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 + " must be system uid or original calling uid "
1344 + sourceRecord.launchedFromUid);
1345 }
1346 }
1347 if (ignoreTargetSecurity) {
1348 if (intent.getComponent() == null) {
1349 throw new SecurityException(
1350 "Component must be specified with ignoreTargetSecurity");
1351 }
1352 if (intent.getSelector() != null) {
1353 throw new SecurityException(
1354 "Selector not allowed with ignoreTargetSecurity");
1355 }
1356 }
1357 targetUid = sourceRecord.launchedFromUid;
1358 targetPackage = sourceRecord.launchedFromPackage;
1359 isResolver = sourceRecord.isResolverOrChildActivity();
1360 }
1361
1362 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001363 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 }
1365
1366 // TODO: Switch to user app stacks here.
1367 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001368 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 .setCallingUid(targetUid)
1370 .setCallingPackage(targetPackage)
1371 .setResolvedType(resolvedType)
1372 .setResultTo(resultTo)
1373 .setResultWho(resultWho)
1374 .setRequestCode(requestCode)
1375 .setStartFlags(startFlags)
1376 .setActivityOptions(bOptions)
1377 .setMayWait(userId)
1378 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1379 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001380 // The target may well be in the background, which would normally prevent it
1381 // from starting an activity. Here we definitely want the start to succeed.
1382 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001383 .execute();
1384 } catch (SecurityException e) {
1385 // XXX need to figure out how to propagate to original app.
1386 // A SecurityException here is generally actually a fault of the original
1387 // calling activity (such as a fairly granting permissions), so propagate it
1388 // back to them.
1389 /*
1390 StringBuilder msg = new StringBuilder();
1391 msg.append("While launching");
1392 msg.append(intent.toString());
1393 msg.append(": ");
1394 msg.append(e.getMessage());
1395 */
1396 throw e;
1397 }
1398 }
1399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1401 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1402 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1403 }
1404
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 @Override
1406 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1407 Intent intent, String resolvedType, IVoiceInteractionSession session,
1408 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1409 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 if (session == null || interactor == null) {
1412 throw new NullPointerException("null session or interactor");
1413 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001414 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001416 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 .setCallingUid(callingUid)
1418 .setCallingPackage(callingPackage)
1419 .setResolvedType(resolvedType)
1420 .setVoiceSession(session)
1421 .setVoiceInteractor(interactor)
1422 .setStartFlags(startFlags)
1423 .setProfilerInfo(profilerInfo)
1424 .setActivityOptions(bOptions)
1425 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001426 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 .execute();
1428 }
1429
1430 @Override
1431 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1432 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001433 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1434 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001436 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .setCallingUid(callingUid)
1438 .setCallingPackage(callingPackage)
1439 .setResolvedType(resolvedType)
1440 .setActivityOptions(bOptions)
1441 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001442 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .execute();
1444 }
1445
1446 @Override
1447 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1448 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450 final int callingPid = Binder.getCallingPid();
1451 final long origId = Binder.clearCallingIdentity();
1452 try {
1453 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001454 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1455 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456
1457 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001458 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1459 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1461 recentsUid, assistDataReceiver);
1462 }
1463 } finally {
1464 Binder.restoreCallingIdentity(origId);
1465 }
1466 }
1467
1468 @Override
1469 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001470 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 "startActivityFromRecents()");
1472
1473 final int callingPid = Binder.getCallingPid();
1474 final int callingUid = Binder.getCallingUid();
1475 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1476 final long origId = Binder.clearCallingIdentity();
1477 try {
1478 synchronized (mGlobalLock) {
1479 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1480 safeOptions);
1481 }
1482 } finally {
1483 Binder.restoreCallingIdentity(origId);
1484 }
1485 }
1486
1487 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001488 * Public API to check if the client is allowed to start an activity on specified display.
1489 *
1490 * If the target display is private or virtual, some restrictions will apply.
1491 *
1492 * @param displayId Target display id.
1493 * @param intent Intent used to launch the activity.
1494 * @param resolvedType The MIME type of the intent.
1495 * @param userId The id of the user for whom the call is made.
1496 * @return {@code true} if a call to start an activity on the target display should succeed and
1497 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1498 */
1499 @Override
1500 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1501 String resolvedType, int userId) {
1502 final int callingUid = Binder.getCallingUid();
1503 final int callingPid = Binder.getCallingPid();
1504 final long origId = Binder.clearCallingIdentity();
1505
1506 try {
1507 // Collect information about the target of the Intent.
1508 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1509 0 /* startFlags */, null /* profilerInfo */, userId,
1510 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1511 UserHandle.USER_NULL));
1512 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1513
1514 synchronized (mGlobalLock) {
1515 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1516 aInfo);
1517 }
1518 } finally {
1519 Binder.restoreCallingIdentity(origId);
1520 }
1521 }
1522
1523 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 * This is the internal entry point for handling Activity.finish().
1525 *
1526 * @param token The Binder token referencing the Activity we want to finish.
1527 * @param resultCode Result code, if any, from this Activity.
1528 * @param resultData Result data (Intent), if any, from this Activity.
1529 * @param finishTask Whether to finish the task associated with this Activity.
1530 *
1531 * @return Returns true if the activity successfully finished, or false if it is still running.
1532 */
1533 @Override
1534 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1535 int finishTask) {
1536 // Refuse possible leaked file descriptors
1537 if (resultData != null && resultData.hasFileDescriptors()) {
1538 throw new IllegalArgumentException("File descriptors passed in Intent");
1539 }
1540
1541 synchronized (mGlobalLock) {
1542 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1543 if (r == null) {
1544 return true;
1545 }
1546 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001547 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001548 ActivityRecord rootR = tr.getRootActivity();
1549 if (rootR == null) {
1550 Slog.w(TAG, "Finishing task with all activities already finished");
1551 }
1552 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1553 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001554 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 return false;
1556 }
1557
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001558 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1559 // We should consolidate.
1560 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001562 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 if (next != null) {
1564 // ask watcher if this is allowed
1565 boolean resumeOK = true;
1566 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001567 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001569 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 Watchdog.getInstance().setActivityController(null);
1571 }
1572
1573 if (!resumeOK) {
1574 Slog.i(TAG, "Not finishing activity because controller resumed");
1575 return false;
1576 }
1577 }
1578 }
1579 final long origId = Binder.clearCallingIdentity();
1580 try {
1581 boolean res;
1582 final boolean finishWithRootActivity =
1583 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1584 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1585 || (finishWithRootActivity && r == rootR)) {
1586 // If requested, remove the task that is associated to this activity only if it
1587 // was the root activity in the task. The result code and data is ignored
1588 // because we don't support returning them across task boundaries. Also, to
1589 // keep backwards compatibility we remove the task from recents when finishing
1590 // task with root activity.
1591 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1592 finishWithRootActivity, "finish-activity");
1593 if (!res) {
1594 Slog.i(TAG, "Removing task failed to finish activity");
1595 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001596 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001597 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 } else {
1599 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1600 resultData, "app-request", true);
1601 if (!res) {
1602 Slog.i(TAG, "Failed to finish by app-request");
1603 }
1604 }
1605 return res;
1606 } finally {
1607 Binder.restoreCallingIdentity(origId);
1608 }
1609 }
1610 }
1611
1612 @Override
1613 public boolean finishActivityAffinity(IBinder token) {
1614 synchronized (mGlobalLock) {
1615 final long origId = Binder.clearCallingIdentity();
1616 try {
1617 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1618 if (r == null) {
1619 return false;
1620 }
1621
1622 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1623 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001624 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001625 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001626 return false;
1627 }
1628 return task.getStack().finishActivityAffinityLocked(r);
1629 } finally {
1630 Binder.restoreCallingIdentity(origId);
1631 }
1632 }
1633 }
1634
1635 @Override
1636 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1637 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001638 try {
1639 WindowProcessController proc = null;
1640 synchronized (mGlobalLock) {
1641 ActivityStack stack = ActivityRecord.getStackLocked(token);
1642 if (stack == null) {
1643 return;
1644 }
1645 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1646 false /* fromTimeout */, false /* processPausingActivities */, config);
1647 if (r != null) {
1648 proc = r.app;
1649 }
1650 if (stopProfiling && proc != null) {
1651 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001652 }
1653 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001654 } finally {
1655 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 }
1658
1659 @Override
1660 public final void activityResumed(IBinder token) {
1661 final long origId = Binder.clearCallingIdentity();
1662 synchronized (mGlobalLock) {
1663 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001664 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001665 }
1666 Binder.restoreCallingIdentity(origId);
1667 }
1668
1669 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001670 public final void activityTopResumedStateLost() {
1671 final long origId = Binder.clearCallingIdentity();
1672 synchronized (mGlobalLock) {
1673 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1674 }
1675 Binder.restoreCallingIdentity(origId);
1676 }
1677
1678 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001679 public final void activityPaused(IBinder token) {
1680 final long origId = Binder.clearCallingIdentity();
1681 synchronized (mGlobalLock) {
1682 ActivityStack stack = ActivityRecord.getStackLocked(token);
1683 if (stack != null) {
1684 stack.activityPausedLocked(token, false);
1685 }
1686 }
1687 Binder.restoreCallingIdentity(origId);
1688 }
1689
1690 @Override
1691 public final void activityStopped(IBinder token, Bundle icicle,
1692 PersistableBundle persistentState, CharSequence description) {
1693 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1694
1695 // Refuse possible leaked file descriptors
1696 if (icicle != null && icicle.hasFileDescriptors()) {
1697 throw new IllegalArgumentException("File descriptors passed in Bundle");
1698 }
1699
1700 final long origId = Binder.clearCallingIdentity();
1701
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001702 String restartingName = null;
1703 int restartingUid = 0;
1704 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001705 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001706 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001708 if (r.attachedToProcess()
1709 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1710 // The activity was requested to restart from
1711 // {@link #restartActivityProcessIfVisible}.
1712 restartingName = r.app.mName;
1713 restartingUid = r.app.mUid;
1714 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 r.activityStoppedLocked(icicle, persistentState, description);
1716 }
1717 }
1718
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001719 if (restartingName != null) {
1720 // In order to let the foreground activity can be restarted with its saved state from
1721 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1722 // until the activity reports stopped with the state. And the activity record will be
1723 // kept because the record state is restarting, then the activity will be restarted
1724 // immediately if it is still the top one.
1725 mStackSupervisor.removeRestartTimeouts(r);
1726 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1727 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001728 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729
1730 Binder.restoreCallingIdentity(origId);
1731 }
1732
1733 @Override
1734 public final void activityDestroyed(IBinder token) {
1735 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1736 synchronized (mGlobalLock) {
1737 ActivityStack stack = ActivityRecord.getStackLocked(token);
1738 if (stack != null) {
1739 stack.activityDestroyedLocked(token, "activityDestroyed");
1740 }
1741 }
1742 }
1743
1744 @Override
1745 public final void activityRelaunched(IBinder token) {
1746 final long origId = Binder.clearCallingIdentity();
1747 synchronized (mGlobalLock) {
1748 mStackSupervisor.activityRelaunchedLocked(token);
1749 }
1750 Binder.restoreCallingIdentity(origId);
1751 }
1752
1753 public final void activitySlept(IBinder token) {
1754 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1755
1756 final long origId = Binder.clearCallingIdentity();
1757
1758 synchronized (mGlobalLock) {
1759 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1760 if (r != null) {
1761 mStackSupervisor.activitySleptLocked(r);
1762 }
1763 }
1764
1765 Binder.restoreCallingIdentity(origId);
1766 }
1767
1768 @Override
1769 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1770 synchronized (mGlobalLock) {
1771 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1772 if (r == null) {
1773 return;
1774 }
1775 final long origId = Binder.clearCallingIdentity();
1776 try {
1777 r.setRequestedOrientation(requestedOrientation);
1778 } finally {
1779 Binder.restoreCallingIdentity(origId);
1780 }
1781 }
1782 }
1783
1784 @Override
1785 public int getRequestedOrientation(IBinder token) {
1786 synchronized (mGlobalLock) {
1787 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1788 if (r == null) {
1789 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1790 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001791 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001792 }
1793 }
1794
1795 @Override
1796 public void setImmersive(IBinder token, boolean immersive) {
1797 synchronized (mGlobalLock) {
1798 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1799 if (r == null) {
1800 throw new IllegalArgumentException();
1801 }
1802 r.immersive = immersive;
1803
1804 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001805 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 }
1809 }
1810 }
1811
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001812 void applyUpdateLockStateLocked(ActivityRecord r) {
1813 // Modifications to the UpdateLock state are done on our handler, outside
1814 // the activity manager's locks. The new state is determined based on the
1815 // state *now* of the relevant activity record. The object is passed to
1816 // the handler solely for logging detail, not to be consulted/modified.
1817 final boolean nextState = r != null && r.immersive;
1818 mH.post(() -> {
1819 if (mUpdateLock.isHeld() != nextState) {
1820 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1821 "Applying new update lock state '" + nextState + "' for " + r);
1822 if (nextState) {
1823 mUpdateLock.acquire();
1824 } else {
1825 mUpdateLock.release();
1826 }
1827 }
1828 });
1829 }
1830
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001831 @Override
1832 public boolean isImmersive(IBinder token) {
1833 synchronized (mGlobalLock) {
1834 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1835 if (r == null) {
1836 throw new IllegalArgumentException();
1837 }
1838 return r.immersive;
1839 }
1840 }
1841
1842 @Override
1843 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001844 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001845 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001846 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847 return (r != null) ? r.immersive : false;
1848 }
1849 }
1850
1851 @Override
1852 public void overridePendingTransition(IBinder token, String packageName,
1853 int enterAnim, int exitAnim) {
1854 synchronized (mGlobalLock) {
1855 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1856 if (self == null) {
1857 return;
1858 }
1859
1860 final long origId = Binder.clearCallingIdentity();
1861
1862 if (self.isState(
1863 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001864 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001865 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 }
1867
1868 Binder.restoreCallingIdentity(origId);
1869 }
1870 }
1871
1872 @Override
1873 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001874 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001876 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001877 if (r == null) {
1878 return ActivityManager.COMPAT_MODE_UNKNOWN;
1879 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001880 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 }
1882 }
1883
1884 @Override
1885 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001887 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001888 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001890 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 if (r == null) {
1892 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1893 return;
1894 }
1895 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001896 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 }
1898 }
1899
1900 @Override
1901 public int getLaunchedFromUid(IBinder activityToken) {
1902 ActivityRecord srec;
1903 synchronized (mGlobalLock) {
1904 srec = ActivityRecord.forTokenLocked(activityToken);
1905 }
1906 if (srec == null) {
1907 return -1;
1908 }
1909 return srec.launchedFromUid;
1910 }
1911
1912 @Override
1913 public String getLaunchedFromPackage(IBinder activityToken) {
1914 ActivityRecord srec;
1915 synchronized (mGlobalLock) {
1916 srec = ActivityRecord.forTokenLocked(activityToken);
1917 }
1918 if (srec == null) {
1919 return null;
1920 }
1921 return srec.launchedFromPackage;
1922 }
1923
1924 @Override
1925 public boolean convertFromTranslucent(IBinder token) {
1926 final long origId = Binder.clearCallingIdentity();
1927 try {
1928 synchronized (mGlobalLock) {
1929 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1930 if (r == null) {
1931 return false;
1932 }
1933 final boolean translucentChanged = r.changeWindowTranslucency(true);
1934 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001935 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 return translucentChanged;
1939 }
1940 } finally {
1941 Binder.restoreCallingIdentity(origId);
1942 }
1943 }
1944
1945 @Override
1946 public boolean convertToTranslucent(IBinder token, Bundle options) {
1947 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1948 final long origId = Binder.clearCallingIdentity();
1949 try {
1950 synchronized (mGlobalLock) {
1951 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1952 if (r == null) {
1953 return false;
1954 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001955 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 int index = task.mActivities.lastIndexOf(r);
1957 if (index > 0) {
1958 ActivityRecord under = task.mActivities.get(index - 1);
1959 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1960 }
1961 final boolean translucentChanged = r.changeWindowTranslucency(false);
1962 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001963 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001965 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001966 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 return translucentChanged;
1968 }
1969 } finally {
1970 Binder.restoreCallingIdentity(origId);
1971 }
1972 }
1973
1974 @Override
1975 public void notifyActivityDrawn(IBinder token) {
1976 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001978 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001979 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001980 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 }
1982 }
1983 }
1984
1985 @Override
1986 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1987 synchronized (mGlobalLock) {
1988 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1989 if (r == null) {
1990 return;
1991 }
1992 r.reportFullyDrawnLocked(restoredFromBundle);
1993 }
1994 }
1995
1996 @Override
1997 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1998 synchronized (mGlobalLock) {
1999 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2000 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2001 return stack.mDisplayId;
2002 }
2003 return DEFAULT_DISPLAY;
2004 }
2005 }
2006
2007 @Override
2008 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 long ident = Binder.clearCallingIdentity();
2011 try {
2012 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002013 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002015 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 return null;
2018 }
2019 } finally {
2020 Binder.restoreCallingIdentity(ident);
2021 }
2022 }
2023
2024 @Override
2025 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002026 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2028 final long callingId = Binder.clearCallingIdentity();
2029 try {
2030 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002031 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 if (stack == null) {
2033 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2034 return;
2035 }
2036 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002037 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002038 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002039 }
2040 }
2041 } finally {
2042 Binder.restoreCallingIdentity(callingId);
2043 }
2044 }
2045
2046 @Override
2047 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002048 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2050 final long callingId = Binder.clearCallingIdentity();
2051 try {
2052 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002053 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002054 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 if (task == null) {
2056 return;
2057 }
2058 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002059 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002060 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 }
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(callingId);
2065 }
2066 }
2067
2068 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002069 public void restartActivityProcessIfVisible(IBinder activityToken) {
2070 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2071 final long callingId = Binder.clearCallingIdentity();
2072 try {
2073 synchronized (mGlobalLock) {
2074 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2075 if (r == null) {
2076 return;
2077 }
2078 r.restartProcessIfVisible();
2079 }
2080 } finally {
2081 Binder.restoreCallingIdentity(callingId);
2082 }
2083 }
2084
2085 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002087 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002088 synchronized (mGlobalLock) {
2089 final long ident = Binder.clearCallingIdentity();
2090 try {
2091 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2092 "remove-task");
2093 } finally {
2094 Binder.restoreCallingIdentity(ident);
2095 }
2096 }
2097 }
2098
2099 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002100 public void removeAllVisibleRecentTasks() {
2101 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2102 synchronized (mGlobalLock) {
2103 final long ident = Binder.clearCallingIdentity();
2104 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002105 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
2109 }
2110 }
2111
2112 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2114 synchronized (mGlobalLock) {
2115 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2116 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002117 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 }
2119 }
2120 return false;
2121 }
2122
2123 @Override
2124 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2125 Intent resultData) {
2126
2127 synchronized (mGlobalLock) {
2128 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2129 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002130 return r.getActivityStack().navigateUpToLocked(
2131 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 }
2133 return false;
2134 }
2135 }
2136
2137 /**
2138 * Attempts to move a task backwards in z-order (the order of activities within the task is
2139 * unchanged).
2140 *
2141 * There are several possible results of this call:
2142 * - if the task is locked, then we will show the lock toast
2143 * - if there is a task behind the provided task, then that task is made visible and resumed as
2144 * this task is moved to the back
2145 * - otherwise, if there are no other tasks in the stack:
2146 * - if this task is in the pinned stack, then we remove the stack completely, which will
2147 * have the effect of moving the task to the top or bottom of the fullscreen stack
2148 * (depending on whether it is visible)
2149 * - otherwise, we simply return home and hide this task
2150 *
2151 * @param token A reference to the activity we wish to move
2152 * @param nonRoot If false then this only works if the activity is the root
2153 * of a task; if true it will work for any activity in a task.
2154 * @return Returns true if the move completed, false if not.
2155 */
2156 @Override
2157 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002158 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 synchronized (mGlobalLock) {
2160 final long origId = Binder.clearCallingIdentity();
2161 try {
2162 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002163 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 if (task != null) {
2165 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2166 }
2167 } finally {
2168 Binder.restoreCallingIdentity(origId);
2169 }
2170 }
2171 return false;
2172 }
2173
2174 @Override
2175 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002176 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 long ident = Binder.clearCallingIdentity();
2178 Rect rect = new Rect();
2179 try {
2180 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002181 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2183 if (task == null) {
2184 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2185 return rect;
2186 }
2187 if (task.getStack() != null) {
2188 // Return the bounds from window manager since it will be adjusted for various
2189 // things like the presense of a docked stack for tasks that aren't resizeable.
2190 task.getWindowContainerBounds(rect);
2191 } else {
2192 // Task isn't in window manager yet since it isn't associated with a stack.
2193 // Return the persist value from activity manager
2194 if (!task.matchParentBounds()) {
2195 rect.set(task.getBounds());
2196 } else if (task.mLastNonFullscreenBounds != null) {
2197 rect.set(task.mLastNonFullscreenBounds);
2198 }
2199 }
2200 }
2201 } finally {
2202 Binder.restoreCallingIdentity(ident);
2203 }
2204 return rect;
2205 }
2206
2207 @Override
2208 public ActivityManager.TaskDescription getTaskDescription(int id) {
2209 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002212 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2214 if (tr != null) {
2215 return tr.lastTaskDescription;
2216 }
2217 }
2218 return null;
2219 }
2220
2221 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002222 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2223 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2224 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2225 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2226 return;
2227 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002229 synchronized (mGlobalLock) {
2230 final long ident = Binder.clearCallingIdentity();
2231 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002232 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002233 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002234 if (task == null) {
2235 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2236 return;
2237 }
2238
2239 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2240 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2241
2242 if (!task.isActivityTypeStandardOrUndefined()) {
2243 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2244 + " non-standard task " + taskId + " to windowing mode="
2245 + windowingMode);
2246 }
2247
2248 final ActivityStack stack = task.getStack();
2249 if (toTop) {
2250 stack.moveToFront("setTaskWindowingMode", task);
2251 }
2252 stack.setWindowingMode(windowingMode);
2253 } finally {
2254 Binder.restoreCallingIdentity(ident);
2255 }
2256 }
2257 }
2258
2259 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002260 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002261 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 ActivityRecord r = getCallingRecordLocked(token);
2263 return r != null ? r.info.packageName : null;
2264 }
2265 }
2266
2267 @Override
2268 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002269 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002270 ActivityRecord r = getCallingRecordLocked(token);
2271 return r != null ? r.intent.getComponent() : null;
2272 }
2273 }
2274
2275 private ActivityRecord getCallingRecordLocked(IBinder token) {
2276 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2277 if (r == null) {
2278 return null;
2279 }
2280 return r.resultTo;
2281 }
2282
2283 @Override
2284 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286
2287 synchronized (mGlobalLock) {
2288 final long origId = Binder.clearCallingIdentity();
2289 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002290 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 } finally {
2292 Binder.restoreCallingIdentity(origId);
2293 }
2294 }
2295 }
2296
Mark Renouf446251d2019-04-26 10:22:41 -04002297 @Override
2298 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2299 synchronized (mGlobalLock) {
2300 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2301 if (r == null) {
2302 return;
2303 }
2304 ActivityStack stack = r.getActivityStack();
2305 if (stack != null && stack.isSingleTaskInstance()) {
2306 // Single-task stacks are used for activities which are presented in floating
2307 // windows above full screen activities. Instead of directly finishing the
2308 // task, a task change listener is used to notify SystemUI so the action can be
2309 // handled specially.
2310 final TaskRecord task = r.getTaskRecord();
2311 mTaskChangeNotificationController
2312 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2313 } else {
2314 try {
2315 callback.requestFinish();
2316 } catch (RemoteException e) {
2317 Slog.e(TAG, "Failed to invoke request finish callback", e);
2318 }
2319 }
2320 }
2321 }
2322
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323 /**
2324 * TODO: Add mController hook
2325 */
2326 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002327 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2328 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002329 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002330
2331 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2332 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002333 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2334 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335 }
2336 }
2337
Ricky Waiaca8a772019-04-04 16:01:06 +01002338 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2339 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002340 boolean fromRecents) {
2341
Ricky Waiaca8a772019-04-04 16:01:06 +01002342 final int callingPid = Binder.getCallingPid();
2343 final int callingUid = Binder.getCallingUid();
2344 if (!isSameApp(callingUid, callingPackage)) {
2345 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2346 + Binder.getCallingPid() + " as package " + callingPackage;
2347 Slog.w(TAG, msg);
2348 throw new SecurityException(msg);
2349 }
2350 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 SafeActivityOptions.abort(options);
2352 return;
2353 }
2354 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 WindowProcessController callerApp = null;
2356 if (appThread != null) {
2357 callerApp = getProcessController(appThread);
2358 }
2359 final ActivityStarter starter = getActivityStartController().obtainStarter(
2360 null /* intent */, "moveTaskToFront");
2361 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2362 -1, callerApp, null, false, null)) {
2363 boolean abort = !isBackgroundActivityStartsEnabled();
2364 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2365 if (abort) {
2366 return;
2367 }
2368 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002370 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002371 if (task == null) {
2372 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002373 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 return;
2375 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002376 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002378 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379 return;
2380 }
2381 ActivityOptions realOptions = options != null
2382 ? options.getOptions(mStackSupervisor)
2383 : null;
2384 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2385 false /* forceNonResizable */);
2386
2387 final ActivityRecord topActivity = task.getTopActivity();
2388 if (topActivity != null) {
2389
2390 // We are reshowing a task, use a starting window to hide the initial draw delay
2391 // so the transition can start earlier.
2392 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2393 true /* taskSwitch */, fromRecents);
2394 }
2395 } finally {
2396 Binder.restoreCallingIdentity(origId);
2397 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 }
2399
Ricky Waiaca8a772019-04-04 16:01:06 +01002400 /**
2401 * Return true if callingUid is system, or packageName belongs to that callingUid.
2402 */
2403 boolean isSameApp(int callingUid, @Nullable String packageName) {
2404 try {
2405 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2406 if (packageName == null) {
2407 return false;
2408 }
2409 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2410 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2411 UserHandle.getUserId(callingUid));
2412 return UserHandle.isSameApp(callingUid, uid);
2413 }
2414 } catch (RemoteException e) {
2415 // Should not happen
2416 }
2417 return true;
2418 }
2419
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002420 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2421 int callingPid, int callingUid, String name) {
2422 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2423 return true;
2424 }
2425
2426 if (getRecentTasks().isCallerRecents(sourceUid)) {
2427 return true;
2428 }
2429
2430 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2431 if (perm == PackageManager.PERMISSION_GRANTED) {
2432 return true;
2433 }
2434 if (checkAllowAppSwitchUid(sourceUid)) {
2435 return true;
2436 }
2437
2438 // If the actual IPC caller is different from the logical source, then
2439 // also see if they are allowed to control app switches.
2440 if (callingUid != -1 && callingUid != sourceUid) {
2441 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2442 if (perm == PackageManager.PERMISSION_GRANTED) {
2443 return true;
2444 }
2445 if (checkAllowAppSwitchUid(callingUid)) {
2446 return true;
2447 }
2448 }
2449
2450 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2451 return false;
2452 }
2453
2454 private boolean checkAllowAppSwitchUid(int uid) {
2455 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2456 if (types != null) {
2457 for (int i = types.size() - 1; i >= 0; i--) {
2458 if (types.valueAt(i).intValue() == uid) {
2459 return true;
2460 }
2461 }
2462 }
2463 return false;
2464 }
2465
2466 @Override
2467 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2468 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2469 "setActivityController()");
2470 synchronized (mGlobalLock) {
2471 mController = controller;
2472 mControllerIsAMonkey = imAMonkey;
2473 Watchdog.getInstance().setActivityController(controller);
2474 }
2475 }
2476
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002477 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002478 synchronized (mGlobalLock) {
2479 return mController != null && mControllerIsAMonkey;
2480 }
2481 }
2482
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002483 @Override
2484 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2485 synchronized (mGlobalLock) {
2486 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2487 }
2488 }
2489
2490 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002491 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2492 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2493 }
2494
2495 @Override
2496 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2497 @WindowConfiguration.ActivityType int ignoreActivityType,
2498 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2499 final int callingUid = Binder.getCallingUid();
2500 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2501
2502 synchronized (mGlobalLock) {
2503 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2504
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002505 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002506 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002507 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 ignoreWindowingMode, callingUid, allowed);
2509 }
2510
2511 return list;
2512 }
2513
2514 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002515 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2516 synchronized (mGlobalLock) {
2517 final long origId = Binder.clearCallingIdentity();
2518 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2519 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002520 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002521 }
2522 Binder.restoreCallingIdentity(origId);
2523 }
2524 }
2525
2526 @Override
2527 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002528 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002529 ActivityStack stack = ActivityRecord.getStackLocked(token);
2530 if (stack != null) {
2531 return stack.willActivityBeVisibleLocked(token);
2532 }
2533 return false;
2534 }
2535 }
2536
2537 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002538 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002539 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002540 synchronized (mGlobalLock) {
2541 final long ident = Binder.clearCallingIdentity();
2542 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002543 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 if (task == null) {
2545 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2546 return;
2547 }
2548
2549 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2550 + " to stackId=" + stackId + " toTop=" + toTop);
2551
Wale Ogunwaled32da472018-11-16 07:19:28 -08002552 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 if (stack == null) {
2554 throw new IllegalStateException(
2555 "moveTaskToStack: No stack for stackId=" + stackId);
2556 }
2557 if (!stack.isActivityTypeStandardOrUndefined()) {
2558 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2559 + taskId + " to stack " + stackId);
2560 }
2561 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002562 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2564 }
2565 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2566 "moveTaskToStack");
2567 } finally {
2568 Binder.restoreCallingIdentity(ident);
2569 }
2570 }
2571 }
2572
2573 @Override
2574 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2575 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002576 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577
2578 final long ident = Binder.clearCallingIdentity();
2579 try {
2580 synchronized (mGlobalLock) {
2581 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002582 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002583 if (stack == null) {
2584 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2585 return;
2586 }
2587 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2588 throw new IllegalArgumentException("Stack: " + stackId
2589 + " doesn't support animated resize.");
2590 }
2591 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2592 animationDuration, false /* fromFullscreen */);
2593 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 if (stack == null) {
2596 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2597 return;
2598 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002599 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002600 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2601 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2602 }
2603 }
2604 } finally {
2605 Binder.restoreCallingIdentity(ident);
2606 }
2607 }
2608
wilsonshih5c4cf522019-01-25 09:03:47 +08002609 @Override
2610 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2611 int animationDuration) {
2612 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2613
2614 final long ident = Binder.clearCallingIdentity();
2615 try {
2616 synchronized (mGlobalLock) {
2617 if (xOffset == 0 && yOffset == 0) {
2618 return;
2619 }
2620 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2621 if (stack == null) {
2622 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2623 return;
2624 }
2625 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2626 throw new IllegalArgumentException("Stack: " + stackId
2627 + " doesn't support animated resize.");
2628 }
2629 final Rect destBounds = new Rect();
2630 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002631 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002632 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2633 return;
2634 }
2635 destBounds.offset(xOffset, yOffset);
2636 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2637 animationDuration, false /* fromFullscreen */);
2638 }
2639 } finally {
2640 Binder.restoreCallingIdentity(ident);
2641 }
2642 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002643 /**
2644 * Moves the specified task to the primary-split-screen stack.
2645 *
2646 * @param taskId Id of task to move.
2647 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2648 * exist already. See
2649 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2650 * and
2651 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2652 * @param toTop If the task and stack should be moved to the top.
2653 * @param animate Whether we should play an animation for the moving the task.
2654 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2655 * stack. Pass {@code null} to use default bounds.
2656 * @param showRecents If the recents activity should be shown on the other side of the task
2657 * going into split-screen mode.
2658 */
2659 @Override
2660 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2661 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002662 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002663 "setTaskWindowingModeSplitScreenPrimary()");
2664 synchronized (mGlobalLock) {
2665 final long ident = Binder.clearCallingIdentity();
2666 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002667 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002668 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002669 if (task == null) {
2670 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2671 return false;
2672 }
2673 if (DEBUG_STACK) Slog.d(TAG_STACK,
2674 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2675 + " to createMode=" + createMode + " toTop=" + toTop);
2676 if (!task.isActivityTypeStandardOrUndefined()) {
2677 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2678 + " non-standard task " + taskId + " to split-screen windowing mode");
2679 }
2680
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002681 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 final int windowingMode = task.getWindowingMode();
2683 final ActivityStack stack = task.getStack();
2684 if (toTop) {
2685 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2686 }
2687 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002688 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2689 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 return windowingMode != task.getWindowingMode();
2691 } finally {
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
2695 }
2696
2697 /**
2698 * Removes stacks in the input windowing modes from the system if they are of activity type
2699 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2700 */
2701 @Override
2702 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 "removeStacksInWindowingModes()");
2705
2706 synchronized (mGlobalLock) {
2707 final long ident = Binder.clearCallingIdentity();
2708 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002709 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 } finally {
2711 Binder.restoreCallingIdentity(ident);
2712 }
2713 }
2714 }
2715
2716 @Override
2717 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002718 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 "removeStacksWithActivityTypes()");
2720
2721 synchronized (mGlobalLock) {
2722 final long ident = Binder.clearCallingIdentity();
2723 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002724 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 } finally {
2726 Binder.restoreCallingIdentity(ident);
2727 }
2728 }
2729 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002730
2731 @Override
2732 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2733 int userId) {
2734 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002735 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2736 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002737 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002738 final boolean detailed = checkGetTasksPermission(
2739 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2740 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741 == PackageManager.PERMISSION_GRANTED;
2742
2743 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002744 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002745 callingUid);
2746 }
2747 }
2748
2749 @Override
2750 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 long ident = Binder.clearCallingIdentity();
2753 try {
2754 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002755 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 }
2757 } finally {
2758 Binder.restoreCallingIdentity(ident);
2759 }
2760 }
2761
2762 @Override
2763 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002764 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 long ident = Binder.clearCallingIdentity();
2766 try {
2767 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002768 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 }
2770 } finally {
2771 Binder.restoreCallingIdentity(ident);
2772 }
2773 }
2774
2775 @Override
2776 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002777 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 final long callingUid = Binder.getCallingUid();
2779 final long origId = Binder.clearCallingIdentity();
2780 try {
2781 synchronized (mGlobalLock) {
2782 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002783 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2785 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2786 }
2787 } finally {
2788 Binder.restoreCallingIdentity(origId);
2789 }
2790 }
2791
2792 @Override
2793 public void startLockTaskModeByToken(IBinder token) {
2794 synchronized (mGlobalLock) {
2795 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2796 if (r == null) {
2797 return;
2798 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002799 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002800 }
2801 }
2802
2803 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002804 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 // This makes inner call to look as if it was initiated by system.
2807 long ident = Binder.clearCallingIdentity();
2808 try {
2809 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002810 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002811 MATCH_TASK_IN_STACKS_ONLY);
2812 if (task == null) {
2813 return;
2814 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815
2816 // When starting lock task mode the stack must be in front and focused
2817 task.getStack().moveToFront("startSystemLockTaskMode");
2818 startLockTaskModeLocked(task, true /* isSystemCaller */);
2819 }
2820 } finally {
2821 Binder.restoreCallingIdentity(ident);
2822 }
2823 }
2824
2825 @Override
2826 public void stopLockTaskModeByToken(IBinder token) {
2827 synchronized (mGlobalLock) {
2828 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2829 if (r == null) {
2830 return;
2831 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002832 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 }
2834 }
2835
2836 /**
2837 * This API should be called by SystemUI only when user perform certain action to dismiss
2838 * lock task mode. We should only dismiss pinned lock task mode in this case.
2839 */
2840 @Override
2841 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002842 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2844 }
2845
2846 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2847 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2848 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2849 return;
2850 }
2851
Wale Ogunwaled32da472018-11-16 07:19:28 -08002852 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 if (stack == null || task != stack.topTask()) {
2854 throw new IllegalArgumentException("Invalid task, not in foreground");
2855 }
2856
2857 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2858 // system or a specific app.
2859 // * System-initiated requests will only start the pinned mode (screen pinning)
2860 // * App-initiated requests
2861 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2862 // - will start the pinned mode, otherwise
2863 final int callingUid = Binder.getCallingUid();
2864 long ident = Binder.clearCallingIdentity();
2865 try {
2866 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002867 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002869 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870 } finally {
2871 Binder.restoreCallingIdentity(ident);
2872 }
2873 }
2874
2875 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2876 final int callingUid = Binder.getCallingUid();
2877 long ident = Binder.clearCallingIdentity();
2878 try {
2879 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002880 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 }
2882 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2883 // task and jumping straight into a call in the case of emergency call back.
2884 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2885 if (tm != null) {
2886 tm.showInCallScreen(false);
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(ident);
2890 }
2891 }
2892
2893 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002894 public void updateLockTaskPackages(int userId, String[] packages) {
2895 final int callingUid = Binder.getCallingUid();
2896 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2897 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2898 "updateLockTaskPackages()");
2899 }
2900 synchronized (this) {
2901 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2902 + Arrays.toString(packages));
2903 getLockTaskController().updateLockTaskPackages(userId, packages);
2904 }
2905 }
2906
2907 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002908 public boolean isInLockTaskMode() {
2909 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2910 }
2911
2912 @Override
2913 public int getLockTaskModeState() {
2914 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002915 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 }
2917 }
2918
2919 @Override
2920 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2921 synchronized (mGlobalLock) {
2922 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2923 if (r != null) {
2924 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002925 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002927 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002928 }
2929 }
2930 }
2931
2932 @Override
2933 public Bundle getActivityOptions(IBinder token) {
2934 final long origId = Binder.clearCallingIdentity();
2935 try {
2936 synchronized (mGlobalLock) {
2937 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2938 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002939 final ActivityOptions activityOptions = r.takeOptionsLocked(
2940 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 return activityOptions == null ? null : activityOptions.toBundle();
2942 }
2943 return null;
2944 }
2945 } finally {
2946 Binder.restoreCallingIdentity(origId);
2947 }
2948 }
2949
2950 @Override
2951 public List<IBinder> getAppTasks(String callingPackage) {
2952 int callingUid = Binder.getCallingUid();
2953 long ident = Binder.clearCallingIdentity();
2954 try {
2955 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002956 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 }
2958 } finally {
2959 Binder.restoreCallingIdentity(ident);
2960 }
2961 }
2962
2963 @Override
2964 public void finishVoiceTask(IVoiceInteractionSession session) {
2965 synchronized (mGlobalLock) {
2966 final long origId = Binder.clearCallingIdentity();
2967 try {
2968 // TODO: VI Consider treating local voice interactions and voice tasks
2969 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002970 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 } finally {
2972 Binder.restoreCallingIdentity(origId);
2973 }
2974 }
2975
2976 }
2977
2978 @Override
2979 public boolean isTopOfTask(IBinder token) {
2980 synchronized (mGlobalLock) {
2981 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002982 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983 }
2984 }
2985
2986 @Override
2987 public void notifyLaunchTaskBehindComplete(IBinder token) {
2988 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2989 }
2990
2991 @Override
2992 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002993 mH.post(() -> {
2994 synchronized (mGlobalLock) {
2995 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002996 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002997 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002998 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002999 } catch (RemoteException e) {
3000 }
3001 }
3002 }
3003
3004 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 }
3006
3007 /** Called from an app when assist data is ready. */
3008 @Override
3009 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3010 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003011 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003012 synchronized (pae) {
3013 pae.result = extras;
3014 pae.structure = structure;
3015 pae.content = content;
3016 if (referrer != null) {
3017 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3018 }
3019 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003020 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003021 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3022 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 structure.setHomeActivity(pae.isHome);
3024 }
3025 pae.haveResult = true;
3026 pae.notifyAll();
3027 if (pae.intent == null && pae.receiver == null) {
3028 // Caller is just waiting for the result.
3029 return;
3030 }
3031 }
3032 // We are now ready to launch the assist activity.
3033 IAssistDataReceiver sendReceiver = null;
3034 Bundle sendBundle = null;
3035 synchronized (mGlobalLock) {
3036 buildAssistBundleLocked(pae, extras);
3037 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003038 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 if (!exists) {
3040 // Timed out.
3041 return;
3042 }
3043
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003044 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 // Caller wants result sent back to them.
3046 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003047 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3048 pae.activity.getTaskRecord().taskId);
3049 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3050 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3052 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3053 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3054 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3055 }
3056 }
3057 if (sendReceiver != null) {
3058 try {
3059 sendReceiver.onHandleAssistData(sendBundle);
3060 } catch (RemoteException e) {
3061 }
3062 return;
3063 }
3064
3065 final long ident = Binder.clearCallingIdentity();
3066 try {
3067 if (TextUtils.equals(pae.intent.getAction(),
3068 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3069 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003070
3071 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 } else {
3073 pae.intent.replaceExtras(pae.extras);
3074 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3075 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3076 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003077 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078
3079 try {
3080 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3081 } catch (ActivityNotFoundException e) {
3082 Slog.w(TAG, "No activity to handle assist action.", e);
3083 }
3084 }
3085 } finally {
3086 Binder.restoreCallingIdentity(ident);
3087 }
3088 }
3089
Marvin Ramin830d4e32019-03-12 13:16:58 +01003090 /**
3091 * Workaround for historical API which starts the Assist service with a non-foreground
3092 * {@code startService()} call.
3093 */
3094 private void startVoiceInteractionServiceAsUser(
3095 Intent intent, int userHandle, String reason) {
3096 // Resolve the intent to find out which package we need to whitelist.
3097 ResolveInfo resolveInfo =
3098 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3099 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3100 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3101 return;
3102 }
3103 intent.setPackage(resolveInfo.serviceInfo.packageName);
3104
3105 // Whitelist background services temporarily.
3106 LocalServices.getService(DeviceIdleController.LocalService.class)
3107 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3108 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3109
3110 // Finally, try to start the service.
3111 try {
3112 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3113 } catch (RuntimeException e) {
3114 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3115 }
3116 }
3117
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 @Override
3119 public int addAppTask(IBinder activityToken, Intent intent,
3120 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3121 final int callingUid = Binder.getCallingUid();
3122 final long callingIdent = Binder.clearCallingIdentity();
3123
3124 try {
3125 synchronized (mGlobalLock) {
3126 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3127 if (r == null) {
3128 throw new IllegalArgumentException("Activity does not exist; token="
3129 + activityToken);
3130 }
3131 ComponentName comp = intent.getComponent();
3132 if (comp == null) {
3133 throw new IllegalArgumentException("Intent " + intent
3134 + " must specify explicit component");
3135 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003136 if (thumbnail.getWidth() != mThumbnailWidth
3137 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 throw new IllegalArgumentException("Bad thumbnail size: got "
3139 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003140 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141 }
3142 if (intent.getSelector() != null) {
3143 intent.setSelector(null);
3144 }
3145 if (intent.getSourceBounds() != null) {
3146 intent.setSourceBounds(null);
3147 }
3148 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3149 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3150 // The caller has added this as an auto-remove task... that makes no
3151 // sense, so turn off auto-remove.
3152 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3153 }
3154 }
3155 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3156 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3157 if (ainfo.applicationInfo.uid != callingUid) {
3158 throw new SecurityException(
3159 "Can't add task for another application: target uid="
3160 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3161 }
3162
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003163 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003165 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003167 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 // The app has too many tasks already and we can't add any more
3169 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3170 return INVALID_TASK_ID;
3171 }
3172 task.lastTaskDescription.copyFrom(description);
3173
3174 // TODO: Send the thumbnail to WM to store it.
3175
3176 return task.taskId;
3177 }
3178 } finally {
3179 Binder.restoreCallingIdentity(callingIdent);
3180 }
3181 }
3182
3183 @Override
3184 public Point getAppTaskThumbnailSize() {
3185 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 }
3188 }
3189
3190 @Override
3191 public void setTaskResizeable(int taskId, int resizeableMode) {
3192 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003193 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3195 if (task == null) {
3196 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3197 return;
3198 }
3199 task.setResizeMode(resizeableMode);
3200 }
3201 }
3202
3203 @Override
3204 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003205 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 long ident = Binder.clearCallingIdentity();
3207 try {
3208 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003209 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003210 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 if (task == null) {
3212 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3213 return;
3214 }
3215 // Place the task in the right stack if it isn't there already based on
3216 // the requested bounds.
3217 // The stack transition logic is:
3218 // - a null bounds on a freeform task moves that task to fullscreen
3219 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3220 // that task to freeform
3221 // - otherwise the task is not moved
3222 ActivityStack stack = task.getStack();
3223 if (!task.getWindowConfiguration().canResizeTask()) {
3224 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3225 }
3226 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3227 stack = stack.getDisplay().getOrCreateStack(
3228 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3229 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3230 stack = stack.getDisplay().getOrCreateStack(
3231 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3232 }
3233
3234 // Reparent the task to the right stack if necessary
3235 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3236 if (stack != task.getStack()) {
3237 // Defer resume until the task is resized below
3238 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3239 DEFER_RESUME, "resizeTask");
3240 preserveWindow = false;
3241 }
3242
3243 // After reparenting (which only resizes the task to the stack bounds), resize the
3244 // task to the actual bounds provided
3245 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3246 }
3247 } finally {
3248 Binder.restoreCallingIdentity(ident);
3249 }
3250 }
3251
3252 @Override
3253 public boolean releaseActivityInstance(IBinder token) {
3254 synchronized (mGlobalLock) {
3255 final long origId = Binder.clearCallingIdentity();
3256 try {
3257 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3258 if (r == null) {
3259 return false;
3260 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003261 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 } finally {
3263 Binder.restoreCallingIdentity(origId);
3264 }
3265 }
3266 }
3267
3268 @Override
3269 public void releaseSomeActivities(IApplicationThread appInt) {
3270 synchronized (mGlobalLock) {
3271 final long origId = Binder.clearCallingIdentity();
3272 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003273 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003274 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 } finally {
3276 Binder.restoreCallingIdentity(origId);
3277 }
3278 }
3279 }
3280
3281 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003282 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003283 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 != PackageManager.PERMISSION_GRANTED) {
3285 throw new SecurityException("Requires permission "
3286 + android.Manifest.permission.DEVICE_POWER);
3287 }
3288
3289 synchronized (mGlobalLock) {
3290 long ident = Binder.clearCallingIdentity();
3291 if (mKeyguardShown != keyguardShowing) {
3292 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003293 final Message msg = PooledLambda.obtainMessage(
3294 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3295 keyguardShowing);
3296 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 }
3298 try {
wilsonshih177261f2019-02-22 12:02:18 +08003299 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003300 } finally {
3301 Binder.restoreCallingIdentity(ident);
3302 }
3303 }
3304
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003305 mH.post(() -> {
3306 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3307 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3308 }
3309 });
3310 }
3311
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003312 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003313 mH.post(() -> {
3314 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3315 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3316 }
3317 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 }
3319
3320 @Override
3321 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003322 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3323 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324
3325 final File passedIconFile = new File(filePath);
3326 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3327 passedIconFile.getName());
3328 if (!legitIconFile.getPath().equals(filePath)
3329 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3330 throw new IllegalArgumentException("Bad file path: " + filePath
3331 + " passed for userId " + userId);
3332 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003333 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 }
3335
3336 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003337 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003338 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3339 final ActivityOptions activityOptions = safeOptions != null
3340 ? safeOptions.getOptions(mStackSupervisor)
3341 : null;
3342 if (activityOptions == null
3343 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3344 || activityOptions.getCustomInPlaceResId() == 0) {
3345 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3346 "with valid animation");
3347 }
lumark588a3e82018-07-20 18:53:54 +08003348 // Get top display of front most application.
3349 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3350 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003351 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3352 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3353 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003354 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003355 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003356 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 }
3358
3359 @Override
3360 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 synchronized (mGlobalLock) {
3363 final long ident = Binder.clearCallingIdentity();
3364 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003365 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 if (stack == null) {
3367 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3368 return;
3369 }
3370 if (!stack.isActivityTypeStandardOrUndefined()) {
3371 throw new IllegalArgumentException(
3372 "Removing non-standard stack is not allowed.");
3373 }
3374 mStackSupervisor.removeStack(stack);
3375 } finally {
3376 Binder.restoreCallingIdentity(ident);
3377 }
3378 }
3379 }
3380
3381 @Override
3382 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384
3385 synchronized (mGlobalLock) {
3386 final long ident = Binder.clearCallingIdentity();
3387 try {
3388 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3389 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003390 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 } finally {
3392 Binder.restoreCallingIdentity(ident);
3393 }
3394 }
3395 }
3396
3397 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003398 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 synchronized (mGlobalLock) {
3400 long ident = Binder.clearCallingIdentity();
3401 try {
3402 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3403 if (r == null) {
3404 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003405 "toggleFreeformWindowingMode: No activity record matching token="
3406 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003407 }
3408
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003409 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003410 if (stack == null) {
3411 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3412 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 }
3414
Yunfan Chend967af82019-01-17 18:30:18 +09003415 if (!stack.inFreeformWindowingMode()
3416 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3417 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3418 + "toggle between fullscreen and freeform.");
3419 }
3420
3421 if (stack.inFreeformWindowingMode()) {
3422 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003423 } else if (stack.getParent().inFreeformWindowingMode()) {
3424 // If the window is on a freeform display, set it to undefined. It will be
3425 // resolved to freeform and it can adjust windowing mode when the display mode
3426 // changes in runtime.
3427 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003428 } else {
3429 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3430 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 } finally {
3432 Binder.restoreCallingIdentity(ident);
3433 }
3434 }
3435 }
3436
3437 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3438 @Override
3439 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003440 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003441 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003442 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 }
3444
3445 /** Unregister a task stack listener so that it stops receiving callbacks. */
3446 @Override
3447 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003448 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003450 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 }
3452
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003453 @Override
3454 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3455 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3456 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3457 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3458 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3459 }
3460
3461 @Override
3462 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3463 IBinder activityToken, int flags) {
3464 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3465 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3466 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3467 }
3468
3469 @Override
3470 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3471 Bundle args) {
3472 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3473 true /* focused */, true /* newSessionId */, userHandle, args,
3474 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3475 }
3476
3477 @Override
3478 public Bundle getAssistContextExtras(int requestType) {
3479 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3480 null, null, true /* focused */, true /* newSessionId */,
3481 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3482 if (pae == null) {
3483 return null;
3484 }
3485 synchronized (pae) {
3486 while (!pae.haveResult) {
3487 try {
3488 pae.wait();
3489 } catch (InterruptedException e) {
3490 }
3491 }
3492 }
3493 synchronized (mGlobalLock) {
3494 buildAssistBundleLocked(pae, pae.result);
3495 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003496 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 }
3498 return pae.extras;
3499 }
3500
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003501 /**
3502 * Binder IPC calls go through the public entry point.
3503 * This can be called with or without the global lock held.
3504 */
3505 private static int checkCallingPermission(String permission) {
3506 return checkPermission(
3507 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3508 }
3509
3510 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003511 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003512 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3513 mAmInternal.enforceCallingPermission(permission, func);
3514 }
3515 }
3516
3517 @VisibleForTesting
3518 int checkGetTasksPermission(String permission, int pid, int uid) {
3519 return checkPermission(permission, pid, uid);
3520 }
3521
3522 static int checkPermission(String permission, int pid, int uid) {
3523 if (permission == null) {
3524 return PackageManager.PERMISSION_DENIED;
3525 }
3526 return checkComponentPermission(permission, pid, uid, -1, true);
3527 }
3528
Wale Ogunwale214f3482018-10-04 11:00:47 -07003529 public static int checkComponentPermission(String permission, int pid, int uid,
3530 int owningUid, boolean exported) {
3531 return ActivityManagerService.checkComponentPermission(
3532 permission, pid, uid, owningUid, exported);
3533 }
3534
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003535 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3536 if (getRecentTasks().isCallerRecents(callingUid)) {
3537 // Always allow the recents component to get tasks
3538 return true;
3539 }
3540
3541 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3542 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3543 if (!allowed) {
3544 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3545 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3546 // Temporary compatibility: some existing apps on the system image may
3547 // still be requesting the old permission and not switched to the new
3548 // one; if so, we'll still allow them full access. This means we need
3549 // to see if they are holding the old permission and are a system app.
3550 try {
3551 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3552 allowed = true;
3553 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3554 + " is using old GET_TASKS but privileged; allowing");
3555 }
3556 } catch (RemoteException e) {
3557 }
3558 }
3559 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3560 + " does not hold REAL_GET_TASKS; limiting output");
3561 }
3562 return allowed;
3563 }
3564
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003565 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3566 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3567 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3568 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003569 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003570 "enqueueAssistContext()");
3571
3572 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003573 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 if (activity == null) {
3575 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3576 return null;
3577 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003578 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3580 return null;
3581 }
3582 if (focused) {
3583 if (activityToken != null) {
3584 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3585 if (activity != caller) {
3586 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3587 + " is not current top " + activity);
3588 return null;
3589 }
3590 }
3591 } else {
3592 activity = ActivityRecord.forTokenLocked(activityToken);
3593 if (activity == null) {
3594 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3595 + " couldn't be found");
3596 return null;
3597 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003598 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3600 return null;
3601 }
3602 }
3603
3604 PendingAssistExtras pae;
3605 Bundle extras = new Bundle();
3606 if (args != null) {
3607 extras.putAll(args);
3608 }
3609 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003610 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611
3612 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3613 userHandle);
3614 pae.isHome = activity.isActivityTypeHome();
3615
3616 // Increment the sessionId if necessary
3617 if (newSessionId) {
3618 mViSessionId++;
3619 }
3620 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003621 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3622 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003623 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003624 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 } catch (RemoteException e) {
3626 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3627 return null;
3628 }
3629 return pae;
3630 }
3631 }
3632
3633 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3634 if (result != null) {
3635 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3636 }
3637 if (pae.hint != null) {
3638 pae.extras.putBoolean(pae.hint, true);
3639 }
3640 }
3641
3642 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3643 IAssistDataReceiver receiver;
3644 synchronized (mGlobalLock) {
3645 mPendingAssistExtras.remove(pae);
3646 receiver = pae.receiver;
3647 }
3648 if (receiver != null) {
3649 // Caller wants result sent back to them.
3650 Bundle sendBundle = new Bundle();
3651 // At least return the receiver extras
3652 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3653 try {
3654 pae.receiver.onHandleAssistData(sendBundle);
3655 } catch (RemoteException e) {
3656 }
3657 }
3658 }
3659
3660 public class PendingAssistExtras extends Binder implements Runnable {
3661 public final ActivityRecord activity;
3662 public boolean isHome;
3663 public final Bundle extras;
3664 public final Intent intent;
3665 public final String hint;
3666 public final IAssistDataReceiver receiver;
3667 public final int userHandle;
3668 public boolean haveResult = false;
3669 public Bundle result = null;
3670 public AssistStructure structure = null;
3671 public AssistContent content = null;
3672 public Bundle receiverExtras;
3673
3674 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3675 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3676 int _userHandle) {
3677 activity = _activity;
3678 extras = _extras;
3679 intent = _intent;
3680 hint = _hint;
3681 receiver = _receiver;
3682 receiverExtras = _receiverExtras;
3683 userHandle = _userHandle;
3684 }
3685
3686 @Override
3687 public void run() {
3688 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3689 synchronized (this) {
3690 haveResult = true;
3691 notifyAll();
3692 }
3693 pendingAssistExtrasTimedOut(this);
3694 }
3695 }
3696
3697 @Override
3698 public boolean isAssistDataAllowedOnCurrentActivity() {
3699 int userId;
3700 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003701 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003702 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3703 return false;
3704 }
3705
3706 final ActivityRecord activity = focusedStack.getTopActivity();
3707 if (activity == null) {
3708 return false;
3709 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003710 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 }
3712 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3713 }
3714
3715 @Override
3716 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3717 long ident = Binder.clearCallingIdentity();
3718 try {
3719 synchronized (mGlobalLock) {
3720 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003721 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722 if (top != caller) {
3723 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3724 + " is not current top " + top);
3725 return false;
3726 }
3727 if (!top.nowVisible) {
3728 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3729 + " is not visible");
3730 return false;
3731 }
3732 }
3733 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3734 token);
3735 } finally {
3736 Binder.restoreCallingIdentity(ident);
3737 }
3738 }
3739
3740 @Override
3741 public boolean isRootVoiceInteraction(IBinder token) {
3742 synchronized (mGlobalLock) {
3743 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3744 if (r == null) {
3745 return false;
3746 }
3747 return r.rootVoiceInteraction;
3748 }
3749 }
3750
Wale Ogunwalef6733932018-06-27 05:14:34 -07003751 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3752 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3753 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3754 if (activityToCallback == null) return;
3755 activityToCallback.setVoiceSessionLocked(voiceSession);
3756
3757 // Inform the activity
3758 try {
3759 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3760 voiceInteractor);
3761 long token = Binder.clearCallingIdentity();
3762 try {
3763 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3764 } finally {
3765 Binder.restoreCallingIdentity(token);
3766 }
3767 // TODO: VI Should we cache the activity so that it's easier to find later
3768 // rather than scan through all the stacks and activities?
3769 } catch (RemoteException re) {
3770 activityToCallback.clearVoiceSessionLocked();
3771 // TODO: VI Should this terminate the voice session?
3772 }
3773 }
3774
3775 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3776 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3777 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3778 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3779 boolean wasRunningVoice = mRunningVoice != null;
3780 mRunningVoice = session;
3781 if (!wasRunningVoice) {
3782 mVoiceWakeLock.acquire();
3783 updateSleepIfNeededLocked();
3784 }
3785 }
3786 }
3787
3788 void finishRunningVoiceLocked() {
3789 if (mRunningVoice != null) {
3790 mRunningVoice = null;
3791 mVoiceWakeLock.release();
3792 updateSleepIfNeededLocked();
3793 }
3794 }
3795
3796 @Override
3797 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3798 synchronized (mGlobalLock) {
3799 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3800 if (keepAwake) {
3801 mVoiceWakeLock.acquire();
3802 } else {
3803 mVoiceWakeLock.release();
3804 }
3805 }
3806 }
3807 }
3808
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003809 @Override
3810 public ComponentName getActivityClassForToken(IBinder token) {
3811 synchronized (mGlobalLock) {
3812 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3813 if (r == null) {
3814 return null;
3815 }
3816 return r.intent.getComponent();
3817 }
3818 }
3819
3820 @Override
3821 public String getPackageForToken(IBinder token) {
3822 synchronized (mGlobalLock) {
3823 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3824 if (r == null) {
3825 return null;
3826 }
3827 return r.packageName;
3828 }
3829 }
3830
3831 @Override
3832 public void showLockTaskEscapeMessage(IBinder token) {
3833 synchronized (mGlobalLock) {
3834 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3835 if (r == null) {
3836 return;
3837 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003838 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 }
3840 }
3841
3842 @Override
3843 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003844 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003845 final long token = Binder.clearCallingIdentity();
3846 try {
3847 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003848 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003849 }
3850 } finally {
3851 Binder.restoreCallingIdentity(token);
3852 }
3853 }
3854
3855 /**
3856 * Try to place task to provided position. The final position might be different depending on
3857 * current user and stacks state. The task will be moved to target stack if it's currently in
3858 * different stack.
3859 */
3860 @Override
3861 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003862 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003863 synchronized (mGlobalLock) {
3864 long ident = Binder.clearCallingIdentity();
3865 try {
3866 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3867 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003868 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003869 if (task == null) {
3870 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3871 + taskId);
3872 }
3873
Wale Ogunwaled32da472018-11-16 07:19:28 -08003874 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875
3876 if (stack == null) {
3877 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3878 + stackId);
3879 }
3880 if (!stack.isActivityTypeStandardOrUndefined()) {
3881 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3882 + " the position of task " + taskId + " in/to non-standard stack");
3883 }
3884
3885 // TODO: Have the callers of this API call a separate reparent method if that is
3886 // what they intended to do vs. having this method also do reparenting.
3887 if (task.getStack() == stack) {
3888 // Change position in current stack.
3889 stack.positionChildAt(task, position);
3890 } else {
3891 // Reparent to new stack.
3892 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3893 !DEFER_RESUME, "positionTaskInStack");
3894 }
3895 } finally {
3896 Binder.restoreCallingIdentity(ident);
3897 }
3898 }
3899 }
3900
3901 @Override
3902 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3903 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3904 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3905 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3906 synchronized (mGlobalLock) {
3907 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3908 if (record == null) {
3909 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3910 + "found for: " + token);
3911 }
3912 record.setSizeConfigurations(horizontalSizeConfiguration,
3913 verticalSizeConfigurations, smallestSizeConfigurations);
3914 }
3915 }
3916
3917 /**
3918 * Dismisses split-screen multi-window mode.
3919 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3920 */
3921 @Override
3922 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003923 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3925 final long ident = Binder.clearCallingIdentity();
3926 try {
3927 synchronized (mGlobalLock) {
3928 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003929 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 if (stack == null) {
3931 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3932 return;
3933 }
3934
3935 if (toTop) {
3936 // Caller wants the current split-screen primary stack to be the top stack after
3937 // it goes fullscreen, so move it to the front.
3938 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003939 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 // In this case the current split-screen primary stack shouldn't be the top
3941 // stack after it goes fullscreen, but it current has focus, so we move the
3942 // focus to the top-most split-screen secondary stack next to it.
3943 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3944 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3945 if (otherStack != null) {
3946 otherStack.moveToFront("dismissSplitScreenMode_other");
3947 }
3948 }
3949
Evan Rosky10475742018-09-05 19:02:48 -07003950 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 }
3952 } finally {
3953 Binder.restoreCallingIdentity(ident);
3954 }
3955 }
3956
3957 /**
3958 * Dismisses Pip
3959 * @param animate True if the dismissal should be animated.
3960 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3961 * default animation duration should be used.
3962 */
3963 @Override
3964 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003965 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 final long ident = Binder.clearCallingIdentity();
3967 try {
3968 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003969 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003970 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 if (stack == null) {
3972 Slog.w(TAG, "dismissPip: pinned stack not found.");
3973 return;
3974 }
3975 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3976 throw new IllegalArgumentException("Stack: " + stack
3977 + " doesn't support animated resize.");
3978 }
3979 if (animate) {
3980 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3981 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3982 } else {
3983 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3984 }
3985 }
3986 } finally {
3987 Binder.restoreCallingIdentity(ident);
3988 }
3989 }
3990
3991 @Override
3992 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003993 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003994 synchronized (mGlobalLock) {
3995 mSuppressResizeConfigChanges = suppress;
3996 }
3997 }
3998
3999 /**
4000 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4001 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4002 * activity and clearing the task at the same time.
4003 */
4004 @Override
4005 // TODO: API should just be about changing windowing modes...
4006 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 "moveTasksToFullscreenStack()");
4009 synchronized (mGlobalLock) {
4010 final long origId = Binder.clearCallingIdentity();
4011 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004012 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 if (stack != null){
4014 if (!stack.isActivityTypeStandardOrUndefined()) {
4015 throw new IllegalArgumentException(
4016 "You can't move tasks from non-standard stacks.");
4017 }
4018 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4019 }
4020 } finally {
4021 Binder.restoreCallingIdentity(origId);
4022 }
4023 }
4024 }
4025
4026 /**
4027 * Moves the top activity in the input stackId to the pinned stack.
4028 *
4029 * @param stackId Id of stack to move the top activity to pinned stack.
4030 * @param bounds Bounds to use for pinned stack.
4031 *
4032 * @return True if the top activity of the input stack was successfully moved to the pinned
4033 * stack.
4034 */
4035 @Override
4036 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 "moveTopActivityToPinnedStack()");
4039 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004040 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4042 + "Device doesn't support picture-in-picture mode");
4043 }
4044
4045 long ident = Binder.clearCallingIdentity();
4046 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004047 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004048 } finally {
4049 Binder.restoreCallingIdentity(ident);
4050 }
4051 }
4052 }
4053
4054 @Override
4055 public boolean isInMultiWindowMode(IBinder token) {
4056 final long origId = Binder.clearCallingIdentity();
4057 try {
4058 synchronized (mGlobalLock) {
4059 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4060 if (r == null) {
4061 return false;
4062 }
4063 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4064 return r.inMultiWindowMode();
4065 }
4066 } finally {
4067 Binder.restoreCallingIdentity(origId);
4068 }
4069 }
4070
4071 @Override
4072 public boolean isInPictureInPictureMode(IBinder token) {
4073 final long origId = Binder.clearCallingIdentity();
4074 try {
4075 synchronized (mGlobalLock) {
4076 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4077 }
4078 } finally {
4079 Binder.restoreCallingIdentity(origId);
4080 }
4081 }
4082
4083 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004084 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4085 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 return false;
4087 }
4088
4089 // If we are animating to fullscreen then we have already dispatched the PIP mode
4090 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004091 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4092 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093 }
4094
4095 @Override
4096 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4097 final long origId = Binder.clearCallingIdentity();
4098 try {
4099 synchronized (mGlobalLock) {
4100 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4101 "enterPictureInPictureMode", token, params);
4102
4103 // If the activity is already in picture in picture mode, then just return early
4104 if (isInPictureInPictureMode(r)) {
4105 return true;
4106 }
4107
4108 // Activity supports picture-in-picture, now check that we can enter PiP at this
4109 // point, if it is
4110 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4111 false /* beforeStopping */)) {
4112 return false;
4113 }
4114
4115 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004116 synchronized (mGlobalLock) {
4117 // Only update the saved args from the args that are set
4118 r.pictureInPictureArgs.copyOnlySet(params);
4119 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4120 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4121 // Adjust the source bounds by the insets for the transition down
4122 final Rect sourceBounds = new Rect(
4123 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004124 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004125 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004126 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004127 stack.setPictureInPictureAspectRatio(aspectRatio);
4128 stack.setPictureInPictureActions(actions);
4129 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4130 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4131 logPictureInPictureArgs(params);
4132 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 };
4134
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004135 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004136 // If the keyguard is showing or occluded, then try and dismiss it before
4137 // entering picture-in-picture (this will prompt the user to authenticate if the
4138 // device is currently locked).
4139 dismissKeyguard(token, new KeyguardDismissCallback() {
4140 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004141 public void onDismissSucceeded() {
4142 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 }
4144 }, null /* message */);
4145 } else {
4146 // Enter picture in picture immediately otherwise
4147 enterPipRunnable.run();
4148 }
4149 return true;
4150 }
4151 } finally {
4152 Binder.restoreCallingIdentity(origId);
4153 }
4154 }
4155
4156 @Override
4157 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4158 final long origId = Binder.clearCallingIdentity();
4159 try {
4160 synchronized (mGlobalLock) {
4161 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4162 "setPictureInPictureParams", token, params);
4163
4164 // Only update the saved args from the args that are set
4165 r.pictureInPictureArgs.copyOnlySet(params);
4166 if (r.inPinnedWindowingMode()) {
4167 // If the activity is already in picture-in-picture, update the pinned stack now
4168 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4169 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004170 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004171 if (!stack.isAnimatingBoundsToFullscreen()) {
4172 stack.setPictureInPictureAspectRatio(
4173 r.pictureInPictureArgs.getAspectRatio());
4174 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4175 }
4176 }
4177 logPictureInPictureArgs(params);
4178 }
4179 } finally {
4180 Binder.restoreCallingIdentity(origId);
4181 }
4182 }
4183
4184 @Override
4185 public int getMaxNumPictureInPictureActions(IBinder token) {
4186 // Currently, this is a static constant, but later, we may change this to be dependent on
4187 // the context of the activity
4188 return 3;
4189 }
4190
4191 private void logPictureInPictureArgs(PictureInPictureParams params) {
4192 if (params.hasSetActions()) {
4193 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4194 params.getActions().size());
4195 }
4196 if (params.hasSetAspectRatio()) {
4197 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4198 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4199 MetricsLogger.action(lm);
4200 }
4201 }
4202
4203 /**
4204 * Checks the state of the system and the activity associated with the given {@param token} to
4205 * verify that picture-in-picture is supported for that activity.
4206 *
4207 * @return the activity record for the given {@param token} if all the checks pass.
4208 */
4209 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4210 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004211 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 throw new IllegalStateException(caller
4213 + ": Device doesn't support picture-in-picture mode.");
4214 }
4215
4216 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4217 if (r == null) {
4218 throw new IllegalStateException(caller
4219 + ": Can't find activity for token=" + token);
4220 }
4221
4222 if (!r.supportsPictureInPicture()) {
4223 throw new IllegalStateException(caller
4224 + ": Current activity does not support picture-in-picture.");
4225 }
4226
4227 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004228 && !mWindowManager.isValidPictureInPictureAspectRatio(
4229 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 final float minAspectRatio = mContext.getResources().getFloat(
4231 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4232 final float maxAspectRatio = mContext.getResources().getFloat(
4233 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4234 throw new IllegalArgumentException(String.format(caller
4235 + ": Aspect ratio is too extreme (must be between %f and %f).",
4236 minAspectRatio, maxAspectRatio));
4237 }
4238
4239 // Truncate the number of actions if necessary
4240 params.truncateActions(getMaxNumPictureInPictureActions(token));
4241
4242 return r;
4243 }
4244
4245 @Override
4246 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 synchronized (mGlobalLock) {
4249 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4250 if (r == null) {
4251 throw new IllegalArgumentException("Activity does not exist; token="
4252 + activityToken);
4253 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004254 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004255 }
4256 }
4257
4258 @Override
4259 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4260 Rect tempDockedTaskInsetBounds,
4261 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 long ident = Binder.clearCallingIdentity();
4264 try {
4265 synchronized (mGlobalLock) {
4266 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4267 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4268 PRESERVE_WINDOWS);
4269 }
4270 } finally {
4271 Binder.restoreCallingIdentity(ident);
4272 }
4273 }
4274
4275 @Override
4276 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004277 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004278 final long ident = Binder.clearCallingIdentity();
4279 try {
4280 synchronized (mGlobalLock) {
4281 mStackSupervisor.setSplitScreenResizing(resizing);
4282 }
4283 } finally {
4284 Binder.restoreCallingIdentity(ident);
4285 }
4286 }
4287
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004288 /**
4289 * Check that we have the features required for VR-related API calls, and throw an exception if
4290 * not.
4291 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004292 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 if (!mContext.getPackageManager().hasSystemFeature(
4294 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4295 throw new UnsupportedOperationException("VR mode not supported on this device!");
4296 }
4297 }
4298
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 @Override
4300 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004301 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302
4303 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4304
4305 ActivityRecord r;
4306 synchronized (mGlobalLock) {
4307 r = ActivityRecord.isInStackLocked(token);
4308 }
4309
4310 if (r == null) {
4311 throw new IllegalArgumentException();
4312 }
4313
4314 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004315 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 VrManagerInternal.NO_ERROR) {
4317 return err;
4318 }
4319
4320 // Clear the binder calling uid since this path may call moveToTask().
4321 final long callingId = Binder.clearCallingIdentity();
4322 try {
4323 synchronized (mGlobalLock) {
4324 r.requestedVrComponent = (enabled) ? packageName : null;
4325
4326 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004327 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004328 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 }
4330 return 0;
4331 }
4332 } finally {
4333 Binder.restoreCallingIdentity(callingId);
4334 }
4335 }
4336
4337 @Override
4338 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4339 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4340 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004341 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4343 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4344 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004345 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 || activity.voiceSession != null) {
4347 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4348 return;
4349 }
4350 if (activity.pendingVoiceInteractionStart) {
4351 Slog.w(TAG, "Pending start of voice interaction already.");
4352 return;
4353 }
4354 activity.pendingVoiceInteractionStart = true;
4355 }
4356 LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .startLocalVoiceInteraction(callingActivity, options);
4358 }
4359
4360 @Override
4361 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4362 LocalServices.getService(VoiceInteractionManagerInternal.class)
4363 .stopLocalVoiceInteraction(callingActivity);
4364 }
4365
4366 @Override
4367 public boolean supportsLocalVoiceInteraction() {
4368 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4369 .supportsLocalVoiceInteraction();
4370 }
4371
4372 /** Notifies all listeners when the pinned stack animation starts. */
4373 @Override
4374 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004375 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 }
4377
4378 /** Notifies all listeners when the pinned stack animation ends. */
4379 @Override
4380 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004381 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382 }
4383
4384 @Override
4385 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 final long ident = Binder.clearCallingIdentity();
4388 try {
4389 synchronized (mGlobalLock) {
4390 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4391 }
4392 } finally {
4393 Binder.restoreCallingIdentity(ident);
4394 }
4395 }
4396
4397 @Override
4398 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004399 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004400
4401 synchronized (mGlobalLock) {
4402 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004403 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 // Call might come when display is not yet added or has already been removed.
4405 if (DEBUG_CONFIGURATION) {
4406 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4407 + displayId);
4408 }
4409 return false;
4410 }
4411
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 }
4416
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004417 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004418 final Message msg = PooledLambda.obtainMessage(
4419 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4420 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 }
4422
4423 final long origId = Binder.clearCallingIdentity();
4424 try {
4425 if (values != null) {
4426 Settings.System.clearConfiguration(values);
4427 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004428 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4430 return mTmpUpdateConfigurationResult.changes != 0;
4431 } finally {
4432 Binder.restoreCallingIdentity(origId);
4433 }
4434 }
4435 }
4436
4437 @Override
4438 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440
4441 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 }
4446
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004448 final Message msg = PooledLambda.obtainMessage(
4449 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4450 DEFAULT_DISPLAY);
4451 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 }
4453
4454 final long origId = Binder.clearCallingIdentity();
4455 try {
4456 if (values != null) {
4457 Settings.System.clearConfiguration(values);
4458 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004459 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 UserHandle.USER_NULL, false /* deferResume */,
4461 mTmpUpdateConfigurationResult);
4462 return mTmpUpdateConfigurationResult.changes != 0;
4463 } finally {
4464 Binder.restoreCallingIdentity(origId);
4465 }
4466 }
4467 }
4468
4469 @Override
4470 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4471 CharSequence message) {
4472 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4475 }
4476 final long callingId = Binder.clearCallingIdentity();
4477 try {
4478 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004479 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 }
4481 } finally {
4482 Binder.restoreCallingIdentity(callingId);
4483 }
4484 }
4485
4486 @Override
4487 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004488 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 "cancelTaskWindowTransition()");
4490 final long ident = Binder.clearCallingIdentity();
4491 try {
4492 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004493 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 MATCH_TASK_IN_STACKS_ONLY);
4495 if (task == null) {
4496 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4497 return;
4498 }
4499 task.cancelWindowTransition();
4500 }
4501 } finally {
4502 Binder.restoreCallingIdentity(ident);
4503 }
4504 }
4505
4506 @Override
4507 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 final long ident = Binder.clearCallingIdentity();
4510 try {
4511 final TaskRecord task;
4512 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004513 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004514 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4515 if (task == null) {
4516 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4517 return null;
4518 }
4519 }
4520 // Don't call this while holding the lock as this operation might hit the disk.
4521 return task.getSnapshot(reducedResolution);
4522 } finally {
4523 Binder.restoreCallingIdentity(ident);
4524 }
4525 }
4526
4527 @Override
4528 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4529 synchronized (mGlobalLock) {
4530 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4531 if (r == null) {
4532 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4533 + token);
4534 return;
4535 }
4536 final long origId = Binder.clearCallingIdentity();
4537 try {
4538 r.setDisablePreviewScreenshots(disable);
4539 } finally {
4540 Binder.restoreCallingIdentity(origId);
4541 }
4542 }
4543 }
4544
4545 /** Return the user id of the last resumed activity. */
4546 @Override
4547 public @UserIdInt
4548 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004549 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004550 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4551 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004552 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004553 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004555 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 }
4557 }
4558
4559 @Override
4560 public void updateLockTaskFeatures(int userId, int flags) {
4561 final int callingUid = Binder.getCallingUid();
4562 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004563 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 "updateLockTaskFeatures()");
4565 }
4566 synchronized (mGlobalLock) {
4567 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4568 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004569 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004570 }
4571 }
4572
4573 @Override
4574 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4575 synchronized (mGlobalLock) {
4576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4577 if (r == null) {
4578 return;
4579 }
4580 final long origId = Binder.clearCallingIdentity();
4581 try {
4582 r.setShowWhenLocked(showWhenLocked);
4583 } finally {
4584 Binder.restoreCallingIdentity(origId);
4585 }
4586 }
4587 }
4588
4589 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004590 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4591 synchronized (mGlobalLock) {
4592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4593 if (r == null) {
4594 return;
4595 }
4596 final long origId = Binder.clearCallingIdentity();
4597 try {
4598 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4599 } finally {
4600 Binder.restoreCallingIdentity(origId);
4601 }
4602 }
4603 }
4604
4605 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004606 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4607 synchronized (mGlobalLock) {
4608 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4609 if (r == null) {
4610 return;
4611 }
4612 final long origId = Binder.clearCallingIdentity();
4613 try {
4614 r.setTurnScreenOn(turnScreenOn);
4615 } finally {
4616 Binder.restoreCallingIdentity(origId);
4617 }
4618 }
4619 }
4620
4621 @Override
4622 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004623 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004624 "registerRemoteAnimations");
4625 definition.setCallingPid(Binder.getCallingPid());
4626 synchronized (mGlobalLock) {
4627 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4628 if (r == null) {
4629 return;
4630 }
4631 final long origId = Binder.clearCallingIdentity();
4632 try {
4633 r.registerRemoteAnimations(definition);
4634 } finally {
4635 Binder.restoreCallingIdentity(origId);
4636 }
4637 }
4638 }
4639
4640 @Override
4641 public void registerRemoteAnimationForNextActivityStart(String packageName,
4642 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004643 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 "registerRemoteAnimationForNextActivityStart");
4645 adapter.setCallingPid(Binder.getCallingPid());
4646 synchronized (mGlobalLock) {
4647 final long origId = Binder.clearCallingIdentity();
4648 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004649 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004650 packageName, adapter);
4651 } finally {
4652 Binder.restoreCallingIdentity(origId);
4653 }
4654 }
4655 }
4656
Evan Rosky966759f2019-01-15 10:33:58 -08004657 @Override
4658 public void registerRemoteAnimationsForDisplay(int displayId,
4659 RemoteAnimationDefinition definition) {
4660 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4661 "registerRemoteAnimations");
4662 definition.setCallingPid(Binder.getCallingPid());
4663 synchronized (mGlobalLock) {
4664 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4665 if (display == null) {
4666 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4667 return;
4668 }
4669 final long origId = Binder.clearCallingIdentity();
4670 try {
4671 display.mDisplayContent.registerRemoteAnimations(definition);
4672 } finally {
4673 Binder.restoreCallingIdentity(origId);
4674 }
4675 }
4676 }
4677
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004678 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4679 @Override
4680 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4681 synchronized (mGlobalLock) {
4682 final long origId = Binder.clearCallingIdentity();
4683 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004684 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004685 } finally {
4686 Binder.restoreCallingIdentity(origId);
4687 }
4688 }
4689 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004690
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004691 @Override
4692 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004693 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004694 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004695 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004696 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004697 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 }
4699 }
4700
4701 @Override
4702 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004703 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004704 != PERMISSION_GRANTED) {
4705 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4706 + Binder.getCallingPid()
4707 + ", uid=" + Binder.getCallingUid()
4708 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4709 Slog.w(TAG, msg);
4710 throw new SecurityException(msg);
4711 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004712 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004714 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004715 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004716 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004717 }
4718 }
4719
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004720 @Override
4721 public void stopAppSwitches() {
4722 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4723 synchronized (mGlobalLock) {
4724 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4725 mDidAppSwitch = false;
4726 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4727 }
4728 }
4729
4730 @Override
4731 public void resumeAppSwitches() {
4732 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4733 synchronized (mGlobalLock) {
4734 // Note that we don't execute any pending app switches... we will
4735 // let those wait until either the timeout, or the next start
4736 // activity request.
4737 mAppSwitchesAllowedTime = 0;
4738 }
4739 }
4740
4741 void onStartActivitySetDidAppSwitch() {
4742 if (mDidAppSwitch) {
4743 // This is the second allowed switch since we stopped switches, so now just generally
4744 // allow switches. Use case:
4745 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4746 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4747 // anyone to switch again).
4748 mAppSwitchesAllowedTime = 0;
4749 } else {
4750 mDidAppSwitch = true;
4751 }
4752 }
4753
4754 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004755 boolean shouldDisableNonVrUiLocked() {
4756 return mVrController.shouldDisableNonVrUiLocked();
4757 }
4758
Wale Ogunwale53783742018-09-16 10:21:51 -07004759 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004760 // VR apps are expected to run in a main display. If an app is turning on VR for
4761 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4762 // fullscreen stack before enabling VR Mode.
4763 // TODO: The goal of this code is to keep the VR app on the main display. When the
4764 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4765 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4766 // option would be a better choice here.
4767 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4768 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4769 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004770 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004771 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004772 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004773 }
4774 mH.post(() -> {
4775 if (!mVrController.onVrModeChanged(r)) {
4776 return;
4777 }
4778 synchronized (mGlobalLock) {
4779 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4780 mWindowManager.disableNonVrUi(disableNonVrUi);
4781 if (disableNonVrUi) {
4782 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4783 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004784 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 }
4786 }
4787 });
4788 }
4789
Wale Ogunwale53783742018-09-16 10:21:51 -07004790 @Override
4791 public int getPackageScreenCompatMode(String packageName) {
4792 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4793 synchronized (mGlobalLock) {
4794 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4795 }
4796 }
4797
4798 @Override
4799 public void setPackageScreenCompatMode(String packageName, int mode) {
4800 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4801 "setPackageScreenCompatMode");
4802 synchronized (mGlobalLock) {
4803 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4804 }
4805 }
4806
4807 @Override
4808 public boolean getPackageAskScreenCompat(String packageName) {
4809 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4810 synchronized (mGlobalLock) {
4811 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4812 }
4813 }
4814
4815 @Override
4816 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4817 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4818 "setPackageAskScreenCompat");
4819 synchronized (mGlobalLock) {
4820 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4821 }
4822 }
4823
Wale Ogunwale64258362018-10-16 15:13:37 -07004824 public static String relaunchReasonToString(int relaunchReason) {
4825 switch (relaunchReason) {
4826 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4827 return "window_resize";
4828 case RELAUNCH_REASON_FREE_RESIZE:
4829 return "free_resize";
4830 default:
4831 return null;
4832 }
4833 }
4834
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004835 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004836 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004837 }
4838
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004839 /** Pokes the task persister. */
4840 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4841 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4842 }
4843
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004844 boolean isKeyguardLocked() {
4845 return mKeyguardController.isKeyguardLocked();
4846 }
4847
Garfield Tan01548632018-11-27 10:15:48 -08004848 /**
4849 * Clears launch params for the given package.
4850 * @param packageNames the names of the packages of which the launch params are to be cleared
4851 */
4852 @Override
4853 public void clearLaunchParamsForPackages(List<String> packageNames) {
4854 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4855 "clearLaunchParamsForPackages");
4856 synchronized (mGlobalLock) {
4857 for (int i = 0; i < packageNames.size(); ++i) {
4858 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4859 }
4860 }
4861 }
4862
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004863 /**
4864 * Makes the display with the given id a single task instance display. I.e the display can only
4865 * contain one task.
4866 */
4867 @Override
4868 public void setDisplayToSingleTaskInstance(int displayId) {
4869 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4870 "setDisplayToSingleTaskInstance");
4871 final long origId = Binder.clearCallingIdentity();
4872 try {
4873 final ActivityDisplay display =
4874 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4875 if (display != null) {
4876 display.setDisplayToSingleTaskInstance();
4877 }
4878 } finally {
4879 Binder.restoreCallingIdentity(origId);
4880 }
4881 }
4882
Wale Ogunwale31913b52018-10-13 08:29:31 -07004883 void dumpLastANRLocked(PrintWriter pw) {
4884 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4885 if (mLastANRState == null) {
4886 pw.println(" <no ANR has occurred since boot>");
4887 } else {
4888 pw.println(mLastANRState);
4889 }
4890 }
4891
4892 void dumpLastANRTracesLocked(PrintWriter pw) {
4893 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4894
4895 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4896 if (ArrayUtils.isEmpty(files)) {
4897 pw.println(" <no ANR has occurred since boot>");
4898 return;
4899 }
4900 // Find the latest file.
4901 File latest = null;
4902 for (File f : files) {
4903 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4904 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004905 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004906 }
4907 pw.print("File: ");
4908 pw.print(latest.getName());
4909 pw.println();
4910 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4911 String line;
4912 while ((line = in.readLine()) != null) {
4913 pw.println(line);
4914 }
4915 } catch (IOException e) {
4916 pw.print("Unable to read: ");
4917 pw.print(e);
4918 pw.println();
4919 }
4920 }
4921
4922 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4923 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4924 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4925 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4926 }
4927
4928 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4929 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4930 pw.println(header);
4931
Wale Ogunwaled32da472018-11-16 07:19:28 -08004932 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004933 dumpPackage);
4934 boolean needSep = printedAnything;
4935
4936 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004937 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004938 " ResumedActivity: ");
4939 if (printed) {
4940 printedAnything = true;
4941 needSep = false;
4942 }
4943
4944 if (dumpPackage == null) {
4945 if (needSep) {
4946 pw.println();
4947 }
4948 printedAnything = true;
4949 mStackSupervisor.dump(pw, " ");
4950 }
4951
4952 if (!printedAnything) {
4953 pw.println(" (nothing)");
4954 }
4955 }
4956
4957 void dumpActivityContainersLocked(PrintWriter pw) {
4958 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004959 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004960 pw.println(" ");
4961 }
4962
4963 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4964 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4965 getActivityStartController().dump(pw, "", dumpPackage);
4966 }
4967
4968 /**
4969 * There are three things that cmd can be:
4970 * - a flattened component name that matches an existing activity
4971 * - the cmd arg isn't the flattened component name of an existing activity:
4972 * dump all activity whose component contains the cmd as a substring
4973 * - A hex number of the ActivityRecord object instance.
4974 *
4975 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4976 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4977 */
4978 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4979 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4980 ArrayList<ActivityRecord> activities;
4981
4982 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004983 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004984 dumpFocusedStackOnly);
4985 }
4986
4987 if (activities.size() <= 0) {
4988 return false;
4989 }
4990
4991 String[] newArgs = new String[args.length - opti];
4992 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4993
4994 TaskRecord lastTask = null;
4995 boolean needSep = false;
4996 for (int i = activities.size() - 1; i >= 0; i--) {
4997 ActivityRecord r = activities.get(i);
4998 if (needSep) {
4999 pw.println();
5000 }
5001 needSep = true;
5002 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005003 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005004 if (lastTask != task) {
5005 lastTask = task;
5006 pw.print("TASK "); pw.print(lastTask.affinity);
5007 pw.print(" id="); pw.print(lastTask.taskId);
5008 pw.print(" userId="); pw.println(lastTask.userId);
5009 if (dumpAll) {
5010 lastTask.dump(pw, " ");
5011 }
5012 }
5013 }
5014 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5015 }
5016 return true;
5017 }
5018
5019 /**
5020 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5021 * there is a thread associated with the activity.
5022 */
5023 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5024 final ActivityRecord r, String[] args, boolean dumpAll) {
5025 String innerPrefix = prefix + " ";
5026 synchronized (mGlobalLock) {
5027 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5028 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5029 pw.print(" pid=");
5030 if (r.hasProcess()) pw.println(r.app.getPid());
5031 else pw.println("(not running)");
5032 if (dumpAll) {
5033 r.dump(pw, innerPrefix);
5034 }
5035 }
5036 if (r.attachedToProcess()) {
5037 // flush anything that is already in the PrintWriter since the thread is going
5038 // to write to the file descriptor directly
5039 pw.flush();
5040 try {
5041 TransferPipe tp = new TransferPipe();
5042 try {
5043 r.app.getThread().dumpActivity(tp.getWriteFd(),
5044 r.appToken, innerPrefix, args);
5045 tp.go(fd);
5046 } finally {
5047 tp.kill();
5048 }
5049 } catch (IOException e) {
5050 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5051 } catch (RemoteException e) {
5052 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5053 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005054 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005055 }
5056
sanryhuang498e77e2018-12-06 14:57:01 +08005057 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5058 boolean testPssMode) {
5059 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5060 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5061 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005062 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005063 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5064 st.toString());
5065 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005066 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5067 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5068 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005069 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5070 testPssMode);
5071 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005072 }
5073
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005074 int getCurrentUserId() {
5075 return mAmInternal.getCurrentUserId();
5076 }
5077
5078 private void enforceNotIsolatedCaller(String caller) {
5079 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5080 throw new SecurityException("Isolated process not allowed to call " + caller);
5081 }
5082 }
5083
Wale Ogunwalef6733932018-06-27 05:14:34 -07005084 public Configuration getConfiguration() {
5085 Configuration ci;
5086 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005087 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005088 ci.userSetLocale = false;
5089 }
5090 return ci;
5091 }
5092
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005093 /**
5094 * Current global configuration information. Contains general settings for the entire system,
5095 * also corresponds to the merged configuration of the default display.
5096 */
5097 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005098 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005099 }
5100
5101 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5102 boolean initLocale) {
5103 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5104 }
5105
5106 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5107 boolean initLocale, boolean deferResume) {
5108 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5109 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5110 UserHandle.USER_NULL, deferResume);
5111 }
5112
Wale Ogunwale59507092018-10-29 09:00:30 -07005113 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005114 final long origId = Binder.clearCallingIdentity();
5115 try {
5116 synchronized (mGlobalLock) {
5117 updateConfigurationLocked(values, null, false, true, userId,
5118 false /* deferResume */);
5119 }
5120 } finally {
5121 Binder.restoreCallingIdentity(origId);
5122 }
5123 }
5124
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005125 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5126 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5127 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5128 deferResume, null /* result */);
5129 }
5130
5131 /**
5132 * Do either or both things: (1) change the current configuration, and (2)
5133 * make sure the given activity is running with the (now) current
5134 * configuration. Returns true if the activity has been left running, or
5135 * false if <var>starting</var> is being destroyed to match the new
5136 * configuration.
5137 *
5138 * @param userId is only used when persistent parameter is set to true to persist configuration
5139 * for that particular user
5140 */
5141 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5142 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5143 ActivityTaskManagerService.UpdateConfigurationResult result) {
5144 int changes = 0;
5145 boolean kept = true;
5146
5147 if (mWindowManager != null) {
5148 mWindowManager.deferSurfaceLayout();
5149 }
5150 try {
5151 if (values != null) {
5152 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5153 deferResume);
5154 }
5155
5156 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5157 } finally {
5158 if (mWindowManager != null) {
5159 mWindowManager.continueSurfaceLayout();
5160 }
5161 }
5162
5163 if (result != null) {
5164 result.changes = changes;
5165 result.activityRelaunched = !kept;
5166 }
5167 return kept;
5168 }
5169
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005170 /** Update default (global) configuration and notify listeners about changes. */
5171 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5172 boolean persistent, int userId, boolean deferResume) {
5173 mTempConfig.setTo(getGlobalConfiguration());
5174 final int changes = mTempConfig.updateFrom(values);
5175 if (changes == 0) {
5176 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5177 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5178 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5179 // (even if there are no actual changes) to unfreeze the window.
5180 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5181 return 0;
5182 }
5183
5184 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5185 "Updating global configuration to: " + values);
5186
5187 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5188 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5189 values.colorMode,
5190 values.densityDpi,
5191 values.fontScale,
5192 values.hardKeyboardHidden,
5193 values.keyboard,
5194 values.keyboardHidden,
5195 values.mcc,
5196 values.mnc,
5197 values.navigation,
5198 values.navigationHidden,
5199 values.orientation,
5200 values.screenHeightDp,
5201 values.screenLayout,
5202 values.screenWidthDp,
5203 values.smallestScreenWidthDp,
5204 values.touchscreen,
5205 values.uiMode);
5206
5207
5208 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5209 final LocaleList locales = values.getLocales();
5210 int bestLocaleIndex = 0;
5211 if (locales.size() > 1) {
5212 if (mSupportedSystemLocales == null) {
5213 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5214 }
5215 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5216 }
5217 SystemProperties.set("persist.sys.locale",
5218 locales.get(bestLocaleIndex).toLanguageTag());
5219 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005220
5221 final Message m = PooledLambda.obtainMessage(
5222 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5223 locales.get(bestLocaleIndex));
5224 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
5226
Yunfan Chen75157d72018-07-27 14:47:21 +09005227 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228
5229 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005230 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231
5232 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5233 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005234 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235
5236 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005237 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238
5239 AttributeCache ac = AttributeCache.instance();
5240 if (ac != null) {
5241 ac.updateConfiguration(mTempConfig);
5242 }
5243
5244 // Make sure all resources in our process are updated right now, so that anyone who is going
5245 // to retrieve resource values after we return will be sure to get the new ones. This is
5246 // especially important during boot, where the first config change needs to guarantee all
5247 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005248 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249
5250 // We need another copy of global config because we're scheduling some calls instead of
5251 // running them in place. We need to be sure that object we send will be handled unchanged.
5252 final Configuration configCopy = new Configuration(mTempConfig);
5253 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005254 final Message msg = PooledLambda.obtainMessage(
5255 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5256 this, userId, configCopy);
5257 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258 }
5259
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005260 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5261 for (int i = pidMap.size() - 1; i >= 0; i--) {
5262 final int pid = pidMap.keyAt(i);
5263 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005264 if (DEBUG_CONFIGURATION) {
5265 Slog.v(TAG_CONFIGURATION, "Update process config of "
5266 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005267 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005268 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269 }
5270
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005271 final Message msg = PooledLambda.obtainMessage(
5272 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5273 mAmInternal, changes, initLocale);
5274 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005275
5276 // Override configuration of the default display duplicates global config, so we need to
5277 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005278 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005279 DEFAULT_DISPLAY);
5280
5281 return changes;
5282 }
5283
5284 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5285 boolean deferResume, int displayId) {
5286 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5287 displayId, null /* result */);
5288 }
5289
5290 /**
5291 * Updates override configuration specific for the selected display. If no config is provided,
5292 * new one will be computed in WM based on current display info.
5293 */
5294 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5295 ActivityRecord starting, boolean deferResume, int displayId,
5296 ActivityTaskManagerService.UpdateConfigurationResult result) {
5297 int changes = 0;
5298 boolean kept = true;
5299
5300 if (mWindowManager != null) {
5301 mWindowManager.deferSurfaceLayout();
5302 }
5303 try {
5304 if (values != null) {
5305 if (displayId == DEFAULT_DISPLAY) {
5306 // Override configuration of the default display duplicates global config, so
5307 // we're calling global config update instead for default display. It will also
5308 // apply the correct override config.
5309 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5310 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5311 } else {
5312 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5313 }
5314 }
5315
5316 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5317 } finally {
5318 if (mWindowManager != null) {
5319 mWindowManager.continueSurfaceLayout();
5320 }
5321 }
5322
5323 if (result != null) {
5324 result.changes = changes;
5325 result.activityRelaunched = !kept;
5326 }
5327 return kept;
5328 }
5329
5330 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5331 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005332 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333 final int changes = mTempConfig.updateFrom(values);
5334 if (changes != 0) {
5335 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5336 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005337 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005338
5339 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5340 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005341 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342
Wale Ogunwale5c918702018-10-18 11:06:33 -07005343 // Post message to start process to avoid possible deadlock of calling into AMS with
5344 // the ATMS lock held.
5345 final Message msg = PooledLambda.obtainMessage(
5346 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005347 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005348 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005349 }
5350 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351 return changes;
5352 }
5353
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 private void updateEventDispatchingLocked(boolean booted) {
5355 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5356 }
5357
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005358 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5359 final ContentResolver resolver = mContext.getContentResolver();
5360 Settings.System.putConfigurationForUser(resolver, config, userId);
5361 }
5362
5363 private void sendLocaleToMountDaemonMsg(Locale l) {
5364 try {
5365 IBinder service = ServiceManager.getService("mount");
5366 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5367 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5368 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5369 } catch (RemoteException e) {
5370 Log.e(TAG, "Error storing locale for decryption UI", e);
5371 }
5372 }
5373
Alison Cichowlas3e340502018-08-07 17:15:01 -04005374 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5375 mStartActivitySources.remove(permissionToken);
5376 mExpiredStartAsCallerTokens.add(permissionToken);
5377 }
5378
5379 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5380 mExpiredStartAsCallerTokens.remove(permissionToken);
5381 }
5382
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005383 boolean isActivityStartsLoggingEnabled() {
5384 return mAmInternal.isActivityStartsLoggingEnabled();
5385 }
5386
Michal Karpinski8596ded2018-11-14 14:43:48 +00005387 boolean isBackgroundActivityStartsEnabled() {
5388 return mAmInternal.isBackgroundActivityStartsEnabled();
5389 }
5390
Ricky Waiaca8a772019-04-04 16:01:06 +01005391 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5392 if (packageName == null) {
5393 return false;
5394 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005395 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5396 }
5397
Wale Ogunwalef6733932018-06-27 05:14:34 -07005398 void enableScreenAfterBoot(boolean booted) {
5399 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5400 SystemClock.uptimeMillis());
5401 mWindowManager.enableScreenAfterBoot();
5402
5403 synchronized (mGlobalLock) {
5404 updateEventDispatchingLocked(booted);
5405 }
5406 }
5407
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005408 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5409 if (r == null || !r.hasProcess()) {
5410 return KEY_DISPATCHING_TIMEOUT_MS;
5411 }
5412 return getInputDispatchingTimeoutLocked(r.app);
5413 }
5414
5415 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005416 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005417 }
5418
Wale Ogunwalef6733932018-06-27 05:14:34 -07005419 /**
5420 * Decide based on the configuration whether we should show the ANR,
5421 * crash, etc dialogs. The idea is that if there is no affordance to
5422 * press the on-screen buttons, or the user experience would be more
5423 * greatly impacted than the crash itself, we shouldn't show the dialog.
5424 *
5425 * A thought: SystemUI might also want to get told about this, the Power
5426 * dialog / global actions also might want different behaviors.
5427 */
5428 private void updateShouldShowDialogsLocked(Configuration config) {
5429 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5430 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5431 && config.navigation == Configuration.NAVIGATION_NONAV);
5432 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5433 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5434 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5435 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5436 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5437 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5438 HIDE_ERROR_DIALOGS, 0) != 0;
5439 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5440 }
5441
5442 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5443 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5444 FONT_SCALE, 1.0f, userId);
5445
5446 synchronized (this) {
5447 if (getGlobalConfiguration().fontScale == scaleFactor) {
5448 return;
5449 }
5450
5451 final Configuration configuration
5452 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5453 configuration.fontScale = scaleFactor;
5454 updatePersistentConfiguration(configuration, userId);
5455 }
5456 }
5457
5458 // Actually is sleeping or shutting down or whatever else in the future
5459 // is an inactive state.
5460 boolean isSleepingOrShuttingDownLocked() {
5461 return isSleepingLocked() || mShuttingDown;
5462 }
5463
5464 boolean isSleepingLocked() {
5465 return mSleeping;
5466 }
5467
Riddle Hsu16567132018-08-16 21:37:47 +08005468 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005470 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005471 if (task.isActivityTypeStandard()) {
5472 if (mCurAppTimeTracker != r.appTimeTracker) {
5473 // We are switching app tracking. Complete the current one.
5474 if (mCurAppTimeTracker != null) {
5475 mCurAppTimeTracker.stop();
5476 mH.obtainMessage(
5477 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005478 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479 mCurAppTimeTracker = null;
5480 }
5481 if (r.appTimeTracker != null) {
5482 mCurAppTimeTracker = r.appTimeTracker;
5483 startTimeTrackingFocusedActivityLocked();
5484 }
5485 } else {
5486 startTimeTrackingFocusedActivityLocked();
5487 }
5488 } else {
5489 r.appTimeTracker = null;
5490 }
5491 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5492 // TODO: Probably not, because we don't want to resume voice on switching
5493 // back to this activity
5494 if (task.voiceInteractor != null) {
5495 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5496 } else {
5497 finishRunningVoiceLocked();
5498
5499 if (mLastResumedActivity != null) {
5500 final IVoiceInteractionSession session;
5501
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005502 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 if (lastResumedActivityTask != null
5504 && lastResumedActivityTask.voiceSession != null) {
5505 session = lastResumedActivityTask.voiceSession;
5506 } else {
5507 session = mLastResumedActivity.voiceSession;
5508 }
5509
5510 if (session != null) {
5511 // We had been in a voice interaction session, but now focused has
5512 // move to something different. Just finish the session, we can't
5513 // return to it and retain the proper state and synchronization with
5514 // the voice interaction service.
5515 finishVoiceTask(session);
5516 }
5517 }
5518 }
5519
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005520 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5521 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522 }
5523 updateResumedAppTrace(r);
5524 mLastResumedActivity = r;
5525
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005526 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527
5528 applyUpdateLockStateLocked(r);
5529 applyUpdateVrModeLocked(r);
5530
5531 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005532 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005533 r == null ? "NULL" : r.shortComponentName,
5534 reason);
5535 }
5536
5537 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5538 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005539 final ActivityTaskManagerInternal.SleepToken token =
5540 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541 updateSleepIfNeededLocked();
5542 return token;
5543 }
5544 }
5545
5546 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005547 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 final boolean wasSleeping = mSleeping;
5549 boolean updateOomAdj = false;
5550
5551 if (!shouldSleep) {
5552 // If wasSleeping is true, we need to wake up activity manager state from when
5553 // we started sleeping. In either case, we need to apply the sleep tokens, which
5554 // will wake up stacks or put them to sleep as appropriate.
5555 if (wasSleeping) {
5556 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005557 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5558 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 startTimeTrackingFocusedActivityLocked();
5560 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005561 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005562 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5563 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005564 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005565 if (wasSleeping) {
5566 updateOomAdj = true;
5567 }
5568 } else if (!mSleeping && shouldSleep) {
5569 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005570 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5571 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 if (mCurAppTimeTracker != null) {
5573 mCurAppTimeTracker.stop();
5574 }
5575 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005576 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005577 mStackSupervisor.goingToSleepLocked();
5578 updateResumedAppTrace(null /* resumed */);
5579 updateOomAdj = true;
5580 }
5581 if (updateOomAdj) {
5582 mH.post(mAmInternal::updateOomAdj);
5583 }
5584 }
5585
5586 void updateOomAdj() {
5587 mH.post(mAmInternal::updateOomAdj);
5588 }
5589
Wale Ogunwale53783742018-09-16 10:21:51 -07005590 void updateCpuStats() {
5591 mH.post(mAmInternal::updateCpuStats);
5592 }
5593
Hui Yu03d12402018-12-06 18:00:37 -08005594 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5595 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005596 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5597 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005598 mH.sendMessage(m);
5599 }
5600
Hui Yu03d12402018-12-06 18:00:37 -08005601 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005602 ComponentName taskRoot = null;
5603 final TaskRecord task = activity.getTaskRecord();
5604 if (task != null) {
5605 final ActivityRecord rootActivity = task.getRootActivity();
5606 if (rootActivity != null) {
5607 taskRoot = rootActivity.mActivityComponent;
5608 }
5609 }
5610
Hui Yu03d12402018-12-06 18:00:37 -08005611 final Message m = PooledLambda.obtainMessage(
5612 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005613 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005614 mH.sendMessage(m);
5615 }
5616
Wale Ogunwale53783742018-09-16 10:21:51 -07005617 void setBooting(boolean booting) {
5618 mAmInternal.setBooting(booting);
5619 }
5620
5621 boolean isBooting() {
5622 return mAmInternal.isBooting();
5623 }
5624
5625 void setBooted(boolean booted) {
5626 mAmInternal.setBooted(booted);
5627 }
5628
5629 boolean isBooted() {
5630 return mAmInternal.isBooted();
5631 }
5632
5633 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5634 mH.post(() -> {
5635 if (finishBooting) {
5636 mAmInternal.finishBooting();
5637 }
5638 if (enableScreen) {
5639 mInternal.enableScreenAfterBoot(isBooted());
5640 }
5641 });
5642 }
5643
5644 void setHeavyWeightProcess(ActivityRecord root) {
5645 mHeavyWeightProcess = root.app;
5646 final Message m = PooledLambda.obtainMessage(
5647 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005648 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005649 mH.sendMessage(m);
5650 }
5651
5652 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5653 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5654 return;
5655 }
5656
5657 mHeavyWeightProcess = null;
5658 final Message m = PooledLambda.obtainMessage(
5659 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5660 proc.mUserId);
5661 mH.sendMessage(m);
5662 }
5663
5664 private void cancelHeavyWeightProcessNotification(int userId) {
5665 final INotificationManager inm = NotificationManager.getService();
5666 if (inm == null) {
5667 return;
5668 }
5669 try {
5670 inm.cancelNotificationWithTag("android", null,
5671 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5672 } catch (RuntimeException e) {
5673 Slog.w(TAG, "Error canceling notification for service", e);
5674 } catch (RemoteException e) {
5675 }
5676
5677 }
5678
5679 private void postHeavyWeightProcessNotification(
5680 WindowProcessController proc, Intent intent, int userId) {
5681 if (proc == null) {
5682 return;
5683 }
5684
5685 final INotificationManager inm = NotificationManager.getService();
5686 if (inm == null) {
5687 return;
5688 }
5689
5690 try {
5691 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5692 String text = mContext.getString(R.string.heavy_weight_notification,
5693 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5694 Notification notification =
5695 new Notification.Builder(context,
5696 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5697 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5698 .setWhen(0)
5699 .setOngoing(true)
5700 .setTicker(text)
5701 .setColor(mContext.getColor(
5702 com.android.internal.R.color.system_notification_accent_color))
5703 .setContentTitle(text)
5704 .setContentText(
5705 mContext.getText(R.string.heavy_weight_notification_detail))
5706 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5707 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5708 new UserHandle(userId)))
5709 .build();
5710 try {
5711 inm.enqueueNotificationWithTag("android", "android", null,
5712 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5713 } catch (RuntimeException e) {
5714 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5715 } catch (RemoteException e) {
5716 }
5717 } catch (PackageManager.NameNotFoundException e) {
5718 Slog.w(TAG, "Unable to create context for heavy notification", e);
5719 }
5720
5721 }
5722
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005723 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5724 IBinder token, String resultWho, int requestCode, Intent[] intents,
5725 String[] resolvedTypes, int flags, Bundle bOptions) {
5726
5727 ActivityRecord activity = null;
5728 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5729 activity = ActivityRecord.isInStackLocked(token);
5730 if (activity == null) {
5731 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5732 return null;
5733 }
5734 if (activity.finishing) {
5735 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5736 return null;
5737 }
5738 }
5739
5740 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5741 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5742 bOptions);
5743 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5744 if (noCreate) {
5745 return rec;
5746 }
5747 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5748 if (activity.pendingResults == null) {
5749 activity.pendingResults = new HashSet<>();
5750 }
5751 activity.pendingResults.add(rec.ref);
5752 }
5753 return rec;
5754 }
5755
Andrii Kulian52d255c2018-07-13 11:32:19 -07005756 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005757 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005758 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005759 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5760 mCurAppTimeTracker.start(resumedActivity.packageName);
5761 }
5762 }
5763
5764 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5765 if (mTracedResumedActivity != null) {
5766 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5767 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5768 }
5769 if (resumed != null) {
5770 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5771 constructResumedTraceName(resumed.packageName), 0);
5772 }
5773 mTracedResumedActivity = resumed;
5774 }
5775
5776 private String constructResumedTraceName(String packageName) {
5777 return "focused app: " + packageName;
5778 }
5779
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005780 /** Applies latest configuration and/or visibility updates if needed. */
5781 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5782 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005783 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005784 // mainStack is null during startup.
5785 if (mainStack != null) {
5786 if (changes != 0 && starting == null) {
5787 // If the configuration changed, and the caller is not already
5788 // in the process of starting an activity, then find the top
5789 // activity to check if its configuration needs to change.
5790 starting = mainStack.topRunningActivityLocked();
5791 }
5792
5793 if (starting != null) {
5794 kept = starting.ensureActivityConfiguration(changes,
5795 false /* preserveWindow */);
5796 // And we need to make sure at this point that all other activities
5797 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005798 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005799 !PRESERVE_WINDOWS);
5800 }
5801 }
5802
5803 return kept;
5804 }
5805
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005806 void scheduleAppGcsLocked() {
5807 mH.post(() -> mAmInternal.scheduleAppGcs());
5808 }
5809
Wale Ogunwale53783742018-09-16 10:21:51 -07005810 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5811 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5812 }
5813
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005814 /**
5815 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5816 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5817 * on demand.
5818 */
5819 IPackageManager getPackageManager() {
5820 return AppGlobals.getPackageManager();
5821 }
5822
5823 PackageManagerInternal getPackageManagerInternalLocked() {
5824 if (mPmInternal == null) {
5825 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5826 }
5827 return mPmInternal;
5828 }
5829
Hai Zhangf4da9be2019-05-01 13:46:06 +08005830 PermissionPolicyInternal getPermissionPolicyInternal() {
5831 if (mPermissionPolicyInternal == null) {
5832 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5833 }
5834 return mPermissionPolicyInternal;
5835 }
5836
Wale Ogunwale008163e2018-07-23 23:11:08 -07005837 AppWarnings getAppWarningsLocked() {
5838 return mAppWarnings;
5839 }
5840
Wale Ogunwale214f3482018-10-04 11:00:47 -07005841 Intent getHomeIntent() {
5842 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5843 intent.setComponent(mTopComponent);
5844 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5845 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5846 intent.addCategory(Intent.CATEGORY_HOME);
5847 }
5848 return intent;
5849 }
5850
Chilun2ef71f72018-11-16 17:57:15 +08005851 /**
5852 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5853 * activities.
5854 *
5855 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5856 * component defined in config_secondaryHomeComponent.
5857 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5858 */
5859 Intent getSecondaryHomeIntent(String preferredPackage) {
5860 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005861 if (preferredPackage == null) {
5862 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005863 final String secondaryHomeComponent = mContext.getResources().getString(
5864 com.android.internal.R.string.config_secondaryHomeComponent);
5865 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5866 } else {
5867 intent.setPackage(preferredPackage);
5868 }
5869 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5870 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5871 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5872 }
5873 return intent;
5874 }
5875
Wale Ogunwale214f3482018-10-04 11:00:47 -07005876 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5877 if (info == null) return null;
5878 ApplicationInfo newInfo = new ApplicationInfo(info);
5879 newInfo.initForUser(userId);
5880 return newInfo;
5881 }
5882
Wale Ogunwale9c103022018-10-18 07:44:54 -07005883 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005884 if (uid == SYSTEM_UID) {
5885 // The system gets to run in any process. If there are multiple processes with the same
5886 // uid, just pick the first (this should never happen).
5887 final SparseArray<WindowProcessController> procs =
5888 mProcessNames.getMap().get(processName);
5889 if (procs == null) return null;
5890 final int procCount = procs.size();
5891 for (int i = 0; i < procCount; i++) {
5892 final int procUid = procs.keyAt(i);
5893 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5894 // Don't use an app process or different user process for system component.
5895 continue;
5896 }
5897 return procs.valueAt(i);
5898 }
5899 }
5900
5901 return mProcessNames.get(processName, uid);
5902 }
5903
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005904 WindowProcessController getProcessController(IApplicationThread thread) {
5905 if (thread == null) {
5906 return null;
5907 }
5908
5909 final IBinder threadBinder = thread.asBinder();
5910 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5911 for (int i = pmap.size()-1; i >= 0; i--) {
5912 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5913 for (int j = procs.size() - 1; j >= 0; j--) {
5914 final WindowProcessController proc = procs.valueAt(j);
5915 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5916 return proc;
5917 }
5918 }
5919 }
5920
5921 return null;
5922 }
5923
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005924 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005925 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005926 if (proc == null) return null;
5927 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5928 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005929 }
5930 return null;
5931 }
5932
Riddle Hsua0536432019-02-16 00:38:59 +08005933 int getUidState(int uid) {
5934 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005935 }
5936
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005937 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005938 // A uid is considered to be foreground if it has a visible non-toast window.
5939 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005940 }
5941
Ricky Wai96f5c352019-04-10 18:40:17 +01005942 boolean isDeviceOwner(int uid) {
5943 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005944 }
5945
Ricky Wai96f5c352019-04-10 18:40:17 +01005946 void setDeviceOwnerUid(int uid) {
5947 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005948 }
5949
Wale Ogunwale9de19442018-10-18 19:05:03 -07005950 /**
5951 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5952 * the whitelist
5953 */
5954 String getPendingTempWhitelistTagForUidLocked(int uid) {
5955 return mPendingTempWhitelist.get(uid);
5956 }
5957
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005958 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5959 if (true || Build.IS_USER) {
5960 return;
5961 }
5962
5963 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5964 StrictMode.allowThreadDiskWrites();
5965 try {
5966 File tracesDir = new File("/data/anr");
5967 File tracesFile = null;
5968 try {
5969 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5970
5971 StringBuilder sb = new StringBuilder();
5972 Time tobj = new Time();
5973 tobj.set(System.currentTimeMillis());
5974 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5975 sb.append(": ");
5976 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5977 sb.append(" since ");
5978 sb.append(msg);
5979 FileOutputStream fos = new FileOutputStream(tracesFile);
5980 fos.write(sb.toString().getBytes());
5981 if (app == null) {
5982 fos.write("\n*** No application process!".getBytes());
5983 }
5984 fos.close();
5985 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5986 } catch (IOException e) {
5987 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5988 return;
5989 }
5990
5991 if (app != null && app.getPid() > 0) {
5992 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5993 firstPids.add(app.getPid());
5994 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5995 }
5996
5997 File lastTracesFile = null;
5998 File curTracesFile = null;
5999 for (int i=9; i>=0; i--) {
6000 String name = String.format(Locale.US, "slow%02d.txt", i);
6001 curTracesFile = new File(tracesDir, name);
6002 if (curTracesFile.exists()) {
6003 if (lastTracesFile != null) {
6004 curTracesFile.renameTo(lastTracesFile);
6005 } else {
6006 curTracesFile.delete();
6007 }
6008 }
6009 lastTracesFile = curTracesFile;
6010 }
6011 tracesFile.renameTo(curTracesFile);
6012 } finally {
6013 StrictMode.setThreadPolicy(oldPolicy);
6014 }
6015 }
6016
Michal Karpinskida34cd42019-04-02 19:46:52 +01006017 boolean isAssociatedCompanionApp(int userId, int uid) {
6018 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6019 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006020 return false;
6021 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006022 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006023 }
6024
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006025 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006026 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006027
6028
Wale Ogunwale98875612018-10-12 07:53:02 -07006029 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6030 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006031
Riddle Hsud93a6c42018-11-29 21:50:06 +08006032 H(Looper looper) {
6033 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006034 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006035
6036 @Override
6037 public void handleMessage(Message msg) {
6038 switch (msg.what) {
6039 case REPORT_TIME_TRACKER_MSG: {
6040 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6041 tracker.deliverResult(mContext);
6042 } break;
6043 }
6044 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006045 }
6046
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006047 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006048 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006049
6050 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006051 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006052 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006053
6054 @Override
6055 public void handleMessage(Message msg) {
6056 switch (msg.what) {
6057 case DISMISS_DIALOG_UI_MSG: {
6058 final Dialog d = (Dialog) msg.obj;
6059 d.dismiss();
6060 break;
6061 }
6062 }
6063 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006064 }
6065
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 final class LocalService extends ActivityTaskManagerInternal {
6067 @Override
6068 public SleepToken acquireSleepToken(String tag, int displayId) {
6069 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006070 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006071 }
6072
6073 @Override
6074 public ComponentName getHomeActivityForUser(int userId) {
6075 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006076 final ActivityRecord homeActivity =
6077 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006078 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006079 }
6080 }
6081
6082 @Override
6083 public void onLocalVoiceInteractionStarted(IBinder activity,
6084 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6085 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006086 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006087 }
6088 }
6089
6090 @Override
6091 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6092 synchronized (mGlobalLock) {
6093 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6094 reasons, timestamp);
6095 }
6096 }
6097
6098 @Override
6099 public void notifyAppTransitionFinished() {
6100 synchronized (mGlobalLock) {
6101 mStackSupervisor.notifyAppTransitionDone();
6102 }
6103 }
6104
6105 @Override
6106 public void notifyAppTransitionCancelled() {
6107 synchronized (mGlobalLock) {
6108 mStackSupervisor.notifyAppTransitionDone();
6109 }
6110 }
6111
6112 @Override
6113 public List<IBinder> getTopVisibleActivities() {
6114 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006115 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
6117 }
6118
6119 @Override
6120 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6121 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006122 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123 }
6124 }
6125
6126 @Override
6127 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6128 Bundle bOptions) {
6129 Preconditions.checkNotNull(intents, "intents");
6130 final String[] resolvedTypes = new String[intents.length];
6131
6132 // UID of the package on user userId.
6133 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6134 // packageUid may not be initialized.
6135 int packageUid = 0;
6136 final long ident = Binder.clearCallingIdentity();
6137
6138 try {
6139 for (int i = 0; i < intents.length; i++) {
6140 resolvedTypes[i] =
6141 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6142 }
6143
6144 packageUid = AppGlobals.getPackageManager().getPackageUid(
6145 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6146 } catch (RemoteException e) {
6147 // Shouldn't happen.
6148 } finally {
6149 Binder.restoreCallingIdentity(ident);
6150 }
6151
Riddle Hsu591bf612019-02-14 17:55:31 +08006152 return getActivityStartController().startActivitiesInPackage(
6153 packageUid, packageName,
6154 intents, resolvedTypes, null /* resultTo */,
6155 SafeActivityOptions.fromBundle(bOptions), userId,
6156 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6157 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006158 }
6159
6160 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006161 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6162 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6163 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6164 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006165 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006166 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006167 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6168 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6169 userId, validateIncomingUser, originatingPendingIntent,
6170 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006171 }
6172 }
6173
6174 @Override
6175 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6176 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6177 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6178 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006179 PendingIntentRecord originatingPendingIntent,
6180 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006181 synchronized (mGlobalLock) {
6182 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6183 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6184 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006185 validateIncomingUser, originatingPendingIntent,
6186 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006187 }
6188 }
6189
6190 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6192 Intent intent, Bundle options, int userId) {
6193 return ActivityTaskManagerService.this.startActivityAsUser(
6194 caller, callerPacakge, intent,
6195 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6196 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6197 false /*validateIncomingUser*/);
6198 }
6199
6200 @Override
lumark588a3e82018-07-20 18:53:54 +08006201 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006202 synchronized (mGlobalLock) {
6203
6204 // We might change the visibilities here, so prepare an empty app transition which
6205 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006206 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006207 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006208 if (activityDisplay == null) {
6209 return;
6210 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006211 final DisplayContent dc = activityDisplay.mDisplayContent;
6212 final boolean wasTransitionSet =
6213 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006215 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006217 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218
6219 // If there was a transition set already we don't want to interfere with it as we
6220 // might be starting it too early.
6221 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006222 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006223 }
6224 }
6225 if (callback != null) {
6226 callback.run();
6227 }
6228 }
6229
6230 @Override
6231 public void notifyKeyguardTrustedChanged() {
6232 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006233 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006234 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235 }
6236 }
6237 }
6238
6239 /**
6240 * Called after virtual display Id is updated by
6241 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6242 * {@param vrVr2dDisplayId}.
6243 */
6244 @Override
6245 public void setVr2dDisplayId(int vr2dDisplayId) {
6246 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6247 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006248 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250 }
6251
6252 @Override
6253 public void setFocusedActivity(IBinder token) {
6254 synchronized (mGlobalLock) {
6255 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6256 if (r == null) {
6257 throw new IllegalArgumentException(
6258 "setFocusedActivity: No activity record matching token=" + token);
6259 }
Louis Chang19443452018-10-09 12:10:21 +08006260 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006261 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 }
6263 }
6264 }
6265
6266 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006268 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006269 }
6270
6271 @Override
6272 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006273 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 }
6275
6276 @Override
6277 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006278 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 }
6280
6281 @Override
6282 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6283 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6284 }
6285
6286 @Override
6287 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006288 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006290
6291 @Override
6292 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6293 synchronized (mGlobalLock) {
6294 mActiveVoiceInteractionServiceComponent = component;
6295 }
6296 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006297
6298 @Override
6299 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6300 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6301 return;
6302 }
6303 synchronized (mGlobalLock) {
6304 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6305 if (types == null) {
6306 if (uid < 0) {
6307 return;
6308 }
6309 types = new ArrayMap<>();
6310 mAllowAppSwitchUids.put(userId, types);
6311 }
6312 if (uid < 0) {
6313 types.remove(type);
6314 } else {
6315 types.put(type, uid);
6316 }
6317 }
6318 }
6319
6320 @Override
6321 public void onUserStopped(int userId) {
6322 synchronized (mGlobalLock) {
6323 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6324 mAllowAppSwitchUids.remove(userId);
6325 }
6326 }
6327
6328 @Override
6329 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6330 synchronized (mGlobalLock) {
6331 return ActivityTaskManagerService.this.isGetTasksAllowed(
6332 caller, callingPid, callingUid);
6333 }
6334 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006335
Riddle Hsua0536432019-02-16 00:38:59 +08006336 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006337 @Override
6338 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006339 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006340 mProcessNames.put(proc.mName, proc.mUid, proc);
6341 }
6342 }
6343
Riddle Hsua0536432019-02-16 00:38:59 +08006344 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006345 @Override
6346 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006347 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006348 mProcessNames.remove(name, uid);
6349 }
6350 }
6351
Riddle Hsua0536432019-02-16 00:38:59 +08006352 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006353 @Override
6354 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006355 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006356 if (proc == mHomeProcess) {
6357 mHomeProcess = null;
6358 }
6359 if (proc == mPreviousProcess) {
6360 mPreviousProcess = null;
6361 }
6362 }
6363 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006364
Riddle Hsua0536432019-02-16 00:38:59 +08006365 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006366 @Override
6367 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006368 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006369 return mTopProcessState;
6370 }
6371 }
6372
Riddle Hsua0536432019-02-16 00:38:59 +08006373 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006374 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006375 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006376 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006377 return proc == mHeavyWeightProcess;
6378 }
6379 }
6380
Riddle Hsua0536432019-02-16 00:38:59 +08006381 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006382 @Override
6383 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006384 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006385 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6386 }
6387 }
6388
6389 @Override
6390 public void finishHeavyWeightApp() {
6391 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006392 if (mHeavyWeightProcess != null) {
6393 mHeavyWeightProcess.finishActivities();
6394 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006395 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6396 mHeavyWeightProcess);
6397 }
6398 }
6399
Riddle Hsua0536432019-02-16 00:38:59 +08006400 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006401 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006402 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006403 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006404 return isSleepingLocked();
6405 }
6406 }
6407
6408 @Override
6409 public boolean isShuttingDown() {
6410 synchronized (mGlobalLock) {
6411 return mShuttingDown;
6412 }
6413 }
6414
6415 @Override
6416 public boolean shuttingDown(boolean booted, int timeout) {
6417 synchronized (mGlobalLock) {
6418 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006419 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006420 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006421 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006422 return mStackSupervisor.shutdownLocked(timeout);
6423 }
6424 }
6425
6426 @Override
6427 public void enableScreenAfterBoot(boolean booted) {
6428 synchronized (mGlobalLock) {
6429 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6430 SystemClock.uptimeMillis());
6431 mWindowManager.enableScreenAfterBoot();
6432 updateEventDispatchingLocked(booted);
6433 }
6434 }
6435
6436 @Override
6437 public boolean showStrictModeViolationDialog() {
6438 synchronized (mGlobalLock) {
6439 return mShowDialogs && !mSleeping && !mShuttingDown;
6440 }
6441 }
6442
6443 @Override
6444 public void showSystemReadyErrorDialogsIfNeeded() {
6445 synchronized (mGlobalLock) {
6446 try {
6447 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6448 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6449 + " data partition or your device will be unstable.");
6450 mUiHandler.post(() -> {
6451 if (mShowDialogs) {
6452 AlertDialog d = new BaseErrorDialog(mUiContext);
6453 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6454 d.setCancelable(false);
6455 d.setTitle(mUiContext.getText(R.string.android_system_label));
6456 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6457 d.setButton(DialogInterface.BUTTON_POSITIVE,
6458 mUiContext.getText(R.string.ok),
6459 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6460 d.show();
6461 }
6462 });
6463 }
6464 } catch (RemoteException e) {
6465 }
6466
6467 if (!Build.isBuildConsistent()) {
6468 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6469 mUiHandler.post(() -> {
6470 if (mShowDialogs) {
6471 AlertDialog d = new BaseErrorDialog(mUiContext);
6472 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6473 d.setCancelable(false);
6474 d.setTitle(mUiContext.getText(R.string.android_system_label));
6475 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6476 d.setButton(DialogInterface.BUTTON_POSITIVE,
6477 mUiContext.getText(R.string.ok),
6478 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6479 d.show();
6480 }
6481 });
6482 }
6483 }
6484 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006485
6486 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006487 public void onProcessMapped(int pid, WindowProcessController proc) {
6488 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006489 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006490 }
6491 }
6492
6493 @Override
6494 public void onProcessUnMapped(int pid) {
6495 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006496 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006497 }
6498 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006499
6500 @Override
6501 public void onPackageDataCleared(String name) {
6502 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006503 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006504 mAppWarnings.onPackageDataCleared(name);
6505 }
6506 }
6507
6508 @Override
6509 public void onPackageUninstalled(String name) {
6510 synchronized (mGlobalLock) {
6511 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006512 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006513 }
6514 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006515
6516 @Override
6517 public void onPackageAdded(String name, boolean replacing) {
6518 synchronized (mGlobalLock) {
6519 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6520 }
6521 }
6522
6523 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006524 public void onPackageReplaced(ApplicationInfo aInfo) {
6525 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006526 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006527 }
6528 }
6529
6530 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006531 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6532 synchronized (mGlobalLock) {
6533 return compatibilityInfoForPackageLocked(ai);
6534 }
6535 }
6536
Yunfan Chen75157d72018-07-27 14:47:21 +09006537 /**
6538 * Set the corresponding display information for the process global configuration. To be
6539 * called when we need to show IME on a different display.
6540 *
6541 * @param pid The process id associated with the IME window.
6542 * @param displayId The ID of the display showing the IME.
6543 */
6544 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006545 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006546 // Don't update process-level configuration for Multi-Client IME process since other
6547 // IMEs on other displays will also receive this configuration change due to IME
6548 // services use the same application config/context.
6549 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006550
Yunfan Chen75157d72018-07-27 14:47:21 +09006551 if (pid == MY_PID || pid < 0) {
6552 if (DEBUG_CONFIGURATION) {
6553 Slog.w(TAG,
6554 "Trying to update display configuration for system/invalid process.");
6555 }
6556 return;
6557 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006558 synchronized (mGlobalLock) {
6559 final ActivityDisplay activityDisplay =
6560 mRootActivityContainer.getActivityDisplay(displayId);
6561 if (activityDisplay == null) {
6562 // Call might come when display is not yet added or has been removed.
6563 if (DEBUG_CONFIGURATION) {
6564 Slog.w(TAG, "Trying to update display configuration for non-existing "
6565 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006566 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006567 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006568 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006569 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006570 if (process == null) {
6571 if (DEBUG_CONFIGURATION) {
6572 Slog.w(TAG, "Trying to update display configuration for invalid "
6573 + "process, pid=" + pid);
6574 }
6575 return;
6576 }
6577 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6578 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006579 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006580
6581 @Override
6582 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6583 int requestCode, int resultCode, Intent data) {
6584 synchronized (mGlobalLock) {
6585 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006586 if (r != null && r.getActivityStack() != null) {
6587 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6588 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006589 }
6590 }
6591 }
6592
6593 @Override
6594 public void clearPendingResultForActivity(IBinder activityToken,
6595 WeakReference<PendingIntentRecord> pir) {
6596 synchronized (mGlobalLock) {
6597 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6598 if (r != null && r.pendingResults != null) {
6599 r.pendingResults.remove(pir);
6600 }
6601 }
6602 }
6603
6604 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006605 public ActivityTokens getTopActivityForTask(int taskId) {
6606 synchronized (mGlobalLock) {
6607 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6608 if (taskRecord == null) {
6609 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6610 + " Requested task not found");
6611 return null;
6612 }
6613 final ActivityRecord activity = taskRecord.getTopActivity();
6614 if (activity == null) {
6615 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6616 + " Requested activity not found");
6617 return null;
6618 }
6619 if (!activity.attachedToProcess()) {
6620 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6621 + activity);
6622 return null;
6623 }
6624 return new ActivityTokens(activity.appToken, activity.assistToken,
6625 activity.app.getThread());
6626 }
6627 }
6628
6629 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006630 public IIntentSender getIntentSender(int type, String packageName,
6631 int callingUid, int userId, IBinder token, String resultWho,
6632 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6633 Bundle bOptions) {
6634 synchronized (mGlobalLock) {
6635 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6636 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6637 }
6638 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006639
6640 @Override
6641 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6642 synchronized (mGlobalLock) {
6643 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6644 if (r == null) {
6645 return null;
6646 }
6647 if (r.mServiceConnectionsHolder == null) {
6648 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6649 ActivityTaskManagerService.this, r);
6650 }
6651
6652 return r.mServiceConnectionsHolder;
6653 }
6654 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006655
6656 @Override
6657 public Intent getHomeIntent() {
6658 synchronized (mGlobalLock) {
6659 return ActivityTaskManagerService.this.getHomeIntent();
6660 }
6661 }
6662
6663 @Override
6664 public boolean startHomeActivity(int userId, String reason) {
6665 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006666 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006667 }
6668 }
6669
6670 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006671 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006672 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006673 synchronized (mGlobalLock) {
6674 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006675 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006676 }
Chilun8b1f1be2019-03-13 17:14:36 +08006677 }
6678
6679 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006680 public boolean startHomeOnAllDisplays(int userId, String reason) {
6681 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006682 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006683 }
6684 }
6685
Riddle Hsua0536432019-02-16 00:38:59 +08006686 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006687 @Override
6688 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006689 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006690 if (mFactoryTest == FACTORY_TEST_OFF) {
6691 return false;
6692 }
6693 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6694 && wpc.mName.equals(mTopComponent.getPackageName())) {
6695 return true;
6696 }
6697 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6698 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6699 }
6700 }
6701
6702 @Override
6703 public void updateTopComponentForFactoryTest() {
6704 synchronized (mGlobalLock) {
6705 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6706 return;
6707 }
6708 final ResolveInfo ri = mContext.getPackageManager()
6709 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6710 final CharSequence errorMsg;
6711 if (ri != null) {
6712 final ActivityInfo ai = ri.activityInfo;
6713 final ApplicationInfo app = ai.applicationInfo;
6714 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6715 mTopAction = Intent.ACTION_FACTORY_TEST;
6716 mTopData = null;
6717 mTopComponent = new ComponentName(app.packageName, ai.name);
6718 errorMsg = null;
6719 } else {
6720 errorMsg = mContext.getResources().getText(
6721 com.android.internal.R.string.factorytest_not_system);
6722 }
6723 } else {
6724 errorMsg = mContext.getResources().getText(
6725 com.android.internal.R.string.factorytest_no_action);
6726 }
6727 if (errorMsg == null) {
6728 return;
6729 }
6730
6731 mTopAction = null;
6732 mTopData = null;
6733 mTopComponent = null;
6734 mUiHandler.post(() -> {
6735 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6736 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006737 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006738 });
6739 }
6740 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006741
Riddle Hsua0536432019-02-16 00:38:59 +08006742 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 @Override
6744 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6745 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006746 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006747 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006748 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749
6750 wpc.clearRecentTasks();
6751 wpc.clearActivities();
6752
6753 if (wpc.isInstrumenting()) {
6754 finishInstrumentationCallback.run();
6755 }
6756
Jorim Jaggid0752812018-10-16 16:07:20 +02006757 if (!restarting && hasVisibleActivities) {
6758 mWindowManager.deferSurfaceLayout();
6759 try {
6760 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6761 // If there was nothing to resume, and we are not already restarting
6762 // this process, but there is a visible activity that is hosted by the
6763 // process...then make sure all visible activities are running, taking
6764 // care of restarting this process.
6765 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6766 !PRESERVE_WINDOWS);
6767 }
6768 } finally {
6769 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 }
6772 }
6773 }
6774
6775 @Override
6776 public void closeSystemDialogs(String reason) {
6777 enforceNotIsolatedCaller("closeSystemDialogs");
6778
6779 final int pid = Binder.getCallingPid();
6780 final int uid = Binder.getCallingUid();
6781 final long origId = Binder.clearCallingIdentity();
6782 try {
6783 synchronized (mGlobalLock) {
6784 // Only allow this from foreground processes, so that background
6785 // applications can't abuse it to prevent system UI from being shown.
6786 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006787 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006788 if (!proc.isPerceptible()) {
6789 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6790 + " from background process " + proc);
6791 return;
6792 }
6793 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006794 mWindowManager.closeSystemDialogs(reason);
6795
Wale Ogunwaled32da472018-11-16 07:19:28 -08006796 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006798 // Call into AM outside the synchronized block.
6799 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800 } finally {
6801 Binder.restoreCallingIdentity(origId);
6802 }
6803 }
6804
6805 @Override
6806 public void cleanupDisabledPackageComponents(
6807 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6808 synchronized (mGlobalLock) {
6809 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006810 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006811 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 mStackSupervisor.scheduleIdleLocked();
6814 }
6815
6816 // Clean-up disabled tasks
6817 getRecentTasks().cleanupDisabledPackageTasksLocked(
6818 packageName, disabledClasses, userId);
6819 }
6820 }
6821
6822 @Override
6823 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6824 int userId) {
6825 synchronized (mGlobalLock) {
6826
6827 boolean didSomething =
6828 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006829 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 null, doit, evenPersistent, userId);
6831 return didSomething;
6832 }
6833 }
6834
6835 @Override
6836 public void resumeTopActivities(boolean scheduleIdle) {
6837 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006838 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 if (scheduleIdle) {
6840 mStackSupervisor.scheduleIdleLocked();
6841 }
6842 }
6843 }
6844
Riddle Hsua0536432019-02-16 00:38:59 +08006845 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 @Override
6847 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006848 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6850 }
6851 }
6852
Riddle Hsua0536432019-02-16 00:38:59 +08006853 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 @Override
6855 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006856 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006857 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 }
6859 }
6860
6861 @Override
6862 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6863 try {
6864 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6865 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6866 }
6867 } catch (RemoteException ex) {
6868 throw new SecurityException("Fail to check is caller a privileged app", ex);
6869 }
6870
6871 synchronized (mGlobalLock) {
6872 final long ident = Binder.clearCallingIdentity();
6873 try {
6874 if (mAmInternal.shouldConfirmCredentials(userId)) {
6875 if (mKeyguardController.isKeyguardLocked()) {
6876 // Showing launcher to avoid user entering credential twice.
6877 startHomeActivity(currentUserId, "notifyLockedProfile");
6878 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006879 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 }
6881 } finally {
6882 Binder.restoreCallingIdentity(ident);
6883 }
6884 }
6885 }
6886
6887 @Override
6888 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6889 mAmInternal.enforceCallingPermission(
6890 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6891
6892 synchronized (mGlobalLock) {
6893 final long ident = Binder.clearCallingIdentity();
6894 try {
6895 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6896 FLAG_ACTIVITY_TASK_ON_HOME);
6897 ActivityOptions activityOptions = options != null
6898 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006899 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006900 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006901 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006902 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006903 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6905 UserHandle.CURRENT);
6906 } finally {
6907 Binder.restoreCallingIdentity(ident);
6908 }
6909 }
6910 }
6911
6912 @Override
6913 public void writeActivitiesToProto(ProtoOutputStream proto) {
6914 synchronized (mGlobalLock) {
6915 // The output proto of "activity --proto activities"
6916 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006917 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006918 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6919 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 }
6921 }
6922
6923 @Override
6924 public void saveANRState(String reason) {
6925 synchronized (mGlobalLock) {
6926 final StringWriter sw = new StringWriter();
6927 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6928 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6929 if (reason != null) {
6930 pw.println(" Reason: " + reason);
6931 }
6932 pw.println();
6933 getActivityStartController().dump(pw, " ", null);
6934 pw.println();
6935 pw.println("-------------------------------------------------------------------------------");
6936 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6937 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6938 "" /* header */);
6939 pw.println();
6940 pw.close();
6941
6942 mLastANRState = sw.toString();
6943 }
6944 }
6945
6946 @Override
6947 public void clearSavedANRState() {
6948 synchronized (mGlobalLock) {
6949 mLastANRState = null;
6950 }
6951 }
6952
6953 @Override
6954 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6955 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6956 synchronized (mGlobalLock) {
6957 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6958 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6959 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6960 dumpLastANRLocked(pw);
6961 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6962 dumpLastANRTracesLocked(pw);
6963 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6964 dumpActivityStarterLocked(pw, dumpPackage);
6965 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6966 dumpActivityContainersLocked(pw);
6967 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6968 if (getRecentTasks() != null) {
6969 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6970 }
6971 }
6972 }
6973 }
6974
6975 @Override
6976 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6977 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6978 int wakefulness) {
6979 synchronized (mGlobalLock) {
6980 if (mHomeProcess != null && (dumpPackage == null
6981 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6982 if (needSep) {
6983 pw.println();
6984 needSep = false;
6985 }
6986 pw.println(" mHomeProcess: " + mHomeProcess);
6987 }
6988 if (mPreviousProcess != null && (dumpPackage == null
6989 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6990 if (needSep) {
6991 pw.println();
6992 needSep = false;
6993 }
6994 pw.println(" mPreviousProcess: " + mPreviousProcess);
6995 }
6996 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6997 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6998 StringBuilder sb = new StringBuilder(128);
6999 sb.append(" mPreviousProcessVisibleTime: ");
7000 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7001 pw.println(sb);
7002 }
7003 if (mHeavyWeightProcess != null && (dumpPackage == null
7004 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7005 if (needSep) {
7006 pw.println();
7007 needSep = false;
7008 }
7009 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7010 }
7011 if (dumpPackage == null) {
7012 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007013 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 }
7015 if (dumpAll) {
7016 if (dumpPackage == null) {
7017 pw.println(" mConfigWillChange: "
7018 + getTopDisplayFocusedStack().mConfigWillChange);
7019 }
7020 if (mCompatModePackages.getPackages().size() > 0) {
7021 boolean printed = false;
7022 for (Map.Entry<String, Integer> entry
7023 : mCompatModePackages.getPackages().entrySet()) {
7024 String pkg = entry.getKey();
7025 int mode = entry.getValue();
7026 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7027 continue;
7028 }
7029 if (!printed) {
7030 pw.println(" mScreenCompatPackages:");
7031 printed = true;
7032 }
7033 pw.println(" " + pkg + ": " + mode);
7034 }
7035 }
7036 }
7037
7038 if (dumpPackage == null) {
7039 pw.println(" mWakefulness="
7040 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007041 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007042 if (mRunningVoice != null) {
7043 pw.println(" mRunningVoice=" + mRunningVoice);
7044 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7045 }
7046 pw.println(" mSleeping=" + mSleeping);
7047 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7048 pw.println(" mVrController=" + mVrController);
7049 }
7050 if (mCurAppTimeTracker != null) {
7051 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7052 }
7053 if (mAllowAppSwitchUids.size() > 0) {
7054 boolean printed = false;
7055 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7056 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7057 for (int j = 0; j < types.size(); j++) {
7058 if (dumpPackage == null ||
7059 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7060 if (needSep) {
7061 pw.println();
7062 needSep = false;
7063 }
7064 if (!printed) {
7065 pw.println(" mAllowAppSwitchUids:");
7066 printed = true;
7067 }
7068 pw.print(" User ");
7069 pw.print(mAllowAppSwitchUids.keyAt(i));
7070 pw.print(": Type ");
7071 pw.print(types.keyAt(j));
7072 pw.print(" = ");
7073 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7074 pw.println();
7075 }
7076 }
7077 }
7078 }
7079 if (dumpPackage == null) {
7080 if (mController != null) {
7081 pw.println(" mController=" + mController
7082 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7083 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007084 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7085 pw.println(" mLaunchingActivityWakeLock="
7086 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007087 }
7088
7089 return needSep;
7090 }
7091 }
7092
7093 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007094 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7095 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007096 synchronized (mGlobalLock) {
7097 if (dumpPackage == null) {
7098 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7099 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007100 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7101 if (mRunningVoice != null) {
7102 final long vrToken = proto.start(
7103 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7104 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7105 mRunningVoice.toString());
7106 mVoiceWakeLock.writeToProto(
7107 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7108 proto.end(vrToken);
7109 }
7110 mVrController.writeToProto(proto,
7111 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 if (mController != null) {
7113 final long token = proto.start(CONTROLLER);
7114 proto.write(CONTROLLER, mController.toString());
7115 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7116 proto.end(token);
7117 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007118 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7119 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7120 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122
7123 if (mHomeProcess != null && (dumpPackage == null
7124 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007125 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 }
7127
7128 if (mPreviousProcess != null && (dumpPackage == null
7129 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007130 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7132 }
7133
7134 if (mHeavyWeightProcess != null && (dumpPackage == null
7135 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007136 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 }
7138
7139 for (Map.Entry<String, Integer> entry
7140 : mCompatModePackages.getPackages().entrySet()) {
7141 String pkg = entry.getKey();
7142 int mode = entry.getValue();
7143 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7144 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7145 proto.write(PACKAGE, pkg);
7146 proto.write(MODE, mode);
7147 proto.end(compatToken);
7148 }
7149 }
7150
7151 if (mCurAppTimeTracker != null) {
7152 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7153 }
7154
7155 }
7156 }
7157
7158 @Override
7159 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7160 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7161 boolean dumpFocusedStackOnly) {
7162 synchronized (mGlobalLock) {
7163 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7164 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7165 }
7166 }
7167
7168 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007169 public void dumpForOom(PrintWriter pw) {
7170 synchronized (mGlobalLock) {
7171 pw.println(" mHomeProcess: " + mHomeProcess);
7172 pw.println(" mPreviousProcess: " + mPreviousProcess);
7173 if (mHeavyWeightProcess != null) {
7174 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7175 }
7176 }
7177 }
7178
7179 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 public boolean canGcNow() {
7181 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007182 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184 }
7185
Riddle Hsua0536432019-02-16 00:38:59 +08007186 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007187 @Override
7188 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007189 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007190 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 return top != null ? top.app : null;
7192 }
7193 }
7194
Riddle Hsua0536432019-02-16 00:38:59 +08007195 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007196 @Override
7197 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007198 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007199 if (mRootActivityContainer != null) {
7200 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007201 }
7202 }
7203 }
7204
7205 @Override
7206 public void scheduleDestroyAllActivities(String reason) {
7207 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007208 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007209 }
7210 }
7211
7212 @Override
7213 public void removeUser(int userId) {
7214 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007215 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217 }
7218
7219 @Override
7220 public boolean switchUser(int userId, UserState userState) {
7221 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007222 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 }
7224 }
7225
7226 @Override
7227 public void onHandleAppCrash(WindowProcessController wpc) {
7228 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007229 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007230 }
7231 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007232
7233 @Override
7234 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7235 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007236 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007237 }
7238 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007239
Riddle Hsua0536432019-02-16 00:38:59 +08007240 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007241 @Override
7242 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007243 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007244 }
7245
Riddle Hsua0536432019-02-16 00:38:59 +08007246 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007247 @Override
7248 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007249 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007250 }
7251
Riddle Hsua0536432019-02-16 00:38:59 +08007252 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007253 @Override
7254 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007255 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007256 }
7257
Riddle Hsua0536432019-02-16 00:38:59 +08007258 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007259 @Override
7260 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007261 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007262 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007263
7264 @Override
7265 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007266 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007267 mPendingTempWhitelist.put(uid, tag);
7268 }
7269 }
7270
7271 @Override
7272 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007273 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007274 mPendingTempWhitelist.remove(uid);
7275 }
7276 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007277
7278 @Override
7279 public boolean handleAppCrashInActivityController(String processName, int pid,
7280 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7281 Runnable killCrashingAppCallback) {
7282 synchronized (mGlobalLock) {
7283 if (mController == null) {
7284 return false;
7285 }
7286
7287 try {
7288 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7289 stackTrace)) {
7290 killCrashingAppCallback.run();
7291 return true;
7292 }
7293 } catch (RemoteException e) {
7294 mController = null;
7295 Watchdog.getInstance().setActivityController(null);
7296 }
7297 return false;
7298 }
7299 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007300
7301 @Override
7302 public void removeRecentTasksByPackageName(String packageName, int userId) {
7303 synchronized (mGlobalLock) {
7304 mRecentTasks.removeTasksByPackageName(packageName, userId);
7305 }
7306 }
7307
7308 @Override
7309 public void cleanupRecentTasksForUser(int userId) {
7310 synchronized (mGlobalLock) {
7311 mRecentTasks.cleanupLocked(userId);
7312 }
7313 }
7314
7315 @Override
7316 public void loadRecentTasksForUser(int userId) {
7317 synchronized (mGlobalLock) {
7318 mRecentTasks.loadUserRecentsLocked(userId);
7319 }
7320 }
7321
7322 @Override
7323 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7324 synchronized (mGlobalLock) {
7325 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7326 }
7327 }
7328
7329 @Override
7330 public void flushRecentTasks() {
7331 mRecentTasks.flush();
7332 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007333
7334 @Override
7335 public WindowProcessController getHomeProcess() {
7336 synchronized (mGlobalLock) {
7337 return mHomeProcess;
7338 }
7339 }
7340
7341 @Override
7342 public WindowProcessController getPreviousProcess() {
7343 synchronized (mGlobalLock) {
7344 return mPreviousProcess;
7345 }
7346 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007347
7348 @Override
7349 public void clearLockedTasks(String reason) {
7350 synchronized (mGlobalLock) {
7351 getLockTaskController().clearLockedTasks(reason);
7352 }
7353 }
7354
7355 @Override
7356 public void updateUserConfiguration() {
7357 synchronized (mGlobalLock) {
7358 final Configuration configuration = new Configuration(getGlobalConfiguration());
7359 final int currentUserId = mAmInternal.getCurrentUserId();
7360 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7361 configuration, currentUserId, Settings.System.canWrite(mContext));
7362 updateConfigurationLocked(configuration, null /* starting */,
7363 false /* initLocale */, false /* persistent */, currentUserId,
7364 false /* deferResume */);
7365 }
7366 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007367
7368 @Override
7369 public boolean canShowErrorDialogs() {
7370 synchronized (mGlobalLock) {
7371 return mShowDialogs && !mSleeping && !mShuttingDown
7372 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7373 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7374 mAmInternal.getCurrentUserId())
7375 && !(UserManager.isDeviceInDemoMode(mContext)
7376 && mAmInternal.getCurrentUser().isDemo());
7377 }
7378 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007379
7380 @Override
7381 public void setProfileApp(String profileApp) {
7382 synchronized (mGlobalLock) {
7383 mProfileApp = profileApp;
7384 }
7385 }
7386
7387 @Override
7388 public void setProfileProc(WindowProcessController wpc) {
7389 synchronized (mGlobalLock) {
7390 mProfileProc = wpc;
7391 }
7392 }
7393
7394 @Override
7395 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7396 synchronized (mGlobalLock) {
7397 mProfilerInfo = profilerInfo;
7398 }
7399 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007400
7401 @Override
7402 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7403 synchronized (mGlobalLock) {
7404 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7405 }
7406 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007407
7408 @Override
7409 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7410 synchronized (mGlobalLock) {
7411 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7412 }
7413 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007414
7415 @Override
7416 public boolean isUidForeground(int uid) {
7417 synchronized (mGlobalLock) {
7418 return ActivityTaskManagerService.this.isUidForeground(uid);
7419 }
7420 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007421
7422 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007423 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007424 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007425 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007426 }
7427 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007428
7429 @Override
7430 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007431 // Translate package names into UIDs
7432 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007433 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007434 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7435 if (uid >= 0) {
7436 result.add(uid);
7437 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007438 }
7439 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007440 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007441 }
7442 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007443 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007444}