blob: b234bc6f77c3c750aa438cfa9363f62bad767f66 [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;
268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314
Wale Ogunwale98875612018-10-12 07:53:02 -0700315 /** Used to indicate that an app transition should be animated. */
316 static final boolean ANIMATE = true;
317
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700318 /** Hardware-reported OpenGLES version. */
319 final int GL_ES_VERSION;
320
Wale Ogunwale31913b52018-10-13 08:29:31 -0700321 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
322 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
323 public static final String DUMP_LASTANR_CMD = "lastanr" ;
324 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
325 public static final String DUMP_STARTER_CMD = "starter" ;
326 public static final String DUMP_CONTAINERS_CMD = "containers" ;
327 public static final String DUMP_RECENTS_CMD = "recents" ;
328 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
329
Wale Ogunwale64258362018-10-16 15:13:37 -0700330 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
331 public static final int RELAUNCH_REASON_NONE = 0;
332 /** This activity is being relaunched due to windowing mode change. */
333 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
334 /** This activity is being relaunched due to a free-resize operation. */
335 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
336
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700337 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700338
Wale Ogunwalef6733932018-06-27 05:14:34 -0700339 /**
340 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
341 * change at runtime. Use mContext for non-UI purposes.
342 */
343 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700345 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700346 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700348 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700349 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800350 @VisibleForTesting
351 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 PowerManagerInternal mPowerManagerInternal;
353 private UsageStatsManagerInternal mUsageStatsInternal;
354
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700355 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 IntentFirewall mIntentFirewall;
357
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700358 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800359 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800360 /**
361 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
362 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
363 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
364 *
365 * @see WindowManagerThreadPriorityBooster
366 */
367 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700368 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800369 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700370 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700371 private UserManagerService mUserManager;
372 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700373 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800374 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700375 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700376 /** All processes currently running that might have a window organized by name. */
377 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100378 /** All processes we currently have running mapped by pid and uid */
379 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** This is the process holding what we currently consider to be the "home" activity. */
381 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700382 /** The currently running heavy-weight process, if any. */
383 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700384 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /**
386 * This is the process holding the activity the user last visited that is in a different process
387 * from the one they are currently in.
388 */
389 WindowProcessController mPreviousProcess;
390 /** The time at which the previous process was last visible. */
391 long mPreviousProcessVisibleTime;
392
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700393 /** List of intents that were used to start the most recent tasks. */
394 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700395 /** State of external calls telling us if the device is awake or asleep. */
396 private boolean mKeyguardShown = false;
397
398 // Wrapper around VoiceInteractionServiceManager
399 private AssistUtils mAssistUtils;
400
401 // VoiceInteraction session ID that changes for each new request except when
402 // being called for multi-window assist in a single session.
403 private int mViSessionId = 1000;
404
405 // How long to wait in getAssistContextExtras for the activity and foreground services
406 // to respond with the result.
407 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
408
409 // How long top wait when going through the modern assist (which doesn't need to block
410 // on getting this result before starting to launch its UI).
411 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
412
413 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
414 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
415
Alison Cichowlas3e340502018-08-07 17:15:01 -0400416 // Permission tokens are used to temporarily granted a trusted app the ability to call
417 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
418 // showing any appropriate error messages to the user.
419 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
420 10 * MINUTE_IN_MILLIS;
421
422 // How long before the service actually expires a token. This is slightly longer than
423 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
424 // expiration exception.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
426 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
427
428 // How long the service will remember expired tokens, for the purpose of providing error
429 // messaging when a client uses an expired token.
430 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
431 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
432
Marvin Ramin830d4e32019-03-12 13:16:58 +0100433 // How long to whitelist the Services for when requested.
434 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
435
Alison Cichowlas3e340502018-08-07 17:15:01 -0400436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
462 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
507 IActivityController mController = null;
508 boolean mControllerIsAMonkey = false;
509
Wale Ogunwale214f3482018-10-04 11:00:47 -0700510 final int mFactoryTest;
511
512 /** Used to control how we initialize the service. */
513 ComponentName mTopComponent;
514 String mTopAction = Intent.ACTION_MAIN;
515 String mTopData;
516
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800517 /** Profiling app information. */
518 String mProfileApp = null;
519 WindowProcessController mProfileProc = null;
520 ProfilerInfo mProfilerInfo = null;
521
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700523 * Dump of the activity state at the time of the last ANR. Cleared after
524 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
525 */
526 String mLastANRState;
527
528 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700529 * Used to retain an update lock when the foreground activity is in
530 * immersive mode.
531 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700532 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533
534 /**
535 * Packages that are being allowed to perform unrestricted app switches. Mapping is
536 * User -> Type -> uid.
537 */
538 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
539
540 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private int mThumbnailWidth;
542 private int mThumbnailHeight;
543 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Flag that indicates if multi-window is enabled.
547 *
548 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
549 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
550 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
551 * At least one of the forms of multi-window must be enabled in order for this flag to be
552 * initialized to 'true'.
553 *
554 * @see #mSupportsSplitScreenMultiWindow
555 * @see #mSupportsFreeformWindowManagement
556 * @see #mSupportsPictureInPicture
557 * @see #mSupportsMultiDisplay
558 */
559 boolean mSupportsMultiWindow;
560 boolean mSupportsSplitScreenMultiWindow;
561 boolean mSupportsFreeformWindowManagement;
562 boolean mSupportsPictureInPicture;
563 boolean mSupportsMultiDisplay;
564 boolean mForceResizableActivities;
565
566 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
567
568 // VR Vr2d Display Id.
569 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700570
Wale Ogunwalef6733932018-06-27 05:14:34 -0700571 /**
572 * Set while we are wanting to sleep, to prevent any
573 * activities from being started/resumed.
574 *
575 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
576 *
577 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
578 * while in the sleep state until there is a pending transition out of sleep, in which case
579 * mSleeping is set to false, and remains false while awake.
580 *
581 * Whether mSleeping can quickly toggled between true/false without the device actually
582 * display changing states is undefined.
583 */
584 private boolean mSleeping = false;
585
586 /**
587 * The process state used for processes that are running the top activities.
588 * This changes between TOP and TOP_SLEEPING to following mSleeping.
589 */
590 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
591
592 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
593 // automatically. Important for devices without direct input devices.
594 private boolean mShowDialogs = true;
595
596 /** Set if we are shutting down the system, similar to sleeping. */
597 boolean mShuttingDown = false;
598
599 /**
600 * We want to hold a wake lock while running a voice interaction session, since
601 * this may happen with the screen off and we need to keep the CPU running to
602 * be able to continue to interact with the user.
603 */
604 PowerManager.WakeLock mVoiceWakeLock;
605
606 /**
607 * Set while we are running a voice interaction. This overrides sleeping while it is active.
608 */
609 IVoiceInteractionSession mRunningVoice;
610
611 /**
612 * The last resumed activity. This is identical to the current resumed activity most
613 * of the time but could be different when we're pausing one activity before we resume
614 * another activity.
615 */
616 ActivityRecord mLastResumedActivity;
617
618 /**
619 * The activity that is currently being traced as the active resumed activity.
620 *
621 * @see #updateResumedAppTrace
622 */
623 private @Nullable ActivityRecord mTracedResumedActivity;
624
625 /** If non-null, we are tracking the time the user spends in the currently focused app. */
626 AppTimeTracker mCurAppTimeTracker;
627
Wale Ogunwale008163e2018-07-23 23:11:08 -0700628 private AppWarnings mAppWarnings;
629
Wale Ogunwale53783742018-09-16 10:21:51 -0700630 /**
631 * Packages that the user has asked to have run in screen size
632 * compatibility mode instead of filling the screen.
633 */
634 CompatModePackages mCompatModePackages;
635
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 private FontScaleSettingObserver mFontScaleSettingObserver;
637
Ricky Wai96f5c352019-04-10 18:40:17 +0100638 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000639
Wale Ogunwalef6733932018-06-27 05:14:34 -0700640 private final class FontScaleSettingObserver extends ContentObserver {
641 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
642 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
643
644 public FontScaleSettingObserver() {
645 super(mH);
646 final ContentResolver resolver = mContext.getContentResolver();
647 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
648 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
649 UserHandle.USER_ALL);
650 }
651
652 @Override
653 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
654 if (mFontScaleUri.equals(uri)) {
655 updateFontScaleIfNeeded(userId);
656 } else if (mHideErrorDialogsUri.equals(uri)) {
657 synchronized (mGlobalLock) {
658 updateShouldShowDialogsLocked(getGlobalConfiguration());
659 }
660 }
661 }
662 }
663
Riddle Hsua0536432019-02-16 00:38:59 +0800664 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
665 @Target(ElementType.METHOD)
666 @Retention(RetentionPolicy.SOURCE)
667 @interface HotPath {
668 int NONE = 0;
669 int OOM_ADJUSTMENT = 1;
670 int LRU_UPDATE = 2;
671 int PROCESS_CHANGE = 3;
672 int caller() default NONE;
673 }
674
Charles Chen8d98dd22018-12-26 17:36:54 +0800675 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
676 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700677 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700678 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700679 mSystemThread = ActivityThread.currentActivityThread();
680 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700681 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800682 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700683 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 }
685
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700686 public void onSystemReady() {
687 synchronized (mGlobalLock) {
688 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
689 PackageManager.FEATURE_CANT_SAVE_STATE);
690 mAssistUtils = new AssistUtils(mContext);
691 mVrController.onSystemReady();
692 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700693 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700694 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700695 }
696
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700697 public void onInitPowerManagement() {
698 synchronized (mGlobalLock) {
699 mStackSupervisor.initPowerManagement();
700 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
701 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
702 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
703 mVoiceWakeLock.setReferenceCounted(false);
704 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700708 mFontScaleSettingObserver = new FontScaleSettingObserver();
709 }
710
Wale Ogunwale59507092018-10-29 09:00:30 -0700711 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700712 final boolean freeformWindowManagement =
713 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
714 || Settings.Global.getInt(
715 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
716
717 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
718 final boolean supportsPictureInPicture = supportsMultiWindow &&
719 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
720 final boolean supportsSplitScreenMultiWindow =
721 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
722 final boolean supportsMultiDisplay = mContext.getPackageManager()
723 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700724 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
725 final boolean forceResizable = Settings.Global.getInt(
726 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700727 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728
729 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900730 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700731
732 final Configuration configuration = new Configuration();
733 Settings.System.getConfiguration(resolver, configuration);
734 if (forceRtl) {
735 // This will take care of setting the correct layout direction flags
736 configuration.setLayoutDirection(configuration.locale);
737 }
738
739 synchronized (mGlobalLock) {
740 mForceResizableActivities = forceResizable;
741 final boolean multiWindowFormEnabled = freeformWindowManagement
742 || supportsSplitScreenMultiWindow
743 || supportsPictureInPicture
744 || supportsMultiDisplay;
745 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
746 mSupportsMultiWindow = true;
747 mSupportsFreeformWindowManagement = freeformWindowManagement;
748 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
749 mSupportsPictureInPicture = supportsPictureInPicture;
750 mSupportsMultiDisplay = supportsMultiDisplay;
751 } else {
752 mSupportsMultiWindow = false;
753 mSupportsFreeformWindowManagement = false;
754 mSupportsSplitScreenMultiWindow = false;
755 mSupportsPictureInPicture = false;
756 mSupportsMultiDisplay = false;
757 }
758 mWindowManager.setForceResizableTasks(mForceResizableActivities);
759 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700760 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
761 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700762 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763 // This happens before any activities are started, so we can change global configuration
764 // in-place.
765 updateConfigurationLocked(configuration, null, true);
766 final Configuration globalConfig = getGlobalConfiguration();
767 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
768
769 // Load resources only after the current configuration has been set.
770 final Resources res = mContext.getResources();
771 mThumbnailWidth = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_width);
773 mThumbnailHeight = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_height);
775
776 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
777 mFullscreenThumbnailScale = (float) res
778 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
779 (float) globalConfig.screenWidthDp;
780 } else {
781 mFullscreenThumbnailScale = res.getFraction(
782 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
783 }
784 }
785 }
786
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800787 public WindowManagerGlobalLock getGlobalLock() {
788 return mGlobalLock;
789 }
790
Yunfan Chen585f2932019-01-29 16:04:45 +0900791 /** For test purpose only. */
792 @VisibleForTesting
793 public ActivityTaskManagerInternal getAtmInternal() {
794 return mInternal;
795 }
796
Riddle Hsud93a6c42018-11-29 21:50:06 +0800797 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
798 Looper looper) {
799 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700800 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700801 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700802 final File systemDir = SystemServiceManager.ensureSystemDir();
803 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
804 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
807 mTempConfig.setToDefaults();
808 mTempConfig.setLocales(LocaleList.getDefault());
809 mConfigurationSeq = mTempConfig.seq = 1;
810 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800811 mRootActivityContainer = new RootActivityContainer(this);
812 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700818 mRecentTasks = createRecentTasks();
819 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mKeyguardController = mStackSupervisor.getKeyguardController();
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void onActivityManagerInternalAdded() {
825 synchronized (mGlobalLock) {
826 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
827 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
828 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700829 }
830
Yunfan Chen75157d72018-07-27 14:47:21 +0900831 int increaseConfigurationSeqLocked() {
832 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
833 return mConfigurationSeq;
834 }
835
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 protected ActivityStackSupervisor createStackSupervisor() {
837 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
838 supervisor.initialize();
839 return supervisor;
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void setWindowManager(WindowManagerService wm) {
843 synchronized (mGlobalLock) {
844 mWindowManager = wm;
845 mLockTaskController.setWindowManager(wm);
846 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800847 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700849 }
850
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
852 synchronized (mGlobalLock) {
853 mUsageStatsInternal = usageStatsManager;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 }
856
Wale Ogunwalef6733932018-06-27 05:14:34 -0700857 UserManagerService getUserManager() {
858 if (mUserManager == null) {
859 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
860 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
861 }
862 return mUserManager;
863 }
864
865 AppOpsService getAppOpsService() {
866 if (mAppOpsService == null) {
867 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
868 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
869 }
870 return mAppOpsService;
871 }
872
873 boolean hasUserRestriction(String restriction, int userId) {
874 return getUserManager().hasUserRestriction(restriction, userId);
875 }
876
Michal Karpinski15486842019-04-25 17:33:42 +0100877 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
878 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
879 callingUid, callingPackage);
880 if (mode == AppOpsManager.MODE_DEFAULT) {
881 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
882 == PERMISSION_GRANTED;
883 }
884 return mode == AppOpsManager.MODE_ALLOWED;
885 }
886
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700887 protected RecentTasks createRecentTasks() {
888 return new RecentTasks(this, mStackSupervisor);
889 }
890
891 RecentTasks getRecentTasks() {
892 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700893 }
894
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700895 ClientLifecycleManager getLifecycleManager() {
896 return mLifecycleManager;
897 }
898
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700899 ActivityStartController getActivityStartController() {
900 return mActivityStartController;
901 }
902
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700903 TaskChangeNotificationController getTaskChangeNotificationController() {
904 return mTaskChangeNotificationController;
905 }
906
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700907 LockTaskController getLockTaskController() {
908 return mLockTaskController;
909 }
910
Yunfan Chen75157d72018-07-27 14:47:21 +0900911 /**
912 * Return the global configuration used by the process corresponding to the input pid. This is
913 * usually the global configuration with some overrides specific to that process.
914 */
915 Configuration getGlobalConfigurationForCallingPid() {
916 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800917 return getGlobalConfigurationForPid(pid);
918 }
919
920 /**
921 * Return the global configuration used by the process corresponding to the given pid.
922 */
923 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900924 if (pid == MY_PID || pid < 0) {
925 return getGlobalConfiguration();
926 }
927 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100928 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 return app != null ? app.getConfiguration() : getGlobalConfiguration();
930 }
931 }
932
933 /**
934 * Return the device configuration info used by the process corresponding to the input pid.
935 * The value is consistent with the global configuration for the process.
936 */
937 @Override
938 public ConfigurationInfo getDeviceConfigurationInfo() {
939 ConfigurationInfo config = new ConfigurationInfo();
940 synchronized (mGlobalLock) {
941 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
942 config.reqTouchScreen = globalConfig.touchscreen;
943 config.reqKeyboardType = globalConfig.keyboard;
944 config.reqNavigation = globalConfig.navigation;
945 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
946 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
947 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
948 }
949 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
950 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
951 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
952 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700953 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900954 }
955 return config;
956 }
957
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700958 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700959 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 }
961
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 public static final class Lifecycle extends SystemService {
963 private final ActivityTaskManagerService mService;
964
965 public Lifecycle(Context context) {
966 super(context);
967 mService = new ActivityTaskManagerService(context);
968 }
969
970 @Override
971 public void onStart() {
972 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700973 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700974 }
975
Garfield Tan891146c2018-10-09 12:14:00 -0700976 @Override
977 public void onUnlockUser(int userId) {
978 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800979 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700980 }
981 }
982
983 @Override
984 public void onCleanupUser(int userId) {
985 synchronized (mService.getGlobalLock()) {
986 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
987 }
988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public ActivityTaskManagerService getService() {
991 return mService;
992 }
993 }
994
995 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 public final int startActivity(IApplicationThread caller, String callingPackage,
997 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
998 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
999 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1000 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1001 UserHandle.getCallingUserId());
1002 }
1003
1004 @Override
1005 public final int startActivities(IApplicationThread caller, String callingPackage,
1006 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1007 int userId) {
1008 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001009 enforceNotIsolatedCaller(reason);
1010 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001011 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001012 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1013 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1014 reason, null /* originatingPendingIntent */,
1015 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017
1018 @Override
1019 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1020 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1021 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1022 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1023 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1024 true /*validateIncomingUser*/);
1025 }
1026
1027 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1030 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001031 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001033 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1035
1036 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001037 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 .setCaller(caller)
1039 .setCallingPackage(callingPackage)
1040 .setResolvedType(resolvedType)
1041 .setResultTo(resultTo)
1042 .setResultWho(resultWho)
1043 .setRequestCode(requestCode)
1044 .setStartFlags(startFlags)
1045 .setProfilerInfo(profilerInfo)
1046 .setActivityOptions(bOptions)
1047 .setMayWait(userId)
1048 .execute();
1049
1050 }
1051
1052 @Override
1053 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1054 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001055 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1056 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001057 // Refuse possible leaked file descriptors
1058 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1059 throw new IllegalArgumentException("File descriptors passed in Intent");
1060 }
1061
1062 if (!(target instanceof PendingIntentRecord)) {
1063 throw new IllegalArgumentException("Bad PendingIntent object");
1064 }
1065
1066 PendingIntentRecord pir = (PendingIntentRecord)target;
1067
1068 synchronized (mGlobalLock) {
1069 // If this is coming from the currently resumed activity, it is
1070 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001071 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 if (stack.mResumedActivity != null &&
1073 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001074 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 }
1076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001077 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 }
1080
1081 @Override
1082 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1083 Bundle bOptions) {
1084 // Refuse possible leaked file descriptors
1085 if (intent != null && intent.hasFileDescriptors()) {
1086 throw new IllegalArgumentException("File descriptors passed in Intent");
1087 }
1088 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1089
1090 synchronized (mGlobalLock) {
1091 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1092 if (r == null) {
1093 SafeActivityOptions.abort(options);
1094 return false;
1095 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001096 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 // The caller is not running... d'oh!
1098 SafeActivityOptions.abort(options);
1099 return false;
1100 }
1101 intent = new Intent(intent);
1102 // The caller is not allowed to change the data.
1103 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1104 // And we are resetting to find the next component...
1105 intent.setComponent(null);
1106
1107 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1108
1109 ActivityInfo aInfo = null;
1110 try {
1111 List<ResolveInfo> resolves =
1112 AppGlobals.getPackageManager().queryIntentActivities(
1113 intent, r.resolvedType,
1114 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1115 UserHandle.getCallingUserId()).getList();
1116
1117 // Look for the original activity in the list...
1118 final int N = resolves != null ? resolves.size() : 0;
1119 for (int i=0; i<N; i++) {
1120 ResolveInfo rInfo = resolves.get(i);
1121 if (rInfo.activityInfo.packageName.equals(r.packageName)
1122 && rInfo.activityInfo.name.equals(r.info.name)) {
1123 // We found the current one... the next matching is
1124 // after it.
1125 i++;
1126 if (i<N) {
1127 aInfo = resolves.get(i).activityInfo;
1128 }
1129 if (debug) {
1130 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1131 + "/" + r.info.name);
1132 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1133 ? "null" : aInfo.packageName + "/" + aInfo.name));
1134 }
1135 break;
1136 }
1137 }
1138 } catch (RemoteException e) {
1139 }
1140
1141 if (aInfo == null) {
1142 // Nobody who is next!
1143 SafeActivityOptions.abort(options);
1144 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1145 return false;
1146 }
1147
1148 intent.setComponent(new ComponentName(
1149 aInfo.applicationInfo.packageName, aInfo.name));
1150 intent.setFlags(intent.getFlags()&~(
1151 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1152 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1153 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1154 FLAG_ACTIVITY_NEW_TASK));
1155
1156 // Okay now we need to start the new activity, replacing the currently running activity.
1157 // This is a little tricky because we want to start the new one as if the current one is
1158 // finished, but not finish the current one first so that there is no flicker.
1159 // And thus...
1160 final boolean wasFinishing = r.finishing;
1161 r.finishing = true;
1162
1163 // Propagate reply information over to the new activity.
1164 final ActivityRecord resultTo = r.resultTo;
1165 final String resultWho = r.resultWho;
1166 final int requestCode = r.requestCode;
1167 r.resultTo = null;
1168 if (resultTo != null) {
1169 resultTo.removeResultsLocked(r, resultWho, requestCode);
1170 }
1171
1172 final long origId = Binder.clearCallingIdentity();
1173 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001174 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001176 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .setResolvedType(r.resolvedType)
1178 .setActivityInfo(aInfo)
1179 .setResultTo(resultTo != null ? resultTo.appToken : null)
1180 .setResultWho(resultWho)
1181 .setRequestCode(requestCode)
1182 .setCallingPid(-1)
1183 .setCallingUid(r.launchedFromUid)
1184 .setCallingPackage(r.launchedFromPackage)
1185 .setRealCallingPid(-1)
1186 .setRealCallingUid(r.launchedFromUid)
1187 .setActivityOptions(options)
1188 .execute();
1189 Binder.restoreCallingIdentity(origId);
1190
1191 r.finishing = wasFinishing;
1192 if (res != ActivityManager.START_SUCCESS) {
1193 return false;
1194 }
1195 return true;
1196 }
1197 }
1198
1199 @Override
1200 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1201 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1202 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1203 final WaitResult res = new WaitResult();
1204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001205 enforceNotIsolatedCaller("startActivityAndWait");
1206 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1207 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001209 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .setCaller(caller)
1211 .setCallingPackage(callingPackage)
1212 .setResolvedType(resolvedType)
1213 .setResultTo(resultTo)
1214 .setResultWho(resultWho)
1215 .setRequestCode(requestCode)
1216 .setStartFlags(startFlags)
1217 .setActivityOptions(bOptions)
1218 .setMayWait(userId)
1219 .setProfilerInfo(profilerInfo)
1220 .setWaitResult(res)
1221 .execute();
1222 }
1223 return res;
1224 }
1225
1226 @Override
1227 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1228 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1229 int startFlags, Configuration config, Bundle bOptions, int userId) {
1230 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001231 enforceNotIsolatedCaller("startActivityWithConfig");
1232 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1233 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001234 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001235 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 .setCaller(caller)
1237 .setCallingPackage(callingPackage)
1238 .setResolvedType(resolvedType)
1239 .setResultTo(resultTo)
1240 .setResultWho(resultWho)
1241 .setRequestCode(requestCode)
1242 .setStartFlags(startFlags)
1243 .setGlobalConfiguration(config)
1244 .setActivityOptions(bOptions)
1245 .setMayWait(userId)
1246 .execute();
1247 }
1248 }
1249
Alison Cichowlas3e340502018-08-07 17:15:01 -04001250
1251 @Override
1252 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1253 int callingUid = Binder.getCallingUid();
1254 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1255 throw new SecurityException("Only the system process can request a permission token, "
1256 + "received request from uid: " + callingUid);
1257 }
1258 IBinder permissionToken = new Binder();
1259 synchronized (mGlobalLock) {
1260 mStartActivitySources.put(permissionToken, delegatorToken);
1261 }
1262
1263 Message expireMsg = PooledLambda.obtainMessage(
1264 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1265 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1266
1267 Message forgetMsg = PooledLambda.obtainMessage(
1268 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1269 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1270
1271 return permissionToken;
1272 }
1273
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 @Override
1275 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1276 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1278 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001280 // permission grants) as any app that may launch one of your own activities. So we only
1281 // allow this in two cases:
1282 // 1) The caller is an activity that is part of the core framework, and then only when it
1283 // is running as the system.
1284 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1285 // can only be requested by a system activity, which may then delegate this call to
1286 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 final ActivityRecord sourceRecord;
1288 final int targetUid;
1289 final String targetPackage;
1290 final boolean isResolver;
1291 synchronized (mGlobalLock) {
1292 if (resultTo == null) {
1293 throw new SecurityException("Must be called from an activity");
1294 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 final IBinder sourceToken;
1296 if (permissionToken != null) {
1297 // To even attempt to use a permissionToken, an app must also have this signature
1298 // permission.
1299 mAmInternal.enforceCallingPermission(
1300 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1301 "startActivityAsCaller");
1302 // If called with a permissionToken, we want the sourceRecord from the delegator
1303 // activity that requested this token.
1304 sourceToken = mStartActivitySources.remove(permissionToken);
1305 if (sourceToken == null) {
1306 // Invalid permissionToken, check if it recently expired.
1307 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1308 throw new SecurityException("Called with expired permission token: "
1309 + permissionToken);
1310 } else {
1311 throw new SecurityException("Called with invalid permission token: "
1312 + permissionToken);
1313 }
1314 }
1315 } else {
1316 // This method was called directly by the source.
1317 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001318 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319
Wale Ogunwaled32da472018-11-16 07:19:28 -08001320 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001321 if (sourceRecord == null) {
1322 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 }
1324 if (sourceRecord.app == null) {
1325 throw new SecurityException("Called without a process attached to activity");
1326 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327
1328 // Whether called directly or from a delegate, the source activity must be from the
1329 // android package.
1330 if (!sourceRecord.info.packageName.equals("android")) {
1331 throw new SecurityException("Must be called from an activity that is "
1332 + "declared in the android package");
1333 }
1334
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001335 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 // This is still okay, as long as this activity is running under the
1337 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001338 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 + " must be system uid or original calling uid "
1342 + sourceRecord.launchedFromUid);
1343 }
1344 }
1345 if (ignoreTargetSecurity) {
1346 if (intent.getComponent() == null) {
1347 throw new SecurityException(
1348 "Component must be specified with ignoreTargetSecurity");
1349 }
1350 if (intent.getSelector() != null) {
1351 throw new SecurityException(
1352 "Selector not allowed with ignoreTargetSecurity");
1353 }
1354 }
1355 targetUid = sourceRecord.launchedFromUid;
1356 targetPackage = sourceRecord.launchedFromPackage;
1357 isResolver = sourceRecord.isResolverOrChildActivity();
1358 }
1359
1360 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001361 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 }
1363
1364 // TODO: Switch to user app stacks here.
1365 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001366 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367 .setCallingUid(targetUid)
1368 .setCallingPackage(targetPackage)
1369 .setResolvedType(resolvedType)
1370 .setResultTo(resultTo)
1371 .setResultWho(resultWho)
1372 .setRequestCode(requestCode)
1373 .setStartFlags(startFlags)
1374 .setActivityOptions(bOptions)
1375 .setMayWait(userId)
1376 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1377 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1378 .execute();
1379 } catch (SecurityException e) {
1380 // XXX need to figure out how to propagate to original app.
1381 // A SecurityException here is generally actually a fault of the original
1382 // calling activity (such as a fairly granting permissions), so propagate it
1383 // back to them.
1384 /*
1385 StringBuilder msg = new StringBuilder();
1386 msg.append("While launching");
1387 msg.append(intent.toString());
1388 msg.append(": ");
1389 msg.append(e.getMessage());
1390 */
1391 throw e;
1392 }
1393 }
1394
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001395 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1396 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1397 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1398 }
1399
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 @Override
1401 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1402 Intent intent, String resolvedType, IVoiceInteractionSession session,
1403 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1404 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001405 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 if (session == null || interactor == null) {
1407 throw new NullPointerException("null session or interactor");
1408 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001411 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 .setCallingUid(callingUid)
1413 .setCallingPackage(callingPackage)
1414 .setResolvedType(resolvedType)
1415 .setVoiceSession(session)
1416 .setVoiceInteractor(interactor)
1417 .setStartFlags(startFlags)
1418 .setProfilerInfo(profilerInfo)
1419 .setActivityOptions(bOptions)
1420 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001421 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 .execute();
1423 }
1424
1425 @Override
1426 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1427 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1429 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001431 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 .setCallingUid(callingUid)
1433 .setCallingPackage(callingPackage)
1434 .setResolvedType(resolvedType)
1435 .setActivityOptions(bOptions)
1436 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001437 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 .execute();
1439 }
1440
1441 @Override
1442 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1443 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001444 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 final int callingPid = Binder.getCallingPid();
1446 final long origId = Binder.clearCallingIdentity();
1447 try {
1448 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001449 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1450 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451
1452 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1454 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1456 recentsUid, assistDataReceiver);
1457 }
1458 } finally {
1459 Binder.restoreCallingIdentity(origId);
1460 }
1461 }
1462
1463 @Override
1464 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 "startActivityFromRecents()");
1467
1468 final int callingPid = Binder.getCallingPid();
1469 final int callingUid = Binder.getCallingUid();
1470 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1471 final long origId = Binder.clearCallingIdentity();
1472 try {
1473 synchronized (mGlobalLock) {
1474 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1475 safeOptions);
1476 }
1477 } finally {
1478 Binder.restoreCallingIdentity(origId);
1479 }
1480 }
1481
1482 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001483 * Public API to check if the client is allowed to start an activity on specified display.
1484 *
1485 * If the target display is private or virtual, some restrictions will apply.
1486 *
1487 * @param displayId Target display id.
1488 * @param intent Intent used to launch the activity.
1489 * @param resolvedType The MIME type of the intent.
1490 * @param userId The id of the user for whom the call is made.
1491 * @return {@code true} if a call to start an activity on the target display should succeed and
1492 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1493 */
1494 @Override
1495 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1496 String resolvedType, int userId) {
1497 final int callingUid = Binder.getCallingUid();
1498 final int callingPid = Binder.getCallingPid();
1499 final long origId = Binder.clearCallingIdentity();
1500
1501 try {
1502 // Collect information about the target of the Intent.
1503 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1504 0 /* startFlags */, null /* profilerInfo */, userId,
1505 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1506 UserHandle.USER_NULL));
1507 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1508
1509 synchronized (mGlobalLock) {
1510 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1511 aInfo);
1512 }
1513 } finally {
1514 Binder.restoreCallingIdentity(origId);
1515 }
1516 }
1517
1518 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 * This is the internal entry point for handling Activity.finish().
1520 *
1521 * @param token The Binder token referencing the Activity we want to finish.
1522 * @param resultCode Result code, if any, from this Activity.
1523 * @param resultData Result data (Intent), if any, from this Activity.
1524 * @param finishTask Whether to finish the task associated with this Activity.
1525 *
1526 * @return Returns true if the activity successfully finished, or false if it is still running.
1527 */
1528 @Override
1529 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1530 int finishTask) {
1531 // Refuse possible leaked file descriptors
1532 if (resultData != null && resultData.hasFileDescriptors()) {
1533 throw new IllegalArgumentException("File descriptors passed in Intent");
1534 }
1535
1536 synchronized (mGlobalLock) {
1537 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1538 if (r == null) {
1539 return true;
1540 }
1541 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001542 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001543 ActivityRecord rootR = tr.getRootActivity();
1544 if (rootR == null) {
1545 Slog.w(TAG, "Finishing task with all activities already finished");
1546 }
1547 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1548 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001549 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 return false;
1551 }
1552
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001553 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1554 // We should consolidate.
1555 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001557 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 if (next != null) {
1559 // ask watcher if this is allowed
1560 boolean resumeOK = true;
1561 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001562 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001564 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 Watchdog.getInstance().setActivityController(null);
1566 }
1567
1568 if (!resumeOK) {
1569 Slog.i(TAG, "Not finishing activity because controller resumed");
1570 return false;
1571 }
1572 }
1573 }
1574 final long origId = Binder.clearCallingIdentity();
1575 try {
1576 boolean res;
1577 final boolean finishWithRootActivity =
1578 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1579 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1580 || (finishWithRootActivity && r == rootR)) {
1581 // If requested, remove the task that is associated to this activity only if it
1582 // was the root activity in the task. The result code and data is ignored
1583 // because we don't support returning them across task boundaries. Also, to
1584 // keep backwards compatibility we remove the task from recents when finishing
1585 // task with root activity.
1586 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1587 finishWithRootActivity, "finish-activity");
1588 if (!res) {
1589 Slog.i(TAG, "Removing task failed to finish activity");
1590 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001591 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001592 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 } else {
1594 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1595 resultData, "app-request", true);
1596 if (!res) {
1597 Slog.i(TAG, "Failed to finish by app-request");
1598 }
1599 }
1600 return res;
1601 } finally {
1602 Binder.restoreCallingIdentity(origId);
1603 }
1604 }
1605 }
1606
1607 @Override
1608 public boolean finishActivityAffinity(IBinder token) {
1609 synchronized (mGlobalLock) {
1610 final long origId = Binder.clearCallingIdentity();
1611 try {
1612 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1613 if (r == null) {
1614 return false;
1615 }
1616
1617 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1618 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001619 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001620 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 return false;
1622 }
1623 return task.getStack().finishActivityAffinityLocked(r);
1624 } finally {
1625 Binder.restoreCallingIdentity(origId);
1626 }
1627 }
1628 }
1629
1630 @Override
1631 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1632 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001633 try {
1634 WindowProcessController proc = null;
1635 synchronized (mGlobalLock) {
1636 ActivityStack stack = ActivityRecord.getStackLocked(token);
1637 if (stack == null) {
1638 return;
1639 }
1640 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1641 false /* fromTimeout */, false /* processPausingActivities */, config);
1642 if (r != null) {
1643 proc = r.app;
1644 }
1645 if (stopProfiling && proc != null) {
1646 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 }
1648 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001649 } finally {
1650 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001652 }
1653
1654 @Override
1655 public final void activityResumed(IBinder token) {
1656 final long origId = Binder.clearCallingIdentity();
1657 synchronized (mGlobalLock) {
1658 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001659 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 }
1661 Binder.restoreCallingIdentity(origId);
1662 }
1663
1664 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001665 public final void activityTopResumedStateLost() {
1666 final long origId = Binder.clearCallingIdentity();
1667 synchronized (mGlobalLock) {
1668 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1669 }
1670 Binder.restoreCallingIdentity(origId);
1671 }
1672
1673 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 public final void activityPaused(IBinder token) {
1675 final long origId = Binder.clearCallingIdentity();
1676 synchronized (mGlobalLock) {
1677 ActivityStack stack = ActivityRecord.getStackLocked(token);
1678 if (stack != null) {
1679 stack.activityPausedLocked(token, false);
1680 }
1681 }
1682 Binder.restoreCallingIdentity(origId);
1683 }
1684
1685 @Override
1686 public final void activityStopped(IBinder token, Bundle icicle,
1687 PersistableBundle persistentState, CharSequence description) {
1688 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1689
1690 // Refuse possible leaked file descriptors
1691 if (icicle != null && icicle.hasFileDescriptors()) {
1692 throw new IllegalArgumentException("File descriptors passed in Bundle");
1693 }
1694
1695 final long origId = Binder.clearCallingIdentity();
1696
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001697 String restartingName = null;
1698 int restartingUid = 0;
1699 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001701 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001703 if (r.attachedToProcess()
1704 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1705 // The activity was requested to restart from
1706 // {@link #restartActivityProcessIfVisible}.
1707 restartingName = r.app.mName;
1708 restartingUid = r.app.mUid;
1709 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 r.activityStoppedLocked(icicle, persistentState, description);
1711 }
1712 }
1713
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001714 if (restartingName != null) {
1715 // In order to let the foreground activity can be restarted with its saved state from
1716 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1717 // until the activity reports stopped with the state. And the activity record will be
1718 // kept because the record state is restarting, then the activity will be restarted
1719 // immediately if it is still the top one.
1720 mStackSupervisor.removeRestartTimeouts(r);
1721 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1722 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001723 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724
1725 Binder.restoreCallingIdentity(origId);
1726 }
1727
1728 @Override
1729 public final void activityDestroyed(IBinder token) {
1730 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1731 synchronized (mGlobalLock) {
1732 ActivityStack stack = ActivityRecord.getStackLocked(token);
1733 if (stack != null) {
1734 stack.activityDestroyedLocked(token, "activityDestroyed");
1735 }
1736 }
1737 }
1738
1739 @Override
1740 public final void activityRelaunched(IBinder token) {
1741 final long origId = Binder.clearCallingIdentity();
1742 synchronized (mGlobalLock) {
1743 mStackSupervisor.activityRelaunchedLocked(token);
1744 }
1745 Binder.restoreCallingIdentity(origId);
1746 }
1747
1748 public final void activitySlept(IBinder token) {
1749 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1750
1751 final long origId = Binder.clearCallingIdentity();
1752
1753 synchronized (mGlobalLock) {
1754 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1755 if (r != null) {
1756 mStackSupervisor.activitySleptLocked(r);
1757 }
1758 }
1759
1760 Binder.restoreCallingIdentity(origId);
1761 }
1762
1763 @Override
1764 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1765 synchronized (mGlobalLock) {
1766 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1767 if (r == null) {
1768 return;
1769 }
1770 final long origId = Binder.clearCallingIdentity();
1771 try {
1772 r.setRequestedOrientation(requestedOrientation);
1773 } finally {
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776 }
1777 }
1778
1779 @Override
1780 public int getRequestedOrientation(IBinder token) {
1781 synchronized (mGlobalLock) {
1782 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1783 if (r == null) {
1784 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1785 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001786 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
1788 }
1789
1790 @Override
1791 public void setImmersive(IBinder token, boolean immersive) {
1792 synchronized (mGlobalLock) {
1793 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1794 if (r == null) {
1795 throw new IllegalArgumentException();
1796 }
1797 r.immersive = immersive;
1798
1799 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001800 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 }
1804 }
1805 }
1806
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 void applyUpdateLockStateLocked(ActivityRecord r) {
1808 // Modifications to the UpdateLock state are done on our handler, outside
1809 // the activity manager's locks. The new state is determined based on the
1810 // state *now* of the relevant activity record. The object is passed to
1811 // the handler solely for logging detail, not to be consulted/modified.
1812 final boolean nextState = r != null && r.immersive;
1813 mH.post(() -> {
1814 if (mUpdateLock.isHeld() != nextState) {
1815 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1816 "Applying new update lock state '" + nextState + "' for " + r);
1817 if (nextState) {
1818 mUpdateLock.acquire();
1819 } else {
1820 mUpdateLock.release();
1821 }
1822 }
1823 });
1824 }
1825
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 @Override
1827 public boolean isImmersive(IBinder token) {
1828 synchronized (mGlobalLock) {
1829 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1830 if (r == null) {
1831 throw new IllegalArgumentException();
1832 }
1833 return r.immersive;
1834 }
1835 }
1836
1837 @Override
1838 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001841 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 return (r != null) ? r.immersive : false;
1843 }
1844 }
1845
1846 @Override
1847 public void overridePendingTransition(IBinder token, String packageName,
1848 int enterAnim, int exitAnim) {
1849 synchronized (mGlobalLock) {
1850 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1851 if (self == null) {
1852 return;
1853 }
1854
1855 final long origId = Binder.clearCallingIdentity();
1856
1857 if (self.isState(
1858 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001859 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001860 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
1862
1863 Binder.restoreCallingIdentity(origId);
1864 }
1865 }
1866
1867 @Override
1868 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001871 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001872 if (r == null) {
1873 return ActivityManager.COMPAT_MODE_UNKNOWN;
1874 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001875 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 }
1877 }
1878
1879 @Override
1880 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001881 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001882 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001883 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001885 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 if (r == null) {
1887 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1888 return;
1889 }
1890 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001891 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 }
1893 }
1894
1895 @Override
1896 public int getLaunchedFromUid(IBinder activityToken) {
1897 ActivityRecord srec;
1898 synchronized (mGlobalLock) {
1899 srec = ActivityRecord.forTokenLocked(activityToken);
1900 }
1901 if (srec == null) {
1902 return -1;
1903 }
1904 return srec.launchedFromUid;
1905 }
1906
1907 @Override
1908 public String getLaunchedFromPackage(IBinder activityToken) {
1909 ActivityRecord srec;
1910 synchronized (mGlobalLock) {
1911 srec = ActivityRecord.forTokenLocked(activityToken);
1912 }
1913 if (srec == null) {
1914 return null;
1915 }
1916 return srec.launchedFromPackage;
1917 }
1918
1919 @Override
1920 public boolean convertFromTranslucent(IBinder token) {
1921 final long origId = Binder.clearCallingIdentity();
1922 try {
1923 synchronized (mGlobalLock) {
1924 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1925 if (r == null) {
1926 return false;
1927 }
1928 final boolean translucentChanged = r.changeWindowTranslucency(true);
1929 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001930 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001933 return translucentChanged;
1934 }
1935 } finally {
1936 Binder.restoreCallingIdentity(origId);
1937 }
1938 }
1939
1940 @Override
1941 public boolean convertToTranslucent(IBinder token, Bundle options) {
1942 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1943 final long origId = Binder.clearCallingIdentity();
1944 try {
1945 synchronized (mGlobalLock) {
1946 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1947 if (r == null) {
1948 return false;
1949 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001950 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 int index = task.mActivities.lastIndexOf(r);
1952 if (index > 0) {
1953 ActivityRecord under = task.mActivities.get(index - 1);
1954 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1955 }
1956 final boolean translucentChanged = r.changeWindowTranslucency(false);
1957 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001958 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001960 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 return translucentChanged;
1963 }
1964 } finally {
1965 Binder.restoreCallingIdentity(origId);
1966 }
1967 }
1968
1969 @Override
1970 public void notifyActivityDrawn(IBinder token) {
1971 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1972 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001973 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001975 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 }
1977 }
1978 }
1979
1980 @Override
1981 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1982 synchronized (mGlobalLock) {
1983 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1984 if (r == null) {
1985 return;
1986 }
1987 r.reportFullyDrawnLocked(restoredFromBundle);
1988 }
1989 }
1990
1991 @Override
1992 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1993 synchronized (mGlobalLock) {
1994 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1995 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1996 return stack.mDisplayId;
1997 }
1998 return DEFAULT_DISPLAY;
1999 }
2000 }
2001
2002 @Override
2003 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002004 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 long ident = Binder.clearCallingIdentity();
2006 try {
2007 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002008 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002010 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 }
2012 return null;
2013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018
2019 @Override
2020 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002021 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2023 final long callingId = Binder.clearCallingIdentity();
2024 try {
2025 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002026 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 if (stack == null) {
2028 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2029 return;
2030 }
2031 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002032 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002033 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 }
2035 }
2036 } finally {
2037 Binder.restoreCallingIdentity(callingId);
2038 }
2039 }
2040
2041 @Override
2042 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002043 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2045 final long callingId = Binder.clearCallingIdentity();
2046 try {
2047 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002048 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002049 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (task == null) {
2051 return;
2052 }
2053 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002054 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002055 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 }
2057 }
2058 } finally {
2059 Binder.restoreCallingIdentity(callingId);
2060 }
2061 }
2062
2063 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002064 public void restartActivityProcessIfVisible(IBinder activityToken) {
2065 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2066 final long callingId = Binder.clearCallingIdentity();
2067 try {
2068 synchronized (mGlobalLock) {
2069 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2070 if (r == null) {
2071 return;
2072 }
2073 r.restartProcessIfVisible();
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(callingId);
2077 }
2078 }
2079
2080 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002082 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002083 synchronized (mGlobalLock) {
2084 final long ident = Binder.clearCallingIdentity();
2085 try {
2086 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2087 "remove-task");
2088 } finally {
2089 Binder.restoreCallingIdentity(ident);
2090 }
2091 }
2092 }
2093
2094 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002095 public void removeAllVisibleRecentTasks() {
2096 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2097 synchronized (mGlobalLock) {
2098 final long ident = Binder.clearCallingIdentity();
2099 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002100 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
2104 }
2105 }
2106
2107 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2111 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002112 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 }
2114 }
2115 return false;
2116 }
2117
2118 @Override
2119 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2120 Intent resultData) {
2121
2122 synchronized (mGlobalLock) {
2123 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2124 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002125 return r.getActivityStack().navigateUpToLocked(
2126 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 }
2128 return false;
2129 }
2130 }
2131
2132 /**
2133 * Attempts to move a task backwards in z-order (the order of activities within the task is
2134 * unchanged).
2135 *
2136 * There are several possible results of this call:
2137 * - if the task is locked, then we will show the lock toast
2138 * - if there is a task behind the provided task, then that task is made visible and resumed as
2139 * this task is moved to the back
2140 * - otherwise, if there are no other tasks in the stack:
2141 * - if this task is in the pinned stack, then we remove the stack completely, which will
2142 * have the effect of moving the task to the top or bottom of the fullscreen stack
2143 * (depending on whether it is visible)
2144 * - otherwise, we simply return home and hide this task
2145 *
2146 * @param token A reference to the activity we wish to move
2147 * @param nonRoot If false then this only works if the activity is the root
2148 * of a task; if true it will work for any activity in a task.
2149 * @return Returns true if the move completed, false if not.
2150 */
2151 @Override
2152 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002153 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 synchronized (mGlobalLock) {
2155 final long origId = Binder.clearCallingIdentity();
2156 try {
2157 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002158 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 if (task != null) {
2160 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2161 }
2162 } finally {
2163 Binder.restoreCallingIdentity(origId);
2164 }
2165 }
2166 return false;
2167 }
2168
2169 @Override
2170 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002171 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 long ident = Binder.clearCallingIdentity();
2173 Rect rect = new Rect();
2174 try {
2175 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002176 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2178 if (task == null) {
2179 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2180 return rect;
2181 }
2182 if (task.getStack() != null) {
2183 // Return the bounds from window manager since it will be adjusted for various
2184 // things like the presense of a docked stack for tasks that aren't resizeable.
2185 task.getWindowContainerBounds(rect);
2186 } else {
2187 // Task isn't in window manager yet since it isn't associated with a stack.
2188 // Return the persist value from activity manager
2189 if (!task.matchParentBounds()) {
2190 rect.set(task.getBounds());
2191 } else if (task.mLastNonFullscreenBounds != null) {
2192 rect.set(task.mLastNonFullscreenBounds);
2193 }
2194 }
2195 }
2196 } finally {
2197 Binder.restoreCallingIdentity(ident);
2198 }
2199 return rect;
2200 }
2201
2202 @Override
2203 public ActivityManager.TaskDescription getTaskDescription(int id) {
2204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002205 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002207 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2209 if (tr != null) {
2210 return tr.lastTaskDescription;
2211 }
2212 }
2213 return null;
2214 }
2215
2216 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002217 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2218 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2219 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2220 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2221 return;
2222 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002223 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002224 synchronized (mGlobalLock) {
2225 final long ident = Binder.clearCallingIdentity();
2226 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002227 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002228 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002229 if (task == null) {
2230 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2231 return;
2232 }
2233
2234 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2235 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2236
2237 if (!task.isActivityTypeStandardOrUndefined()) {
2238 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2239 + " non-standard task " + taskId + " to windowing mode="
2240 + windowingMode);
2241 }
2242
2243 final ActivityStack stack = task.getStack();
2244 if (toTop) {
2245 stack.moveToFront("setTaskWindowingMode", task);
2246 }
2247 stack.setWindowingMode(windowingMode);
2248 } finally {
2249 Binder.restoreCallingIdentity(ident);
2250 }
2251 }
2252 }
2253
2254 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002255 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 ActivityRecord r = getCallingRecordLocked(token);
2258 return r != null ? r.info.packageName : null;
2259 }
2260 }
2261
2262 @Override
2263 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002264 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265 ActivityRecord r = getCallingRecordLocked(token);
2266 return r != null ? r.intent.getComponent() : null;
2267 }
2268 }
2269
2270 private ActivityRecord getCallingRecordLocked(IBinder token) {
2271 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2272 if (r == null) {
2273 return null;
2274 }
2275 return r.resultTo;
2276 }
2277
2278 @Override
2279 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002280 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002281
2282 synchronized (mGlobalLock) {
2283 final long origId = Binder.clearCallingIdentity();
2284 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002285 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 } finally {
2287 Binder.restoreCallingIdentity(origId);
2288 }
2289 }
2290 }
2291
Mark Renouf446251d2019-04-26 10:22:41 -04002292 @Override
2293 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2294 synchronized (mGlobalLock) {
2295 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2296 if (r == null) {
2297 return;
2298 }
2299 ActivityStack stack = r.getActivityStack();
2300 if (stack != null && stack.isSingleTaskInstance()) {
2301 // Single-task stacks are used for activities which are presented in floating
2302 // windows above full screen activities. Instead of directly finishing the
2303 // task, a task change listener is used to notify SystemUI so the action can be
2304 // handled specially.
2305 final TaskRecord task = r.getTaskRecord();
2306 mTaskChangeNotificationController
2307 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2308 } else {
2309 try {
2310 callback.requestFinish();
2311 } catch (RemoteException e) {
2312 Slog.e(TAG, "Failed to invoke request finish callback", e);
2313 }
2314 }
2315 }
2316 }
2317
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 /**
2319 * TODO: Add mController hook
2320 */
2321 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002322 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2323 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002324 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002325
2326 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2327 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002328 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2329 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002330 }
2331 }
2332
Ricky Waiaca8a772019-04-04 16:01:06 +01002333 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2334 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335 boolean fromRecents) {
2336
Ricky Waiaca8a772019-04-04 16:01:06 +01002337 final int callingPid = Binder.getCallingPid();
2338 final int callingUid = Binder.getCallingUid();
2339 if (!isSameApp(callingUid, callingPackage)) {
2340 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2341 + Binder.getCallingPid() + " as package " + callingPackage;
2342 Slog.w(TAG, msg);
2343 throw new SecurityException(msg);
2344 }
2345 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002346 SafeActivityOptions.abort(options);
2347 return;
2348 }
2349 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002350 WindowProcessController callerApp = null;
2351 if (appThread != null) {
2352 callerApp = getProcessController(appThread);
2353 }
2354 final ActivityStarter starter = getActivityStartController().obtainStarter(
2355 null /* intent */, "moveTaskToFront");
2356 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2357 -1, callerApp, null, false, null)) {
2358 boolean abort = !isBackgroundActivityStartsEnabled();
2359 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2360 if (abort) {
2361 return;
2362 }
2363 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002365 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 if (task == null) {
2367 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002368 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 return;
2370 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002371 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002373 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 return;
2375 }
2376 ActivityOptions realOptions = options != null
2377 ? options.getOptions(mStackSupervisor)
2378 : null;
2379 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2380 false /* forceNonResizable */);
2381
2382 final ActivityRecord topActivity = task.getTopActivity();
2383 if (topActivity != null) {
2384
2385 // We are reshowing a task, use a starting window to hide the initial draw delay
2386 // so the transition can start earlier.
2387 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2388 true /* taskSwitch */, fromRecents);
2389 }
2390 } finally {
2391 Binder.restoreCallingIdentity(origId);
2392 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 }
2394
Ricky Waiaca8a772019-04-04 16:01:06 +01002395 /**
2396 * Return true if callingUid is system, or packageName belongs to that callingUid.
2397 */
2398 boolean isSameApp(int callingUid, @Nullable String packageName) {
2399 try {
2400 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2401 if (packageName == null) {
2402 return false;
2403 }
2404 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2405 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2406 UserHandle.getUserId(callingUid));
2407 return UserHandle.isSameApp(callingUid, uid);
2408 }
2409 } catch (RemoteException e) {
2410 // Should not happen
2411 }
2412 return true;
2413 }
2414
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2416 int callingPid, int callingUid, String name) {
2417 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2418 return true;
2419 }
2420
2421 if (getRecentTasks().isCallerRecents(sourceUid)) {
2422 return true;
2423 }
2424
2425 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2426 if (perm == PackageManager.PERMISSION_GRANTED) {
2427 return true;
2428 }
2429 if (checkAllowAppSwitchUid(sourceUid)) {
2430 return true;
2431 }
2432
2433 // If the actual IPC caller is different from the logical source, then
2434 // also see if they are allowed to control app switches.
2435 if (callingUid != -1 && callingUid != sourceUid) {
2436 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2437 if (perm == PackageManager.PERMISSION_GRANTED) {
2438 return true;
2439 }
2440 if (checkAllowAppSwitchUid(callingUid)) {
2441 return true;
2442 }
2443 }
2444
2445 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2446 return false;
2447 }
2448
2449 private boolean checkAllowAppSwitchUid(int uid) {
2450 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2451 if (types != null) {
2452 for (int i = types.size() - 1; i >= 0; i--) {
2453 if (types.valueAt(i).intValue() == uid) {
2454 return true;
2455 }
2456 }
2457 }
2458 return false;
2459 }
2460
2461 @Override
2462 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2463 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2464 "setActivityController()");
2465 synchronized (mGlobalLock) {
2466 mController = controller;
2467 mControllerIsAMonkey = imAMonkey;
2468 Watchdog.getInstance().setActivityController(controller);
2469 }
2470 }
2471
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002472 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002473 synchronized (mGlobalLock) {
2474 return mController != null && mControllerIsAMonkey;
2475 }
2476 }
2477
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002478 @Override
2479 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2480 synchronized (mGlobalLock) {
2481 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2482 }
2483 }
2484
2485 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002486 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2487 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2488 }
2489
2490 @Override
2491 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2492 @WindowConfiguration.ActivityType int ignoreActivityType,
2493 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2494 final int callingUid = Binder.getCallingUid();
2495 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2496
2497 synchronized (mGlobalLock) {
2498 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2499
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002500 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002501 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002502 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002503 ignoreWindowingMode, callingUid, allowed);
2504 }
2505
2506 return list;
2507 }
2508
2509 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2511 synchronized (mGlobalLock) {
2512 final long origId = Binder.clearCallingIdentity();
2513 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2514 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002515 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002516 }
2517 Binder.restoreCallingIdentity(origId);
2518 }
2519 }
2520
2521 @Override
2522 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 ActivityStack stack = ActivityRecord.getStackLocked(token);
2525 if (stack != null) {
2526 return stack.willActivityBeVisibleLocked(token);
2527 }
2528 return false;
2529 }
2530 }
2531
2532 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002533 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002534 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 synchronized (mGlobalLock) {
2536 final long ident = Binder.clearCallingIdentity();
2537 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002538 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 if (task == null) {
2540 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2541 return;
2542 }
2543
2544 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2545 + " to stackId=" + stackId + " toTop=" + toTop);
2546
Wale Ogunwaled32da472018-11-16 07:19:28 -08002547 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002548 if (stack == null) {
2549 throw new IllegalStateException(
2550 "moveTaskToStack: No stack for stackId=" + stackId);
2551 }
2552 if (!stack.isActivityTypeStandardOrUndefined()) {
2553 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2554 + taskId + " to stack " + stackId);
2555 }
2556 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2559 }
2560 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2561 "moveTaskToStack");
2562 } finally {
2563 Binder.restoreCallingIdentity(ident);
2564 }
2565 }
2566 }
2567
2568 @Override
2569 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2570 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572
2573 final long ident = Binder.clearCallingIdentity();
2574 try {
2575 synchronized (mGlobalLock) {
2576 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002577 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 if (stack == null) {
2579 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2580 return;
2581 }
2582 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2583 throw new IllegalArgumentException("Stack: " + stackId
2584 + " doesn't support animated resize.");
2585 }
2586 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2587 animationDuration, false /* fromFullscreen */);
2588 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002589 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590 if (stack == null) {
2591 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2592 return;
2593 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002595 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2596 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2597 }
2598 }
2599 } finally {
2600 Binder.restoreCallingIdentity(ident);
2601 }
2602 }
2603
wilsonshih5c4cf522019-01-25 09:03:47 +08002604 @Override
2605 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2606 int animationDuration) {
2607 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2608
2609 final long ident = Binder.clearCallingIdentity();
2610 try {
2611 synchronized (mGlobalLock) {
2612 if (xOffset == 0 && yOffset == 0) {
2613 return;
2614 }
2615 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2616 if (stack == null) {
2617 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2618 return;
2619 }
2620 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2621 throw new IllegalArgumentException("Stack: " + stackId
2622 + " doesn't support animated resize.");
2623 }
2624 final Rect destBounds = new Rect();
2625 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002626 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002627 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2628 return;
2629 }
2630 destBounds.offset(xOffset, yOffset);
2631 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2632 animationDuration, false /* fromFullscreen */);
2633 }
2634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 /**
2639 * Moves the specified task to the primary-split-screen stack.
2640 *
2641 * @param taskId Id of task to move.
2642 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2643 * exist already. See
2644 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2645 * and
2646 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2647 * @param toTop If the task and stack should be moved to the top.
2648 * @param animate Whether we should play an animation for the moving the task.
2649 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2650 * stack. Pass {@code null} to use default bounds.
2651 * @param showRecents If the recents activity should be shown on the other side of the task
2652 * going into split-screen mode.
2653 */
2654 @Override
2655 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2656 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002657 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002658 "setTaskWindowingModeSplitScreenPrimary()");
2659 synchronized (mGlobalLock) {
2660 final long ident = Binder.clearCallingIdentity();
2661 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002662 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002663 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 if (task == null) {
2665 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2666 return false;
2667 }
2668 if (DEBUG_STACK) Slog.d(TAG_STACK,
2669 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2670 + " to createMode=" + createMode + " toTop=" + toTop);
2671 if (!task.isActivityTypeStandardOrUndefined()) {
2672 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2673 + " non-standard task " + taskId + " to split-screen windowing mode");
2674 }
2675
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002676 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002677 final int windowingMode = task.getWindowingMode();
2678 final ActivityStack stack = task.getStack();
2679 if (toTop) {
2680 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2681 }
2682 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002683 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2684 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 return windowingMode != task.getWindowingMode();
2686 } finally {
2687 Binder.restoreCallingIdentity(ident);
2688 }
2689 }
2690 }
2691
2692 /**
2693 * Removes stacks in the input windowing modes from the system if they are of activity type
2694 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2695 */
2696 @Override
2697 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002698 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 "removeStacksInWindowingModes()");
2700
2701 synchronized (mGlobalLock) {
2702 final long ident = Binder.clearCallingIdentity();
2703 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002704 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 } finally {
2706 Binder.restoreCallingIdentity(ident);
2707 }
2708 }
2709 }
2710
2711 @Override
2712 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002713 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002714 "removeStacksWithActivityTypes()");
2715
2716 synchronized (mGlobalLock) {
2717 final long ident = Binder.clearCallingIdentity();
2718 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002719 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 } finally {
2721 Binder.restoreCallingIdentity(ident);
2722 }
2723 }
2724 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002725
2726 @Override
2727 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2728 int userId) {
2729 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002730 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2731 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002732 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 final boolean detailed = checkGetTasksPermission(
2734 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2735 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 == PackageManager.PERMISSION_GRANTED;
2737
2738 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002739 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 callingUid);
2741 }
2742 }
2743
2744 @Override
2745 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002746 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 long ident = Binder.clearCallingIdentity();
2748 try {
2749 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002750 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 }
2752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756
2757 @Override
2758 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 long ident = Binder.clearCallingIdentity();
2761 try {
2762 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002763 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 }
2765 } finally {
2766 Binder.restoreCallingIdentity(ident);
2767 }
2768 }
2769
2770 @Override
2771 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 final long callingUid = Binder.getCallingUid();
2774 final long origId = Binder.clearCallingIdentity();
2775 try {
2776 synchronized (mGlobalLock) {
2777 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002778 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2780 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2781 }
2782 } finally {
2783 Binder.restoreCallingIdentity(origId);
2784 }
2785 }
2786
2787 @Override
2788 public void startLockTaskModeByToken(IBinder token) {
2789 synchronized (mGlobalLock) {
2790 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2791 if (r == null) {
2792 return;
2793 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002794 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 }
2797
2798 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002799 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 // This makes inner call to look as if it was initiated by system.
2802 long ident = Binder.clearCallingIdentity();
2803 try {
2804 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002805 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002806 MATCH_TASK_IN_STACKS_ONLY);
2807 if (task == null) {
2808 return;
2809 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810
2811 // When starting lock task mode the stack must be in front and focused
2812 task.getStack().moveToFront("startSystemLockTaskMode");
2813 startLockTaskModeLocked(task, true /* isSystemCaller */);
2814 }
2815 } finally {
2816 Binder.restoreCallingIdentity(ident);
2817 }
2818 }
2819
2820 @Override
2821 public void stopLockTaskModeByToken(IBinder token) {
2822 synchronized (mGlobalLock) {
2823 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2824 if (r == null) {
2825 return;
2826 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002827 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 }
2829 }
2830
2831 /**
2832 * This API should be called by SystemUI only when user perform certain action to dismiss
2833 * lock task mode. We should only dismiss pinned lock task mode in this case.
2834 */
2835 @Override
2836 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002837 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2839 }
2840
2841 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2842 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2843 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2844 return;
2845 }
2846
Wale Ogunwaled32da472018-11-16 07:19:28 -08002847 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 if (stack == null || task != stack.topTask()) {
2849 throw new IllegalArgumentException("Invalid task, not in foreground");
2850 }
2851
2852 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2853 // system or a specific app.
2854 // * System-initiated requests will only start the pinned mode (screen pinning)
2855 // * App-initiated requests
2856 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2857 // - will start the pinned mode, otherwise
2858 final int callingUid = Binder.getCallingUid();
2859 long ident = Binder.clearCallingIdentity();
2860 try {
2861 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002862 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002864 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865 } finally {
2866 Binder.restoreCallingIdentity(ident);
2867 }
2868 }
2869
2870 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2871 final int callingUid = Binder.getCallingUid();
2872 long ident = Binder.clearCallingIdentity();
2873 try {
2874 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002875 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 }
2877 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2878 // task and jumping straight into a call in the case of emergency call back.
2879 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2880 if (tm != null) {
2881 tm.showInCallScreen(false);
2882 }
2883 } finally {
2884 Binder.restoreCallingIdentity(ident);
2885 }
2886 }
2887
2888 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002889 public void updateLockTaskPackages(int userId, String[] packages) {
2890 final int callingUid = Binder.getCallingUid();
2891 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2892 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2893 "updateLockTaskPackages()");
2894 }
2895 synchronized (this) {
2896 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2897 + Arrays.toString(packages));
2898 getLockTaskController().updateLockTaskPackages(userId, packages);
2899 }
2900 }
2901
2902 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 public boolean isInLockTaskMode() {
2904 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2905 }
2906
2907 @Override
2908 public int getLockTaskModeState() {
2909 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002910 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 }
2912 }
2913
2914 @Override
2915 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2916 synchronized (mGlobalLock) {
2917 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2918 if (r != null) {
2919 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002920 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002922 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 }
2924 }
2925 }
2926
2927 @Override
2928 public Bundle getActivityOptions(IBinder token) {
2929 final long origId = Binder.clearCallingIdentity();
2930 try {
2931 synchronized (mGlobalLock) {
2932 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2933 if (r != null) {
2934 final ActivityOptions activityOptions = r.takeOptionsLocked();
2935 return activityOptions == null ? null : activityOptions.toBundle();
2936 }
2937 return null;
2938 }
2939 } finally {
2940 Binder.restoreCallingIdentity(origId);
2941 }
2942 }
2943
2944 @Override
2945 public List<IBinder> getAppTasks(String callingPackage) {
2946 int callingUid = Binder.getCallingUid();
2947 long ident = Binder.clearCallingIdentity();
2948 try {
2949 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002950 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 }
2952 } finally {
2953 Binder.restoreCallingIdentity(ident);
2954 }
2955 }
2956
2957 @Override
2958 public void finishVoiceTask(IVoiceInteractionSession session) {
2959 synchronized (mGlobalLock) {
2960 final long origId = Binder.clearCallingIdentity();
2961 try {
2962 // TODO: VI Consider treating local voice interactions and voice tasks
2963 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002964 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 } finally {
2966 Binder.restoreCallingIdentity(origId);
2967 }
2968 }
2969
2970 }
2971
2972 @Override
2973 public boolean isTopOfTask(IBinder token) {
2974 synchronized (mGlobalLock) {
2975 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002976 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 }
2978 }
2979
2980 @Override
2981 public void notifyLaunchTaskBehindComplete(IBinder token) {
2982 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2983 }
2984
2985 @Override
2986 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002987 mH.post(() -> {
2988 synchronized (mGlobalLock) {
2989 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002990 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002991 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002992 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002993 } catch (RemoteException e) {
2994 }
2995 }
2996 }
2997
2998 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 }
3000
3001 /** Called from an app when assist data is ready. */
3002 @Override
3003 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3004 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003005 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 synchronized (pae) {
3007 pae.result = extras;
3008 pae.structure = structure;
3009 pae.content = content;
3010 if (referrer != null) {
3011 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3012 }
3013 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003014 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003015 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3016 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003017 structure.setHomeActivity(pae.isHome);
3018 }
3019 pae.haveResult = true;
3020 pae.notifyAll();
3021 if (pae.intent == null && pae.receiver == null) {
3022 // Caller is just waiting for the result.
3023 return;
3024 }
3025 }
3026 // We are now ready to launch the assist activity.
3027 IAssistDataReceiver sendReceiver = null;
3028 Bundle sendBundle = null;
3029 synchronized (mGlobalLock) {
3030 buildAssistBundleLocked(pae, extras);
3031 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003032 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 if (!exists) {
3034 // Timed out.
3035 return;
3036 }
3037
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003038 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 // Caller wants result sent back to them.
3040 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003041 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3042 pae.activity.getTaskRecord().taskId);
3043 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3044 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3046 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3047 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3048 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3049 }
3050 }
3051 if (sendReceiver != null) {
3052 try {
3053 sendReceiver.onHandleAssistData(sendBundle);
3054 } catch (RemoteException e) {
3055 }
3056 return;
3057 }
3058
3059 final long ident = Binder.clearCallingIdentity();
3060 try {
3061 if (TextUtils.equals(pae.intent.getAction(),
3062 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3063 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003064
3065 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 } else {
3067 pae.intent.replaceExtras(pae.extras);
3068 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3069 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3070 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003071 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072
3073 try {
3074 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3075 } catch (ActivityNotFoundException e) {
3076 Slog.w(TAG, "No activity to handle assist action.", e);
3077 }
3078 }
3079 } finally {
3080 Binder.restoreCallingIdentity(ident);
3081 }
3082 }
3083
Marvin Ramin830d4e32019-03-12 13:16:58 +01003084 /**
3085 * Workaround for historical API which starts the Assist service with a non-foreground
3086 * {@code startService()} call.
3087 */
3088 private void startVoiceInteractionServiceAsUser(
3089 Intent intent, int userHandle, String reason) {
3090 // Resolve the intent to find out which package we need to whitelist.
3091 ResolveInfo resolveInfo =
3092 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3093 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3094 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3095 return;
3096 }
3097 intent.setPackage(resolveInfo.serviceInfo.packageName);
3098
3099 // Whitelist background services temporarily.
3100 LocalServices.getService(DeviceIdleController.LocalService.class)
3101 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3102 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3103
3104 // Finally, try to start the service.
3105 try {
3106 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3107 } catch (RuntimeException e) {
3108 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3109 }
3110 }
3111
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 @Override
3113 public int addAppTask(IBinder activityToken, Intent intent,
3114 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3115 final int callingUid = Binder.getCallingUid();
3116 final long callingIdent = Binder.clearCallingIdentity();
3117
3118 try {
3119 synchronized (mGlobalLock) {
3120 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3121 if (r == null) {
3122 throw new IllegalArgumentException("Activity does not exist; token="
3123 + activityToken);
3124 }
3125 ComponentName comp = intent.getComponent();
3126 if (comp == null) {
3127 throw new IllegalArgumentException("Intent " + intent
3128 + " must specify explicit component");
3129 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003130 if (thumbnail.getWidth() != mThumbnailWidth
3131 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003132 throw new IllegalArgumentException("Bad thumbnail size: got "
3133 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003134 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 }
3136 if (intent.getSelector() != null) {
3137 intent.setSelector(null);
3138 }
3139 if (intent.getSourceBounds() != null) {
3140 intent.setSourceBounds(null);
3141 }
3142 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3143 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3144 // The caller has added this as an auto-remove task... that makes no
3145 // sense, so turn off auto-remove.
3146 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3147 }
3148 }
3149 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3150 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3151 if (ainfo.applicationInfo.uid != callingUid) {
3152 throw new SecurityException(
3153 "Can't add task for another application: target uid="
3154 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3155 }
3156
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003157 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003159 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003161 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 // The app has too many tasks already and we can't add any more
3163 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3164 return INVALID_TASK_ID;
3165 }
3166 task.lastTaskDescription.copyFrom(description);
3167
3168 // TODO: Send the thumbnail to WM to store it.
3169
3170 return task.taskId;
3171 }
3172 } finally {
3173 Binder.restoreCallingIdentity(callingIdent);
3174 }
3175 }
3176
3177 @Override
3178 public Point getAppTaskThumbnailSize() {
3179 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 }
3182 }
3183
3184 @Override
3185 public void setTaskResizeable(int taskId, int resizeableMode) {
3186 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003187 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3189 if (task == null) {
3190 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3191 return;
3192 }
3193 task.setResizeMode(resizeableMode);
3194 }
3195 }
3196
3197 @Override
3198 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003199 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 long ident = Binder.clearCallingIdentity();
3201 try {
3202 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003203 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003204 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 if (task == null) {
3206 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3207 return;
3208 }
3209 // Place the task in the right stack if it isn't there already based on
3210 // the requested bounds.
3211 // The stack transition logic is:
3212 // - a null bounds on a freeform task moves that task to fullscreen
3213 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3214 // that task to freeform
3215 // - otherwise the task is not moved
3216 ActivityStack stack = task.getStack();
3217 if (!task.getWindowConfiguration().canResizeTask()) {
3218 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3219 }
3220 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3221 stack = stack.getDisplay().getOrCreateStack(
3222 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3223 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3224 stack = stack.getDisplay().getOrCreateStack(
3225 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3226 }
3227
3228 // Reparent the task to the right stack if necessary
3229 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3230 if (stack != task.getStack()) {
3231 // Defer resume until the task is resized below
3232 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3233 DEFER_RESUME, "resizeTask");
3234 preserveWindow = false;
3235 }
3236
3237 // After reparenting (which only resizes the task to the stack bounds), resize the
3238 // task to the actual bounds provided
3239 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3240 }
3241 } finally {
3242 Binder.restoreCallingIdentity(ident);
3243 }
3244 }
3245
3246 @Override
3247 public boolean releaseActivityInstance(IBinder token) {
3248 synchronized (mGlobalLock) {
3249 final long origId = Binder.clearCallingIdentity();
3250 try {
3251 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3252 if (r == null) {
3253 return false;
3254 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003255 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 } finally {
3257 Binder.restoreCallingIdentity(origId);
3258 }
3259 }
3260 }
3261
3262 @Override
3263 public void releaseSomeActivities(IApplicationThread appInt) {
3264 synchronized (mGlobalLock) {
3265 final long origId = Binder.clearCallingIdentity();
3266 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003267 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003268 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 } finally {
3270 Binder.restoreCallingIdentity(origId);
3271 }
3272 }
3273 }
3274
3275 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003276 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003277 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003278 != PackageManager.PERMISSION_GRANTED) {
3279 throw new SecurityException("Requires permission "
3280 + android.Manifest.permission.DEVICE_POWER);
3281 }
3282
3283 synchronized (mGlobalLock) {
3284 long ident = Binder.clearCallingIdentity();
3285 if (mKeyguardShown != keyguardShowing) {
3286 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003287 final Message msg = PooledLambda.obtainMessage(
3288 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3289 keyguardShowing);
3290 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003291 }
3292 try {
wilsonshih177261f2019-02-22 12:02:18 +08003293 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003294 } finally {
3295 Binder.restoreCallingIdentity(ident);
3296 }
3297 }
3298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003299 mH.post(() -> {
3300 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3301 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3302 }
3303 });
3304 }
3305
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003306 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003307 mH.post(() -> {
3308 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3309 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3310 }
3311 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 }
3313
3314 @Override
3315 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003316 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3317 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318
3319 final File passedIconFile = new File(filePath);
3320 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3321 passedIconFile.getName());
3322 if (!legitIconFile.getPath().equals(filePath)
3323 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3324 throw new IllegalArgumentException("Bad file path: " + filePath
3325 + " passed for userId " + userId);
3326 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003327 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 }
3329
3330 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3333 final ActivityOptions activityOptions = safeOptions != null
3334 ? safeOptions.getOptions(mStackSupervisor)
3335 : null;
3336 if (activityOptions == null
3337 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3338 || activityOptions.getCustomInPlaceResId() == 0) {
3339 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3340 "with valid animation");
3341 }
lumark588a3e82018-07-20 18:53:54 +08003342 // Get top display of front most application.
3343 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3344 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003345 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3346 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3347 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003348 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003349 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003350 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 }
3352
3353 @Override
3354 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003355 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 synchronized (mGlobalLock) {
3357 final long ident = Binder.clearCallingIdentity();
3358 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003359 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003360 if (stack == null) {
3361 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3362 return;
3363 }
3364 if (!stack.isActivityTypeStandardOrUndefined()) {
3365 throw new IllegalArgumentException(
3366 "Removing non-standard stack is not allowed.");
3367 }
3368 mStackSupervisor.removeStack(stack);
3369 } finally {
3370 Binder.restoreCallingIdentity(ident);
3371 }
3372 }
3373 }
3374
3375 @Override
3376 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003377 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378
3379 synchronized (mGlobalLock) {
3380 final long ident = Binder.clearCallingIdentity();
3381 try {
3382 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3383 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003384 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 } finally {
3386 Binder.restoreCallingIdentity(ident);
3387 }
3388 }
3389 }
3390
3391 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003392 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 synchronized (mGlobalLock) {
3394 long ident = Binder.clearCallingIdentity();
3395 try {
3396 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3397 if (r == null) {
3398 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003399 "toggleFreeformWindowingMode: No activity record matching token="
3400 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 }
3402
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003403 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003404 if (stack == null) {
3405 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3406 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003407 }
3408
Yunfan Chend967af82019-01-17 18:30:18 +09003409 if (!stack.inFreeformWindowingMode()
3410 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3411 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3412 + "toggle between fullscreen and freeform.");
3413 }
3414
3415 if (stack.inFreeformWindowingMode()) {
3416 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003417 } else if (stack.getParent().inFreeformWindowingMode()) {
3418 // If the window is on a freeform display, set it to undefined. It will be
3419 // resolved to freeform and it can adjust windowing mode when the display mode
3420 // changes in runtime.
3421 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003422 } else {
3423 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3424 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 } finally {
3426 Binder.restoreCallingIdentity(ident);
3427 }
3428 }
3429 }
3430
3431 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3432 @Override
3433 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003436 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 }
3438
3439 /** Unregister a task stack listener so that it stops receiving callbacks. */
3440 @Override
3441 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003442 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003444 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 }
3446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 @Override
3448 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3449 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3450 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3451 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3452 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3453 }
3454
3455 @Override
3456 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3457 IBinder activityToken, int flags) {
3458 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3459 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3460 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3461 }
3462
3463 @Override
3464 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3465 Bundle args) {
3466 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3467 true /* focused */, true /* newSessionId */, userHandle, args,
3468 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3469 }
3470
3471 @Override
3472 public Bundle getAssistContextExtras(int requestType) {
3473 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3474 null, null, true /* focused */, true /* newSessionId */,
3475 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3476 if (pae == null) {
3477 return null;
3478 }
3479 synchronized (pae) {
3480 while (!pae.haveResult) {
3481 try {
3482 pae.wait();
3483 } catch (InterruptedException e) {
3484 }
3485 }
3486 }
3487 synchronized (mGlobalLock) {
3488 buildAssistBundleLocked(pae, pae.result);
3489 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003490 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003491 }
3492 return pae.extras;
3493 }
3494
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003495 /**
3496 * Binder IPC calls go through the public entry point.
3497 * This can be called with or without the global lock held.
3498 */
3499 private static int checkCallingPermission(String permission) {
3500 return checkPermission(
3501 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3502 }
3503
3504 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003505 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3507 mAmInternal.enforceCallingPermission(permission, func);
3508 }
3509 }
3510
3511 @VisibleForTesting
3512 int checkGetTasksPermission(String permission, int pid, int uid) {
3513 return checkPermission(permission, pid, uid);
3514 }
3515
3516 static int checkPermission(String permission, int pid, int uid) {
3517 if (permission == null) {
3518 return PackageManager.PERMISSION_DENIED;
3519 }
3520 return checkComponentPermission(permission, pid, uid, -1, true);
3521 }
3522
Wale Ogunwale214f3482018-10-04 11:00:47 -07003523 public static int checkComponentPermission(String permission, int pid, int uid,
3524 int owningUid, boolean exported) {
3525 return ActivityManagerService.checkComponentPermission(
3526 permission, pid, uid, owningUid, exported);
3527 }
3528
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003529 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3530 if (getRecentTasks().isCallerRecents(callingUid)) {
3531 // Always allow the recents component to get tasks
3532 return true;
3533 }
3534
3535 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3536 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3537 if (!allowed) {
3538 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3539 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3540 // Temporary compatibility: some existing apps on the system image may
3541 // still be requesting the old permission and not switched to the new
3542 // one; if so, we'll still allow them full access. This means we need
3543 // to see if they are holding the old permission and are a system app.
3544 try {
3545 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3546 allowed = true;
3547 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3548 + " is using old GET_TASKS but privileged; allowing");
3549 }
3550 } catch (RemoteException e) {
3551 }
3552 }
3553 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3554 + " does not hold REAL_GET_TASKS; limiting output");
3555 }
3556 return allowed;
3557 }
3558
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3560 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3561 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3562 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003563 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003564 "enqueueAssistContext()");
3565
3566 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003567 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003568 if (activity == null) {
3569 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3570 return null;
3571 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003572 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003573 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3574 return null;
3575 }
3576 if (focused) {
3577 if (activityToken != null) {
3578 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3579 if (activity != caller) {
3580 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3581 + " is not current top " + activity);
3582 return null;
3583 }
3584 }
3585 } else {
3586 activity = ActivityRecord.forTokenLocked(activityToken);
3587 if (activity == null) {
3588 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3589 + " couldn't be found");
3590 return null;
3591 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003592 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003593 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3594 return null;
3595 }
3596 }
3597
3598 PendingAssistExtras pae;
3599 Bundle extras = new Bundle();
3600 if (args != null) {
3601 extras.putAll(args);
3602 }
3603 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003604 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605
3606 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3607 userHandle);
3608 pae.isHome = activity.isActivityTypeHome();
3609
3610 // Increment the sessionId if necessary
3611 if (newSessionId) {
3612 mViSessionId++;
3613 }
3614 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003615 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3616 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003617 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003618 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003619 } catch (RemoteException e) {
3620 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3621 return null;
3622 }
3623 return pae;
3624 }
3625 }
3626
3627 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3628 if (result != null) {
3629 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3630 }
3631 if (pae.hint != null) {
3632 pae.extras.putBoolean(pae.hint, true);
3633 }
3634 }
3635
3636 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3637 IAssistDataReceiver receiver;
3638 synchronized (mGlobalLock) {
3639 mPendingAssistExtras.remove(pae);
3640 receiver = pae.receiver;
3641 }
3642 if (receiver != null) {
3643 // Caller wants result sent back to them.
3644 Bundle sendBundle = new Bundle();
3645 // At least return the receiver extras
3646 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3647 try {
3648 pae.receiver.onHandleAssistData(sendBundle);
3649 } catch (RemoteException e) {
3650 }
3651 }
3652 }
3653
3654 public class PendingAssistExtras extends Binder implements Runnable {
3655 public final ActivityRecord activity;
3656 public boolean isHome;
3657 public final Bundle extras;
3658 public final Intent intent;
3659 public final String hint;
3660 public final IAssistDataReceiver receiver;
3661 public final int userHandle;
3662 public boolean haveResult = false;
3663 public Bundle result = null;
3664 public AssistStructure structure = null;
3665 public AssistContent content = null;
3666 public Bundle receiverExtras;
3667
3668 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3669 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3670 int _userHandle) {
3671 activity = _activity;
3672 extras = _extras;
3673 intent = _intent;
3674 hint = _hint;
3675 receiver = _receiver;
3676 receiverExtras = _receiverExtras;
3677 userHandle = _userHandle;
3678 }
3679
3680 @Override
3681 public void run() {
3682 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3683 synchronized (this) {
3684 haveResult = true;
3685 notifyAll();
3686 }
3687 pendingAssistExtrasTimedOut(this);
3688 }
3689 }
3690
3691 @Override
3692 public boolean isAssistDataAllowedOnCurrentActivity() {
3693 int userId;
3694 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003695 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3697 return false;
3698 }
3699
3700 final ActivityRecord activity = focusedStack.getTopActivity();
3701 if (activity == null) {
3702 return false;
3703 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003704 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 }
3706 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3707 }
3708
3709 @Override
3710 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3711 long ident = Binder.clearCallingIdentity();
3712 try {
3713 synchronized (mGlobalLock) {
3714 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003715 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 if (top != caller) {
3717 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3718 + " is not current top " + top);
3719 return false;
3720 }
3721 if (!top.nowVisible) {
3722 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3723 + " is not visible");
3724 return false;
3725 }
3726 }
3727 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3728 token);
3729 } finally {
3730 Binder.restoreCallingIdentity(ident);
3731 }
3732 }
3733
3734 @Override
3735 public boolean isRootVoiceInteraction(IBinder token) {
3736 synchronized (mGlobalLock) {
3737 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3738 if (r == null) {
3739 return false;
3740 }
3741 return r.rootVoiceInteraction;
3742 }
3743 }
3744
Wale Ogunwalef6733932018-06-27 05:14:34 -07003745 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3746 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3747 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3748 if (activityToCallback == null) return;
3749 activityToCallback.setVoiceSessionLocked(voiceSession);
3750
3751 // Inform the activity
3752 try {
3753 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3754 voiceInteractor);
3755 long token = Binder.clearCallingIdentity();
3756 try {
3757 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3758 } finally {
3759 Binder.restoreCallingIdentity(token);
3760 }
3761 // TODO: VI Should we cache the activity so that it's easier to find later
3762 // rather than scan through all the stacks and activities?
3763 } catch (RemoteException re) {
3764 activityToCallback.clearVoiceSessionLocked();
3765 // TODO: VI Should this terminate the voice session?
3766 }
3767 }
3768
3769 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3770 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3771 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3772 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3773 boolean wasRunningVoice = mRunningVoice != null;
3774 mRunningVoice = session;
3775 if (!wasRunningVoice) {
3776 mVoiceWakeLock.acquire();
3777 updateSleepIfNeededLocked();
3778 }
3779 }
3780 }
3781
3782 void finishRunningVoiceLocked() {
3783 if (mRunningVoice != null) {
3784 mRunningVoice = null;
3785 mVoiceWakeLock.release();
3786 updateSleepIfNeededLocked();
3787 }
3788 }
3789
3790 @Override
3791 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3792 synchronized (mGlobalLock) {
3793 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3794 if (keepAwake) {
3795 mVoiceWakeLock.acquire();
3796 } else {
3797 mVoiceWakeLock.release();
3798 }
3799 }
3800 }
3801 }
3802
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003803 @Override
3804 public ComponentName getActivityClassForToken(IBinder token) {
3805 synchronized (mGlobalLock) {
3806 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3807 if (r == null) {
3808 return null;
3809 }
3810 return r.intent.getComponent();
3811 }
3812 }
3813
3814 @Override
3815 public String getPackageForToken(IBinder token) {
3816 synchronized (mGlobalLock) {
3817 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3818 if (r == null) {
3819 return null;
3820 }
3821 return r.packageName;
3822 }
3823 }
3824
3825 @Override
3826 public void showLockTaskEscapeMessage(IBinder token) {
3827 synchronized (mGlobalLock) {
3828 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3829 if (r == null) {
3830 return;
3831 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003832 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 }
3834 }
3835
3836 @Override
3837 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003838 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 final long token = Binder.clearCallingIdentity();
3840 try {
3841 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003842 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 }
3844 } finally {
3845 Binder.restoreCallingIdentity(token);
3846 }
3847 }
3848
3849 /**
3850 * Try to place task to provided position. The final position might be different depending on
3851 * current user and stacks state. The task will be moved to target stack if it's currently in
3852 * different stack.
3853 */
3854 @Override
3855 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003856 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003857 synchronized (mGlobalLock) {
3858 long ident = Binder.clearCallingIdentity();
3859 try {
3860 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3861 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003862 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003863 if (task == null) {
3864 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3865 + taskId);
3866 }
3867
Wale Ogunwaled32da472018-11-16 07:19:28 -08003868 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003869
3870 if (stack == null) {
3871 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3872 + stackId);
3873 }
3874 if (!stack.isActivityTypeStandardOrUndefined()) {
3875 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3876 + " the position of task " + taskId + " in/to non-standard stack");
3877 }
3878
3879 // TODO: Have the callers of this API call a separate reparent method if that is
3880 // what they intended to do vs. having this method also do reparenting.
3881 if (task.getStack() == stack) {
3882 // Change position in current stack.
3883 stack.positionChildAt(task, position);
3884 } else {
3885 // Reparent to new stack.
3886 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3887 !DEFER_RESUME, "positionTaskInStack");
3888 }
3889 } finally {
3890 Binder.restoreCallingIdentity(ident);
3891 }
3892 }
3893 }
3894
3895 @Override
3896 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3897 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3898 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3899 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3900 synchronized (mGlobalLock) {
3901 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3902 if (record == null) {
3903 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3904 + "found for: " + token);
3905 }
3906 record.setSizeConfigurations(horizontalSizeConfiguration,
3907 verticalSizeConfigurations, smallestSizeConfigurations);
3908 }
3909 }
3910
3911 /**
3912 * Dismisses split-screen multi-window mode.
3913 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3914 */
3915 @Override
3916 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003917 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3919 final long ident = Binder.clearCallingIdentity();
3920 try {
3921 synchronized (mGlobalLock) {
3922 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003923 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 if (stack == null) {
3925 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3926 return;
3927 }
3928
3929 if (toTop) {
3930 // Caller wants the current split-screen primary stack to be the top stack after
3931 // it goes fullscreen, so move it to the front.
3932 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003933 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 // In this case the current split-screen primary stack shouldn't be the top
3935 // stack after it goes fullscreen, but it current has focus, so we move the
3936 // focus to the top-most split-screen secondary stack next to it.
3937 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3938 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3939 if (otherStack != null) {
3940 otherStack.moveToFront("dismissSplitScreenMode_other");
3941 }
3942 }
3943
Evan Rosky10475742018-09-05 19:02:48 -07003944 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 }
3946 } finally {
3947 Binder.restoreCallingIdentity(ident);
3948 }
3949 }
3950
3951 /**
3952 * Dismisses Pip
3953 * @param animate True if the dismissal should be animated.
3954 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3955 * default animation duration should be used.
3956 */
3957 @Override
3958 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003959 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 final long ident = Binder.clearCallingIdentity();
3961 try {
3962 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003963 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003964 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 if (stack == null) {
3966 Slog.w(TAG, "dismissPip: pinned stack not found.");
3967 return;
3968 }
3969 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3970 throw new IllegalArgumentException("Stack: " + stack
3971 + " doesn't support animated resize.");
3972 }
3973 if (animate) {
3974 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3975 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3976 } else {
3977 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3978 }
3979 }
3980 } finally {
3981 Binder.restoreCallingIdentity(ident);
3982 }
3983 }
3984
3985 @Override
3986 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003987 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988 synchronized (mGlobalLock) {
3989 mSuppressResizeConfigChanges = suppress;
3990 }
3991 }
3992
3993 /**
3994 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3995 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3996 * activity and clearing the task at the same time.
3997 */
3998 @Override
3999 // TODO: API should just be about changing windowing modes...
4000 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004001 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 "moveTasksToFullscreenStack()");
4003 synchronized (mGlobalLock) {
4004 final long origId = Binder.clearCallingIdentity();
4005 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004006 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 if (stack != null){
4008 if (!stack.isActivityTypeStandardOrUndefined()) {
4009 throw new IllegalArgumentException(
4010 "You can't move tasks from non-standard stacks.");
4011 }
4012 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4013 }
4014 } finally {
4015 Binder.restoreCallingIdentity(origId);
4016 }
4017 }
4018 }
4019
4020 /**
4021 * Moves the top activity in the input stackId to the pinned stack.
4022 *
4023 * @param stackId Id of stack to move the top activity to pinned stack.
4024 * @param bounds Bounds to use for pinned stack.
4025 *
4026 * @return True if the top activity of the input stack was successfully moved to the pinned
4027 * stack.
4028 */
4029 @Override
4030 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 "moveTopActivityToPinnedStack()");
4033 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4036 + "Device doesn't support picture-in-picture mode");
4037 }
4038
4039 long ident = Binder.clearCallingIdentity();
4040 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004041 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 } finally {
4043 Binder.restoreCallingIdentity(ident);
4044 }
4045 }
4046 }
4047
4048 @Override
4049 public boolean isInMultiWindowMode(IBinder token) {
4050 final long origId = Binder.clearCallingIdentity();
4051 try {
4052 synchronized (mGlobalLock) {
4053 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4054 if (r == null) {
4055 return false;
4056 }
4057 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4058 return r.inMultiWindowMode();
4059 }
4060 } finally {
4061 Binder.restoreCallingIdentity(origId);
4062 }
4063 }
4064
4065 @Override
4066 public boolean isInPictureInPictureMode(IBinder token) {
4067 final long origId = Binder.clearCallingIdentity();
4068 try {
4069 synchronized (mGlobalLock) {
4070 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4071 }
4072 } finally {
4073 Binder.restoreCallingIdentity(origId);
4074 }
4075 }
4076
4077 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004078 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4079 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 return false;
4081 }
4082
4083 // If we are animating to fullscreen then we have already dispatched the PIP mode
4084 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004085 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4086 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 }
4088
4089 @Override
4090 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4091 final long origId = Binder.clearCallingIdentity();
4092 try {
4093 synchronized (mGlobalLock) {
4094 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4095 "enterPictureInPictureMode", token, params);
4096
4097 // If the activity is already in picture in picture mode, then just return early
4098 if (isInPictureInPictureMode(r)) {
4099 return true;
4100 }
4101
4102 // Activity supports picture-in-picture, now check that we can enter PiP at this
4103 // point, if it is
4104 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4105 false /* beforeStopping */)) {
4106 return false;
4107 }
4108
4109 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004110 synchronized (mGlobalLock) {
4111 // Only update the saved args from the args that are set
4112 r.pictureInPictureArgs.copyOnlySet(params);
4113 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4114 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4115 // Adjust the source bounds by the insets for the transition down
4116 final Rect sourceBounds = new Rect(
4117 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004118 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004119 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004120 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004121 stack.setPictureInPictureAspectRatio(aspectRatio);
4122 stack.setPictureInPictureActions(actions);
4123 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4124 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4125 logPictureInPictureArgs(params);
4126 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 };
4128
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004129 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 // If the keyguard is showing or occluded, then try and dismiss it before
4131 // entering picture-in-picture (this will prompt the user to authenticate if the
4132 // device is currently locked).
4133 dismissKeyguard(token, new KeyguardDismissCallback() {
4134 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004135 public void onDismissSucceeded() {
4136 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004137 }
4138 }, null /* message */);
4139 } else {
4140 // Enter picture in picture immediately otherwise
4141 enterPipRunnable.run();
4142 }
4143 return true;
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(origId);
4147 }
4148 }
4149
4150 @Override
4151 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 synchronized (mGlobalLock) {
4155 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4156 "setPictureInPictureParams", token, params);
4157
4158 // Only update the saved args from the args that are set
4159 r.pictureInPictureArgs.copyOnlySet(params);
4160 if (r.inPinnedWindowingMode()) {
4161 // If the activity is already in picture-in-picture, update the pinned stack now
4162 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4163 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004164 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 if (!stack.isAnimatingBoundsToFullscreen()) {
4166 stack.setPictureInPictureAspectRatio(
4167 r.pictureInPictureArgs.getAspectRatio());
4168 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4169 }
4170 }
4171 logPictureInPictureArgs(params);
4172 }
4173 } finally {
4174 Binder.restoreCallingIdentity(origId);
4175 }
4176 }
4177
4178 @Override
4179 public int getMaxNumPictureInPictureActions(IBinder token) {
4180 // Currently, this is a static constant, but later, we may change this to be dependent on
4181 // the context of the activity
4182 return 3;
4183 }
4184
4185 private void logPictureInPictureArgs(PictureInPictureParams params) {
4186 if (params.hasSetActions()) {
4187 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4188 params.getActions().size());
4189 }
4190 if (params.hasSetAspectRatio()) {
4191 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4192 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4193 MetricsLogger.action(lm);
4194 }
4195 }
4196
4197 /**
4198 * Checks the state of the system and the activity associated with the given {@param token} to
4199 * verify that picture-in-picture is supported for that activity.
4200 *
4201 * @return the activity record for the given {@param token} if all the checks pass.
4202 */
4203 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4204 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 throw new IllegalStateException(caller
4207 + ": Device doesn't support picture-in-picture mode.");
4208 }
4209
4210 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4211 if (r == null) {
4212 throw new IllegalStateException(caller
4213 + ": Can't find activity for token=" + token);
4214 }
4215
4216 if (!r.supportsPictureInPicture()) {
4217 throw new IllegalStateException(caller
4218 + ": Current activity does not support picture-in-picture.");
4219 }
4220
4221 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004222 && !mWindowManager.isValidPictureInPictureAspectRatio(
4223 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 final float minAspectRatio = mContext.getResources().getFloat(
4225 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4226 final float maxAspectRatio = mContext.getResources().getFloat(
4227 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4228 throw new IllegalArgumentException(String.format(caller
4229 + ": Aspect ratio is too extreme (must be between %f and %f).",
4230 minAspectRatio, maxAspectRatio));
4231 }
4232
4233 // Truncate the number of actions if necessary
4234 params.truncateActions(getMaxNumPictureInPictureActions(token));
4235
4236 return r;
4237 }
4238
4239 @Override
4240 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004241 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 synchronized (mGlobalLock) {
4243 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4244 if (r == null) {
4245 throw new IllegalArgumentException("Activity does not exist; token="
4246 + activityToken);
4247 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004248 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 }
4250 }
4251
4252 @Override
4253 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4254 Rect tempDockedTaskInsetBounds,
4255 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 long ident = Binder.clearCallingIdentity();
4258 try {
4259 synchronized (mGlobalLock) {
4260 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4261 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4262 PRESERVE_WINDOWS);
4263 }
4264 } finally {
4265 Binder.restoreCallingIdentity(ident);
4266 }
4267 }
4268
4269 @Override
4270 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 final long ident = Binder.clearCallingIdentity();
4273 try {
4274 synchronized (mGlobalLock) {
4275 mStackSupervisor.setSplitScreenResizing(resizing);
4276 }
4277 } finally {
4278 Binder.restoreCallingIdentity(ident);
4279 }
4280 }
4281
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 /**
4283 * Check that we have the features required for VR-related API calls, and throw an exception if
4284 * not.
4285 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004286 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 if (!mContext.getPackageManager().hasSystemFeature(
4288 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4289 throw new UnsupportedOperationException("VR mode not supported on this device!");
4290 }
4291 }
4292
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 @Override
4294 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296
4297 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4298
4299 ActivityRecord r;
4300 synchronized (mGlobalLock) {
4301 r = ActivityRecord.isInStackLocked(token);
4302 }
4303
4304 if (r == null) {
4305 throw new IllegalArgumentException();
4306 }
4307
4308 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004309 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 VrManagerInternal.NO_ERROR) {
4311 return err;
4312 }
4313
4314 // Clear the binder calling uid since this path may call moveToTask().
4315 final long callingId = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 r.requestedVrComponent = (enabled) ? packageName : null;
4319
4320 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004321 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004322 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324 return 0;
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(callingId);
4328 }
4329 }
4330
4331 @Override
4332 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4333 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4334 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004335 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004336 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4337 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4338 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004339 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 || activity.voiceSession != null) {
4341 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4342 return;
4343 }
4344 if (activity.pendingVoiceInteractionStart) {
4345 Slog.w(TAG, "Pending start of voice interaction already.");
4346 return;
4347 }
4348 activity.pendingVoiceInteractionStart = true;
4349 }
4350 LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .startLocalVoiceInteraction(callingActivity, options);
4352 }
4353
4354 @Override
4355 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4356 LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .stopLocalVoiceInteraction(callingActivity);
4358 }
4359
4360 @Override
4361 public boolean supportsLocalVoiceInteraction() {
4362 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4363 .supportsLocalVoiceInteraction();
4364 }
4365
4366 /** Notifies all listeners when the pinned stack animation starts. */
4367 @Override
4368 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004369 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371
4372 /** Notifies all listeners when the pinned stack animation ends. */
4373 @Override
4374 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004375 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 }
4377
4378 @Override
4379 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 final long ident = Binder.clearCallingIdentity();
4382 try {
4383 synchronized (mGlobalLock) {
4384 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4385 }
4386 } finally {
4387 Binder.restoreCallingIdentity(ident);
4388 }
4389 }
4390
4391 @Override
4392 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394
4395 synchronized (mGlobalLock) {
4396 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004397 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 // Call might come when display is not yet added or has already been removed.
4399 if (DEBUG_CONFIGURATION) {
4400 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4401 + displayId);
4402 }
4403 return false;
4404 }
4405
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004408 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 }
4410
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004412 final Message msg = PooledLambda.obtainMessage(
4413 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4414 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 }
4416
4417 final long origId = Binder.clearCallingIdentity();
4418 try {
4419 if (values != null) {
4420 Settings.System.clearConfiguration(values);
4421 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4424 return mTmpUpdateConfigurationResult.changes != 0;
4425 } finally {
4426 Binder.restoreCallingIdentity(origId);
4427 }
4428 }
4429 }
4430
4431 @Override
4432 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004433 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434
4435 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004436 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 }
4440
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004441 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004442 final Message msg = PooledLambda.obtainMessage(
4443 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4444 DEFAULT_DISPLAY);
4445 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 }
4447
4448 final long origId = Binder.clearCallingIdentity();
4449 try {
4450 if (values != null) {
4451 Settings.System.clearConfiguration(values);
4452 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 UserHandle.USER_NULL, false /* deferResume */,
4455 mTmpUpdateConfigurationResult);
4456 return mTmpUpdateConfigurationResult.changes != 0;
4457 } finally {
4458 Binder.restoreCallingIdentity(origId);
4459 }
4460 }
4461 }
4462
4463 @Override
4464 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4465 CharSequence message) {
4466 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4469 }
4470 final long callingId = Binder.clearCallingIdentity();
4471 try {
4472 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004473 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 }
4475 } finally {
4476 Binder.restoreCallingIdentity(callingId);
4477 }
4478 }
4479
4480 @Override
4481 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004482 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 "cancelTaskWindowTransition()");
4484 final long ident = Binder.clearCallingIdentity();
4485 try {
4486 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004487 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 MATCH_TASK_IN_STACKS_ONLY);
4489 if (task == null) {
4490 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4491 return;
4492 }
4493 task.cancelWindowTransition();
4494 }
4495 } finally {
4496 Binder.restoreCallingIdentity(ident);
4497 }
4498 }
4499
4500 @Override
4501 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004502 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 final long ident = Binder.clearCallingIdentity();
4504 try {
4505 final TaskRecord task;
4506 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004507 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4509 if (task == null) {
4510 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4511 return null;
4512 }
4513 }
4514 // Don't call this while holding the lock as this operation might hit the disk.
4515 return task.getSnapshot(reducedResolution);
4516 } finally {
4517 Binder.restoreCallingIdentity(ident);
4518 }
4519 }
4520
4521 @Override
4522 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4523 synchronized (mGlobalLock) {
4524 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4525 if (r == null) {
4526 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4527 + token);
4528 return;
4529 }
4530 final long origId = Binder.clearCallingIdentity();
4531 try {
4532 r.setDisablePreviewScreenshots(disable);
4533 } finally {
4534 Binder.restoreCallingIdentity(origId);
4535 }
4536 }
4537 }
4538
4539 /** Return the user id of the last resumed activity. */
4540 @Override
4541 public @UserIdInt
4542 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004543 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4545 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004546 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004547 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004549 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004550 }
4551 }
4552
4553 @Override
4554 public void updateLockTaskFeatures(int userId, int flags) {
4555 final int callingUid = Binder.getCallingUid();
4556 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004557 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 "updateLockTaskFeatures()");
4559 }
4560 synchronized (mGlobalLock) {
4561 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4562 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004563 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 }
4565 }
4566
4567 @Override
4568 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4569 synchronized (mGlobalLock) {
4570 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4571 if (r == null) {
4572 return;
4573 }
4574 final long origId = Binder.clearCallingIdentity();
4575 try {
4576 r.setShowWhenLocked(showWhenLocked);
4577 } finally {
4578 Binder.restoreCallingIdentity(origId);
4579 }
4580 }
4581 }
4582
4583 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004584 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4585 synchronized (mGlobalLock) {
4586 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4587 if (r == null) {
4588 return;
4589 }
4590 final long origId = Binder.clearCallingIdentity();
4591 try {
4592 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4593 } finally {
4594 Binder.restoreCallingIdentity(origId);
4595 }
4596 }
4597 }
4598
4599 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004600 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4601 synchronized (mGlobalLock) {
4602 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4603 if (r == null) {
4604 return;
4605 }
4606 final long origId = Binder.clearCallingIdentity();
4607 try {
4608 r.setTurnScreenOn(turnScreenOn);
4609 } finally {
4610 Binder.restoreCallingIdentity(origId);
4611 }
4612 }
4613 }
4614
4615 @Override
4616 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004617 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004618 "registerRemoteAnimations");
4619 definition.setCallingPid(Binder.getCallingPid());
4620 synchronized (mGlobalLock) {
4621 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4622 if (r == null) {
4623 return;
4624 }
4625 final long origId = Binder.clearCallingIdentity();
4626 try {
4627 r.registerRemoteAnimations(definition);
4628 } finally {
4629 Binder.restoreCallingIdentity(origId);
4630 }
4631 }
4632 }
4633
4634 @Override
4635 public void registerRemoteAnimationForNextActivityStart(String packageName,
4636 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004637 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004638 "registerRemoteAnimationForNextActivityStart");
4639 adapter.setCallingPid(Binder.getCallingPid());
4640 synchronized (mGlobalLock) {
4641 final long origId = Binder.clearCallingIdentity();
4642 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004643 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 packageName, adapter);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
Evan Rosky966759f2019-01-15 10:33:58 -08004651 @Override
4652 public void registerRemoteAnimationsForDisplay(int displayId,
4653 RemoteAnimationDefinition definition) {
4654 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4655 "registerRemoteAnimations");
4656 definition.setCallingPid(Binder.getCallingPid());
4657 synchronized (mGlobalLock) {
4658 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4659 if (display == null) {
4660 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4661 return;
4662 }
4663 final long origId = Binder.clearCallingIdentity();
4664 try {
4665 display.mDisplayContent.registerRemoteAnimations(definition);
4666 } finally {
4667 Binder.restoreCallingIdentity(origId);
4668 }
4669 }
4670 }
4671
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004672 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4673 @Override
4674 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4675 synchronized (mGlobalLock) {
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004678 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004679 } finally {
4680 Binder.restoreCallingIdentity(origId);
4681 }
4682 }
4683 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004684
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004685 @Override
4686 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004689 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004690 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004691 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004692 }
4693 }
4694
4695 @Override
4696 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004697 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 != PERMISSION_GRANTED) {
4699 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4700 + Binder.getCallingPid()
4701 + ", uid=" + Binder.getCallingUid()
4702 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4703 Slog.w(TAG, msg);
4704 throw new SecurityException(msg);
4705 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004706 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004708 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004709 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004710 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 }
4712 }
4713
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 @Override
4715 public void stopAppSwitches() {
4716 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4717 synchronized (mGlobalLock) {
4718 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4719 mDidAppSwitch = false;
4720 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4721 }
4722 }
4723
4724 @Override
4725 public void resumeAppSwitches() {
4726 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4727 synchronized (mGlobalLock) {
4728 // Note that we don't execute any pending app switches... we will
4729 // let those wait until either the timeout, or the next start
4730 // activity request.
4731 mAppSwitchesAllowedTime = 0;
4732 }
4733 }
4734
4735 void onStartActivitySetDidAppSwitch() {
4736 if (mDidAppSwitch) {
4737 // This is the second allowed switch since we stopped switches, so now just generally
4738 // allow switches. Use case:
4739 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4740 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4741 // anyone to switch again).
4742 mAppSwitchesAllowedTime = 0;
4743 } else {
4744 mDidAppSwitch = true;
4745 }
4746 }
4747
4748 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 boolean shouldDisableNonVrUiLocked() {
4750 return mVrController.shouldDisableNonVrUiLocked();
4751 }
4752
Wale Ogunwale53783742018-09-16 10:21:51 -07004753 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004754 // VR apps are expected to run in a main display. If an app is turning on VR for
4755 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4756 // fullscreen stack before enabling VR Mode.
4757 // TODO: The goal of this code is to keep the VR app on the main display. When the
4758 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4759 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4760 // option would be a better choice here.
4761 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4762 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4763 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004764 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004765 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004766 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004767 }
4768 mH.post(() -> {
4769 if (!mVrController.onVrModeChanged(r)) {
4770 return;
4771 }
4772 synchronized (mGlobalLock) {
4773 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4774 mWindowManager.disableNonVrUi(disableNonVrUi);
4775 if (disableNonVrUi) {
4776 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4777 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004778 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004779 }
4780 }
4781 });
4782 }
4783
Wale Ogunwale53783742018-09-16 10:21:51 -07004784 @Override
4785 public int getPackageScreenCompatMode(String packageName) {
4786 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4787 synchronized (mGlobalLock) {
4788 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4789 }
4790 }
4791
4792 @Override
4793 public void setPackageScreenCompatMode(String packageName, int mode) {
4794 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4795 "setPackageScreenCompatMode");
4796 synchronized (mGlobalLock) {
4797 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4798 }
4799 }
4800
4801 @Override
4802 public boolean getPackageAskScreenCompat(String packageName) {
4803 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4804 synchronized (mGlobalLock) {
4805 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4806 }
4807 }
4808
4809 @Override
4810 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4811 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4812 "setPackageAskScreenCompat");
4813 synchronized (mGlobalLock) {
4814 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4815 }
4816 }
4817
Wale Ogunwale64258362018-10-16 15:13:37 -07004818 public static String relaunchReasonToString(int relaunchReason) {
4819 switch (relaunchReason) {
4820 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4821 return "window_resize";
4822 case RELAUNCH_REASON_FREE_RESIZE:
4823 return "free_resize";
4824 default:
4825 return null;
4826 }
4827 }
4828
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004829 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004830 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004831 }
4832
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004833 /** Pokes the task persister. */
4834 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4835 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4836 }
4837
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004838 boolean isKeyguardLocked() {
4839 return mKeyguardController.isKeyguardLocked();
4840 }
4841
Garfield Tan01548632018-11-27 10:15:48 -08004842 /**
4843 * Clears launch params for the given package.
4844 * @param packageNames the names of the packages of which the launch params are to be cleared
4845 */
4846 @Override
4847 public void clearLaunchParamsForPackages(List<String> packageNames) {
4848 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4849 "clearLaunchParamsForPackages");
4850 synchronized (mGlobalLock) {
4851 for (int i = 0; i < packageNames.size(); ++i) {
4852 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4853 }
4854 }
4855 }
4856
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004857 /**
4858 * Makes the display with the given id a single task instance display. I.e the display can only
4859 * contain one task.
4860 */
4861 @Override
4862 public void setDisplayToSingleTaskInstance(int displayId) {
4863 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4864 "setDisplayToSingleTaskInstance");
4865 final long origId = Binder.clearCallingIdentity();
4866 try {
4867 final ActivityDisplay display =
4868 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4869 if (display != null) {
4870 display.setDisplayToSingleTaskInstance();
4871 }
4872 } finally {
4873 Binder.restoreCallingIdentity(origId);
4874 }
4875 }
4876
Wale Ogunwale31913b52018-10-13 08:29:31 -07004877 void dumpLastANRLocked(PrintWriter pw) {
4878 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4879 if (mLastANRState == null) {
4880 pw.println(" <no ANR has occurred since boot>");
4881 } else {
4882 pw.println(mLastANRState);
4883 }
4884 }
4885
4886 void dumpLastANRTracesLocked(PrintWriter pw) {
4887 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4888
4889 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4890 if (ArrayUtils.isEmpty(files)) {
4891 pw.println(" <no ANR has occurred since boot>");
4892 return;
4893 }
4894 // Find the latest file.
4895 File latest = null;
4896 for (File f : files) {
4897 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4898 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004899 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004900 }
4901 pw.print("File: ");
4902 pw.print(latest.getName());
4903 pw.println();
4904 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4905 String line;
4906 while ((line = in.readLine()) != null) {
4907 pw.println(line);
4908 }
4909 } catch (IOException e) {
4910 pw.print("Unable to read: ");
4911 pw.print(e);
4912 pw.println();
4913 }
4914 }
4915
4916 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4917 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4918 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4919 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4920 }
4921
4922 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4923 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4924 pw.println(header);
4925
Wale Ogunwaled32da472018-11-16 07:19:28 -08004926 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004927 dumpPackage);
4928 boolean needSep = printedAnything;
4929
4930 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004931 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004932 " ResumedActivity: ");
4933 if (printed) {
4934 printedAnything = true;
4935 needSep = false;
4936 }
4937
4938 if (dumpPackage == null) {
4939 if (needSep) {
4940 pw.println();
4941 }
4942 printedAnything = true;
4943 mStackSupervisor.dump(pw, " ");
4944 }
4945
4946 if (!printedAnything) {
4947 pw.println(" (nothing)");
4948 }
4949 }
4950
4951 void dumpActivityContainersLocked(PrintWriter pw) {
4952 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004953 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004954 pw.println(" ");
4955 }
4956
4957 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4958 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4959 getActivityStartController().dump(pw, "", dumpPackage);
4960 }
4961
4962 /**
4963 * There are three things that cmd can be:
4964 * - a flattened component name that matches an existing activity
4965 * - the cmd arg isn't the flattened component name of an existing activity:
4966 * dump all activity whose component contains the cmd as a substring
4967 * - A hex number of the ActivityRecord object instance.
4968 *
4969 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4970 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4971 */
4972 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4973 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4974 ArrayList<ActivityRecord> activities;
4975
4976 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004977 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004978 dumpFocusedStackOnly);
4979 }
4980
4981 if (activities.size() <= 0) {
4982 return false;
4983 }
4984
4985 String[] newArgs = new String[args.length - opti];
4986 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4987
4988 TaskRecord lastTask = null;
4989 boolean needSep = false;
4990 for (int i = activities.size() - 1; i >= 0; i--) {
4991 ActivityRecord r = activities.get(i);
4992 if (needSep) {
4993 pw.println();
4994 }
4995 needSep = true;
4996 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004997 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004998 if (lastTask != task) {
4999 lastTask = task;
5000 pw.print("TASK "); pw.print(lastTask.affinity);
5001 pw.print(" id="); pw.print(lastTask.taskId);
5002 pw.print(" userId="); pw.println(lastTask.userId);
5003 if (dumpAll) {
5004 lastTask.dump(pw, " ");
5005 }
5006 }
5007 }
5008 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5009 }
5010 return true;
5011 }
5012
5013 /**
5014 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5015 * there is a thread associated with the activity.
5016 */
5017 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5018 final ActivityRecord r, String[] args, boolean dumpAll) {
5019 String innerPrefix = prefix + " ";
5020 synchronized (mGlobalLock) {
5021 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5022 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5023 pw.print(" pid=");
5024 if (r.hasProcess()) pw.println(r.app.getPid());
5025 else pw.println("(not running)");
5026 if (dumpAll) {
5027 r.dump(pw, innerPrefix);
5028 }
5029 }
5030 if (r.attachedToProcess()) {
5031 // flush anything that is already in the PrintWriter since the thread is going
5032 // to write to the file descriptor directly
5033 pw.flush();
5034 try {
5035 TransferPipe tp = new TransferPipe();
5036 try {
5037 r.app.getThread().dumpActivity(tp.getWriteFd(),
5038 r.appToken, innerPrefix, args);
5039 tp.go(fd);
5040 } finally {
5041 tp.kill();
5042 }
5043 } catch (IOException e) {
5044 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5045 } catch (RemoteException e) {
5046 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5047 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005048 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005049 }
5050
sanryhuang498e77e2018-12-06 14:57:01 +08005051 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5052 boolean testPssMode) {
5053 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5054 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5055 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005056 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005057 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5058 st.toString());
5059 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005060 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5061 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5062 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005063 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5064 testPssMode);
5065 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005066 }
5067
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068 int getCurrentUserId() {
5069 return mAmInternal.getCurrentUserId();
5070 }
5071
5072 private void enforceNotIsolatedCaller(String caller) {
5073 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5074 throw new SecurityException("Isolated process not allowed to call " + caller);
5075 }
5076 }
5077
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 public Configuration getConfiguration() {
5079 Configuration ci;
5080 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005081 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005082 ci.userSetLocale = false;
5083 }
5084 return ci;
5085 }
5086
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005087 /**
5088 * Current global configuration information. Contains general settings for the entire system,
5089 * also corresponds to the merged configuration of the default display.
5090 */
5091 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005092 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005093 }
5094
5095 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5096 boolean initLocale) {
5097 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5098 }
5099
5100 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5101 boolean initLocale, boolean deferResume) {
5102 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5103 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5104 UserHandle.USER_NULL, deferResume);
5105 }
5106
Wale Ogunwale59507092018-10-29 09:00:30 -07005107 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005108 final long origId = Binder.clearCallingIdentity();
5109 try {
5110 synchronized (mGlobalLock) {
5111 updateConfigurationLocked(values, null, false, true, userId,
5112 false /* deferResume */);
5113 }
5114 } finally {
5115 Binder.restoreCallingIdentity(origId);
5116 }
5117 }
5118
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5120 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5121 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5122 deferResume, null /* result */);
5123 }
5124
5125 /**
5126 * Do either or both things: (1) change the current configuration, and (2)
5127 * make sure the given activity is running with the (now) current
5128 * configuration. Returns true if the activity has been left running, or
5129 * false if <var>starting</var> is being destroyed to match the new
5130 * configuration.
5131 *
5132 * @param userId is only used when persistent parameter is set to true to persist configuration
5133 * for that particular user
5134 */
5135 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5136 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5137 ActivityTaskManagerService.UpdateConfigurationResult result) {
5138 int changes = 0;
5139 boolean kept = true;
5140
5141 if (mWindowManager != null) {
5142 mWindowManager.deferSurfaceLayout();
5143 }
5144 try {
5145 if (values != null) {
5146 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5147 deferResume);
5148 }
5149
5150 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5151 } finally {
5152 if (mWindowManager != null) {
5153 mWindowManager.continueSurfaceLayout();
5154 }
5155 }
5156
5157 if (result != null) {
5158 result.changes = changes;
5159 result.activityRelaunched = !kept;
5160 }
5161 return kept;
5162 }
5163
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005164 /** Update default (global) configuration and notify listeners about changes. */
5165 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5166 boolean persistent, int userId, boolean deferResume) {
5167 mTempConfig.setTo(getGlobalConfiguration());
5168 final int changes = mTempConfig.updateFrom(values);
5169 if (changes == 0) {
5170 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5171 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5172 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5173 // (even if there are no actual changes) to unfreeze the window.
5174 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5175 return 0;
5176 }
5177
5178 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5179 "Updating global configuration to: " + values);
5180
5181 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5182 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5183 values.colorMode,
5184 values.densityDpi,
5185 values.fontScale,
5186 values.hardKeyboardHidden,
5187 values.keyboard,
5188 values.keyboardHidden,
5189 values.mcc,
5190 values.mnc,
5191 values.navigation,
5192 values.navigationHidden,
5193 values.orientation,
5194 values.screenHeightDp,
5195 values.screenLayout,
5196 values.screenWidthDp,
5197 values.smallestScreenWidthDp,
5198 values.touchscreen,
5199 values.uiMode);
5200
5201
5202 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5203 final LocaleList locales = values.getLocales();
5204 int bestLocaleIndex = 0;
5205 if (locales.size() > 1) {
5206 if (mSupportedSystemLocales == null) {
5207 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5208 }
5209 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5210 }
5211 SystemProperties.set("persist.sys.locale",
5212 locales.get(bestLocaleIndex).toLanguageTag());
5213 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005214
5215 final Message m = PooledLambda.obtainMessage(
5216 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5217 locales.get(bestLocaleIndex));
5218 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
5220
Yunfan Chen75157d72018-07-27 14:47:21 +09005221 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222
5223 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005224 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225
5226 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5227 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005228 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229
5230 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005231 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232
5233 AttributeCache ac = AttributeCache.instance();
5234 if (ac != null) {
5235 ac.updateConfiguration(mTempConfig);
5236 }
5237
5238 // Make sure all resources in our process are updated right now, so that anyone who is going
5239 // to retrieve resource values after we return will be sure to get the new ones. This is
5240 // especially important during boot, where the first config change needs to guarantee all
5241 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005242 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005243
5244 // We need another copy of global config because we're scheduling some calls instead of
5245 // running them in place. We need to be sure that object we send will be handled unchanged.
5246 final Configuration configCopy = new Configuration(mTempConfig);
5247 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005248 final Message msg = PooledLambda.obtainMessage(
5249 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5250 this, userId, configCopy);
5251 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252 }
5253
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005254 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5255 for (int i = pidMap.size() - 1; i >= 0; i--) {
5256 final int pid = pidMap.keyAt(i);
5257 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005258 if (DEBUG_CONFIGURATION) {
5259 Slog.v(TAG_CONFIGURATION, "Update process config of "
5260 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005261 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005262 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005263 }
5264
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005265 final Message msg = PooledLambda.obtainMessage(
5266 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5267 mAmInternal, changes, initLocale);
5268 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 // Override configuration of the default display duplicates global config, so we need to
5271 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005272 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273 DEFAULT_DISPLAY);
5274
5275 return changes;
5276 }
5277
5278 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5279 boolean deferResume, int displayId) {
5280 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5281 displayId, null /* result */);
5282 }
5283
5284 /**
5285 * Updates override configuration specific for the selected display. If no config is provided,
5286 * new one will be computed in WM based on current display info.
5287 */
5288 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5289 ActivityRecord starting, boolean deferResume, int displayId,
5290 ActivityTaskManagerService.UpdateConfigurationResult result) {
5291 int changes = 0;
5292 boolean kept = true;
5293
5294 if (mWindowManager != null) {
5295 mWindowManager.deferSurfaceLayout();
5296 }
5297 try {
5298 if (values != null) {
5299 if (displayId == DEFAULT_DISPLAY) {
5300 // Override configuration of the default display duplicates global config, so
5301 // we're calling global config update instead for default display. It will also
5302 // apply the correct override config.
5303 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5304 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5305 } else {
5306 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5307 }
5308 }
5309
5310 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5311 } finally {
5312 if (mWindowManager != null) {
5313 mWindowManager.continueSurfaceLayout();
5314 }
5315 }
5316
5317 if (result != null) {
5318 result.changes = changes;
5319 result.activityRelaunched = !kept;
5320 }
5321 return kept;
5322 }
5323
5324 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5325 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005326 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005327 final int changes = mTempConfig.updateFrom(values);
5328 if (changes != 0) {
5329 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5330 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005331 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005332
5333 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5334 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005335 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005336
Wale Ogunwale5c918702018-10-18 11:06:33 -07005337 // Post message to start process to avoid possible deadlock of calling into AMS with
5338 // the ATMS lock held.
5339 final Message msg = PooledLambda.obtainMessage(
5340 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005341 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005342 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005343 }
5344 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005345 return changes;
5346 }
5347
Wale Ogunwalef6733932018-06-27 05:14:34 -07005348 private void updateEventDispatchingLocked(boolean booted) {
5349 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5350 }
5351
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005352 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5353 final ContentResolver resolver = mContext.getContentResolver();
5354 Settings.System.putConfigurationForUser(resolver, config, userId);
5355 }
5356
5357 private void sendLocaleToMountDaemonMsg(Locale l) {
5358 try {
5359 IBinder service = ServiceManager.getService("mount");
5360 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5361 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5362 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5363 } catch (RemoteException e) {
5364 Log.e(TAG, "Error storing locale for decryption UI", e);
5365 }
5366 }
5367
Alison Cichowlas3e340502018-08-07 17:15:01 -04005368 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5369 mStartActivitySources.remove(permissionToken);
5370 mExpiredStartAsCallerTokens.add(permissionToken);
5371 }
5372
5373 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5374 mExpiredStartAsCallerTokens.remove(permissionToken);
5375 }
5376
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005377 boolean isActivityStartsLoggingEnabled() {
5378 return mAmInternal.isActivityStartsLoggingEnabled();
5379 }
5380
Michal Karpinski8596ded2018-11-14 14:43:48 +00005381 boolean isBackgroundActivityStartsEnabled() {
5382 return mAmInternal.isBackgroundActivityStartsEnabled();
5383 }
5384
Ricky Waiaca8a772019-04-04 16:01:06 +01005385 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5386 if (packageName == null) {
5387 return false;
5388 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005389 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5390 }
5391
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 void enableScreenAfterBoot(boolean booted) {
5393 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5394 SystemClock.uptimeMillis());
5395 mWindowManager.enableScreenAfterBoot();
5396
5397 synchronized (mGlobalLock) {
5398 updateEventDispatchingLocked(booted);
5399 }
5400 }
5401
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005402 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5403 if (r == null || !r.hasProcess()) {
5404 return KEY_DISPATCHING_TIMEOUT_MS;
5405 }
5406 return getInputDispatchingTimeoutLocked(r.app);
5407 }
5408
5409 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005410 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005411 }
5412
Wale Ogunwalef6733932018-06-27 05:14:34 -07005413 /**
5414 * Decide based on the configuration whether we should show the ANR,
5415 * crash, etc dialogs. The idea is that if there is no affordance to
5416 * press the on-screen buttons, or the user experience would be more
5417 * greatly impacted than the crash itself, we shouldn't show the dialog.
5418 *
5419 * A thought: SystemUI might also want to get told about this, the Power
5420 * dialog / global actions also might want different behaviors.
5421 */
5422 private void updateShouldShowDialogsLocked(Configuration config) {
5423 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5424 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5425 && config.navigation == Configuration.NAVIGATION_NONAV);
5426 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5427 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5428 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5429 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5430 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5431 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5432 HIDE_ERROR_DIALOGS, 0) != 0;
5433 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5434 }
5435
5436 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5437 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5438 FONT_SCALE, 1.0f, userId);
5439
5440 synchronized (this) {
5441 if (getGlobalConfiguration().fontScale == scaleFactor) {
5442 return;
5443 }
5444
5445 final Configuration configuration
5446 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5447 configuration.fontScale = scaleFactor;
5448 updatePersistentConfiguration(configuration, userId);
5449 }
5450 }
5451
5452 // Actually is sleeping or shutting down or whatever else in the future
5453 // is an inactive state.
5454 boolean isSleepingOrShuttingDownLocked() {
5455 return isSleepingLocked() || mShuttingDown;
5456 }
5457
5458 boolean isSleepingLocked() {
5459 return mSleeping;
5460 }
5461
Riddle Hsu16567132018-08-16 21:37:47 +08005462 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005464 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 if (task.isActivityTypeStandard()) {
5466 if (mCurAppTimeTracker != r.appTimeTracker) {
5467 // We are switching app tracking. Complete the current one.
5468 if (mCurAppTimeTracker != null) {
5469 mCurAppTimeTracker.stop();
5470 mH.obtainMessage(
5471 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005472 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473 mCurAppTimeTracker = null;
5474 }
5475 if (r.appTimeTracker != null) {
5476 mCurAppTimeTracker = r.appTimeTracker;
5477 startTimeTrackingFocusedActivityLocked();
5478 }
5479 } else {
5480 startTimeTrackingFocusedActivityLocked();
5481 }
5482 } else {
5483 r.appTimeTracker = null;
5484 }
5485 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5486 // TODO: Probably not, because we don't want to resume voice on switching
5487 // back to this activity
5488 if (task.voiceInteractor != null) {
5489 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5490 } else {
5491 finishRunningVoiceLocked();
5492
5493 if (mLastResumedActivity != null) {
5494 final IVoiceInteractionSession session;
5495
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005496 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005497 if (lastResumedActivityTask != null
5498 && lastResumedActivityTask.voiceSession != null) {
5499 session = lastResumedActivityTask.voiceSession;
5500 } else {
5501 session = mLastResumedActivity.voiceSession;
5502 }
5503
5504 if (session != null) {
5505 // We had been in a voice interaction session, but now focused has
5506 // move to something different. Just finish the session, we can't
5507 // return to it and retain the proper state and synchronization with
5508 // the voice interaction service.
5509 finishVoiceTask(session);
5510 }
5511 }
5512 }
5513
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005514 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5515 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005516 }
5517 updateResumedAppTrace(r);
5518 mLastResumedActivity = r;
5519
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005520 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521
5522 applyUpdateLockStateLocked(r);
5523 applyUpdateVrModeLocked(r);
5524
5525 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005526 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527 r == null ? "NULL" : r.shortComponentName,
5528 reason);
5529 }
5530
5531 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5532 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005533 final ActivityTaskManagerInternal.SleepToken token =
5534 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 updateSleepIfNeededLocked();
5536 return token;
5537 }
5538 }
5539
5540 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005541 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 final boolean wasSleeping = mSleeping;
5543 boolean updateOomAdj = false;
5544
5545 if (!shouldSleep) {
5546 // If wasSleeping is true, we need to wake up activity manager state from when
5547 // we started sleeping. In either case, we need to apply the sleep tokens, which
5548 // will wake up stacks or put them to sleep as appropriate.
5549 if (wasSleeping) {
5550 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005551 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5552 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553 startTimeTrackingFocusedActivityLocked();
5554 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005555 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5557 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005558 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005559 if (wasSleeping) {
5560 updateOomAdj = true;
5561 }
5562 } else if (!mSleeping && shouldSleep) {
5563 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005564 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5565 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005566 if (mCurAppTimeTracker != null) {
5567 mCurAppTimeTracker.stop();
5568 }
5569 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005570 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 mStackSupervisor.goingToSleepLocked();
5572 updateResumedAppTrace(null /* resumed */);
5573 updateOomAdj = true;
5574 }
5575 if (updateOomAdj) {
5576 mH.post(mAmInternal::updateOomAdj);
5577 }
5578 }
5579
5580 void updateOomAdj() {
5581 mH.post(mAmInternal::updateOomAdj);
5582 }
5583
Wale Ogunwale53783742018-09-16 10:21:51 -07005584 void updateCpuStats() {
5585 mH.post(mAmInternal::updateCpuStats);
5586 }
5587
Hui Yu03d12402018-12-06 18:00:37 -08005588 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5589 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005590 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5591 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005592 mH.sendMessage(m);
5593 }
5594
Hui Yu03d12402018-12-06 18:00:37 -08005595 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005596 ComponentName taskRoot = null;
5597 final TaskRecord task = activity.getTaskRecord();
5598 if (task != null) {
5599 final ActivityRecord rootActivity = task.getRootActivity();
5600 if (rootActivity != null) {
5601 taskRoot = rootActivity.mActivityComponent;
5602 }
5603 }
5604
Hui Yu03d12402018-12-06 18:00:37 -08005605 final Message m = PooledLambda.obtainMessage(
5606 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005607 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005608 mH.sendMessage(m);
5609 }
5610
Wale Ogunwale53783742018-09-16 10:21:51 -07005611 void setBooting(boolean booting) {
5612 mAmInternal.setBooting(booting);
5613 }
5614
5615 boolean isBooting() {
5616 return mAmInternal.isBooting();
5617 }
5618
5619 void setBooted(boolean booted) {
5620 mAmInternal.setBooted(booted);
5621 }
5622
5623 boolean isBooted() {
5624 return mAmInternal.isBooted();
5625 }
5626
5627 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5628 mH.post(() -> {
5629 if (finishBooting) {
5630 mAmInternal.finishBooting();
5631 }
5632 if (enableScreen) {
5633 mInternal.enableScreenAfterBoot(isBooted());
5634 }
5635 });
5636 }
5637
5638 void setHeavyWeightProcess(ActivityRecord root) {
5639 mHeavyWeightProcess = root.app;
5640 final Message m = PooledLambda.obtainMessage(
5641 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005642 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005643 mH.sendMessage(m);
5644 }
5645
5646 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5647 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5648 return;
5649 }
5650
5651 mHeavyWeightProcess = null;
5652 final Message m = PooledLambda.obtainMessage(
5653 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5654 proc.mUserId);
5655 mH.sendMessage(m);
5656 }
5657
5658 private void cancelHeavyWeightProcessNotification(int userId) {
5659 final INotificationManager inm = NotificationManager.getService();
5660 if (inm == null) {
5661 return;
5662 }
5663 try {
5664 inm.cancelNotificationWithTag("android", null,
5665 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5666 } catch (RuntimeException e) {
5667 Slog.w(TAG, "Error canceling notification for service", e);
5668 } catch (RemoteException e) {
5669 }
5670
5671 }
5672
5673 private void postHeavyWeightProcessNotification(
5674 WindowProcessController proc, Intent intent, int userId) {
5675 if (proc == null) {
5676 return;
5677 }
5678
5679 final INotificationManager inm = NotificationManager.getService();
5680 if (inm == null) {
5681 return;
5682 }
5683
5684 try {
5685 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5686 String text = mContext.getString(R.string.heavy_weight_notification,
5687 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5688 Notification notification =
5689 new Notification.Builder(context,
5690 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5691 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5692 .setWhen(0)
5693 .setOngoing(true)
5694 .setTicker(text)
5695 .setColor(mContext.getColor(
5696 com.android.internal.R.color.system_notification_accent_color))
5697 .setContentTitle(text)
5698 .setContentText(
5699 mContext.getText(R.string.heavy_weight_notification_detail))
5700 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5701 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5702 new UserHandle(userId)))
5703 .build();
5704 try {
5705 inm.enqueueNotificationWithTag("android", "android", null,
5706 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5707 } catch (RuntimeException e) {
5708 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5709 } catch (RemoteException e) {
5710 }
5711 } catch (PackageManager.NameNotFoundException e) {
5712 Slog.w(TAG, "Unable to create context for heavy notification", e);
5713 }
5714
5715 }
5716
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005717 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5718 IBinder token, String resultWho, int requestCode, Intent[] intents,
5719 String[] resolvedTypes, int flags, Bundle bOptions) {
5720
5721 ActivityRecord activity = null;
5722 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5723 activity = ActivityRecord.isInStackLocked(token);
5724 if (activity == null) {
5725 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5726 return null;
5727 }
5728 if (activity.finishing) {
5729 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5730 return null;
5731 }
5732 }
5733
5734 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5735 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5736 bOptions);
5737 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5738 if (noCreate) {
5739 return rec;
5740 }
5741 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5742 if (activity.pendingResults == null) {
5743 activity.pendingResults = new HashSet<>();
5744 }
5745 activity.pendingResults.add(rec.ref);
5746 }
5747 return rec;
5748 }
5749
Andrii Kulian52d255c2018-07-13 11:32:19 -07005750 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005751 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005752 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005753 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5754 mCurAppTimeTracker.start(resumedActivity.packageName);
5755 }
5756 }
5757
5758 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5759 if (mTracedResumedActivity != null) {
5760 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5761 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5762 }
5763 if (resumed != null) {
5764 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5765 constructResumedTraceName(resumed.packageName), 0);
5766 }
5767 mTracedResumedActivity = resumed;
5768 }
5769
5770 private String constructResumedTraceName(String packageName) {
5771 return "focused app: " + packageName;
5772 }
5773
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005774 /** Applies latest configuration and/or visibility updates if needed. */
5775 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5776 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005777 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005778 // mainStack is null during startup.
5779 if (mainStack != null) {
5780 if (changes != 0 && starting == null) {
5781 // If the configuration changed, and the caller is not already
5782 // in the process of starting an activity, then find the top
5783 // activity to check if its configuration needs to change.
5784 starting = mainStack.topRunningActivityLocked();
5785 }
5786
5787 if (starting != null) {
5788 kept = starting.ensureActivityConfiguration(changes,
5789 false /* preserveWindow */);
5790 // And we need to make sure at this point that all other activities
5791 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005792 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005793 !PRESERVE_WINDOWS);
5794 }
5795 }
5796
5797 return kept;
5798 }
5799
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005800 void scheduleAppGcsLocked() {
5801 mH.post(() -> mAmInternal.scheduleAppGcs());
5802 }
5803
Wale Ogunwale53783742018-09-16 10:21:51 -07005804 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5805 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5806 }
5807
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005808 /**
5809 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5810 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5811 * on demand.
5812 */
5813 IPackageManager getPackageManager() {
5814 return AppGlobals.getPackageManager();
5815 }
5816
5817 PackageManagerInternal getPackageManagerInternalLocked() {
5818 if (mPmInternal == null) {
5819 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5820 }
5821 return mPmInternal;
5822 }
5823
Wale Ogunwale008163e2018-07-23 23:11:08 -07005824 AppWarnings getAppWarningsLocked() {
5825 return mAppWarnings;
5826 }
5827
Wale Ogunwale214f3482018-10-04 11:00:47 -07005828 Intent getHomeIntent() {
5829 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5830 intent.setComponent(mTopComponent);
5831 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5832 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5833 intent.addCategory(Intent.CATEGORY_HOME);
5834 }
5835 return intent;
5836 }
5837
Chilun2ef71f72018-11-16 17:57:15 +08005838 /**
5839 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5840 * activities.
5841 *
5842 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5843 * component defined in config_secondaryHomeComponent.
5844 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5845 */
5846 Intent getSecondaryHomeIntent(String preferredPackage) {
5847 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005848 if (preferredPackage == null) {
5849 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005850 final String secondaryHomeComponent = mContext.getResources().getString(
5851 com.android.internal.R.string.config_secondaryHomeComponent);
5852 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5853 } else {
5854 intent.setPackage(preferredPackage);
5855 }
5856 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5857 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5858 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5859 }
5860 return intent;
5861 }
5862
Wale Ogunwale214f3482018-10-04 11:00:47 -07005863 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5864 if (info == null) return null;
5865 ApplicationInfo newInfo = new ApplicationInfo(info);
5866 newInfo.initForUser(userId);
5867 return newInfo;
5868 }
5869
Wale Ogunwale9c103022018-10-18 07:44:54 -07005870 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005871 if (uid == SYSTEM_UID) {
5872 // The system gets to run in any process. If there are multiple processes with the same
5873 // uid, just pick the first (this should never happen).
5874 final SparseArray<WindowProcessController> procs =
5875 mProcessNames.getMap().get(processName);
5876 if (procs == null) return null;
5877 final int procCount = procs.size();
5878 for (int i = 0; i < procCount; i++) {
5879 final int procUid = procs.keyAt(i);
5880 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5881 // Don't use an app process or different user process for system component.
5882 continue;
5883 }
5884 return procs.valueAt(i);
5885 }
5886 }
5887
5888 return mProcessNames.get(processName, uid);
5889 }
5890
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005891 WindowProcessController getProcessController(IApplicationThread thread) {
5892 if (thread == null) {
5893 return null;
5894 }
5895
5896 final IBinder threadBinder = thread.asBinder();
5897 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5898 for (int i = pmap.size()-1; i >= 0; i--) {
5899 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5900 for (int j = procs.size() - 1; j >= 0; j--) {
5901 final WindowProcessController proc = procs.valueAt(j);
5902 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5903 return proc;
5904 }
5905 }
5906 }
5907
5908 return null;
5909 }
5910
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005911 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005912 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005913 if (proc == null) return null;
5914 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5915 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005916 }
5917 return null;
5918 }
5919
Riddle Hsua0536432019-02-16 00:38:59 +08005920 int getUidState(int uid) {
5921 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005922 }
5923
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005924 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005925 // A uid is considered to be foreground if it has a visible non-toast window.
5926 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005927 }
5928
Ricky Wai96f5c352019-04-10 18:40:17 +01005929 boolean isDeviceOwner(int uid) {
5930 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005931 }
5932
Ricky Wai96f5c352019-04-10 18:40:17 +01005933 void setDeviceOwnerUid(int uid) {
5934 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005935 }
5936
Wale Ogunwale9de19442018-10-18 19:05:03 -07005937 /**
5938 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5939 * the whitelist
5940 */
5941 String getPendingTempWhitelistTagForUidLocked(int uid) {
5942 return mPendingTempWhitelist.get(uid);
5943 }
5944
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005945 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5946 if (true || Build.IS_USER) {
5947 return;
5948 }
5949
5950 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5951 StrictMode.allowThreadDiskWrites();
5952 try {
5953 File tracesDir = new File("/data/anr");
5954 File tracesFile = null;
5955 try {
5956 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5957
5958 StringBuilder sb = new StringBuilder();
5959 Time tobj = new Time();
5960 tobj.set(System.currentTimeMillis());
5961 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5962 sb.append(": ");
5963 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5964 sb.append(" since ");
5965 sb.append(msg);
5966 FileOutputStream fos = new FileOutputStream(tracesFile);
5967 fos.write(sb.toString().getBytes());
5968 if (app == null) {
5969 fos.write("\n*** No application process!".getBytes());
5970 }
5971 fos.close();
5972 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5973 } catch (IOException e) {
5974 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5975 return;
5976 }
5977
5978 if (app != null && app.getPid() > 0) {
5979 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5980 firstPids.add(app.getPid());
5981 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5982 }
5983
5984 File lastTracesFile = null;
5985 File curTracesFile = null;
5986 for (int i=9; i>=0; i--) {
5987 String name = String.format(Locale.US, "slow%02d.txt", i);
5988 curTracesFile = new File(tracesDir, name);
5989 if (curTracesFile.exists()) {
5990 if (lastTracesFile != null) {
5991 curTracesFile.renameTo(lastTracesFile);
5992 } else {
5993 curTracesFile.delete();
5994 }
5995 }
5996 lastTracesFile = curTracesFile;
5997 }
5998 tracesFile.renameTo(curTracesFile);
5999 } finally {
6000 StrictMode.setThreadPolicy(oldPolicy);
6001 }
6002 }
6003
Michal Karpinskida34cd42019-04-02 19:46:52 +01006004 boolean isAssociatedCompanionApp(int userId, int uid) {
6005 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6006 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006007 return false;
6008 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006009 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006010 }
6011
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006012 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006013 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006014
6015
Wale Ogunwale98875612018-10-12 07:53:02 -07006016 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6017 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006018
Riddle Hsud93a6c42018-11-29 21:50:06 +08006019 H(Looper looper) {
6020 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006021 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006022
6023 @Override
6024 public void handleMessage(Message msg) {
6025 switch (msg.what) {
6026 case REPORT_TIME_TRACKER_MSG: {
6027 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6028 tracker.deliverResult(mContext);
6029 } break;
6030 }
6031 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006032 }
6033
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006034 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006035 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006036
6037 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006038 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006039 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006040
6041 @Override
6042 public void handleMessage(Message msg) {
6043 switch (msg.what) {
6044 case DISMISS_DIALOG_UI_MSG: {
6045 final Dialog d = (Dialog) msg.obj;
6046 d.dismiss();
6047 break;
6048 }
6049 }
6050 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006051 }
6052
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 final class LocalService extends ActivityTaskManagerInternal {
6054 @Override
6055 public SleepToken acquireSleepToken(String tag, int displayId) {
6056 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006057 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006058 }
6059
6060 @Override
6061 public ComponentName getHomeActivityForUser(int userId) {
6062 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006063 final ActivityRecord homeActivity =
6064 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006065 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 }
6067 }
6068
6069 @Override
6070 public void onLocalVoiceInteractionStarted(IBinder activity,
6071 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6072 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006073 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006074 }
6075 }
6076
6077 @Override
6078 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6079 synchronized (mGlobalLock) {
6080 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6081 reasons, timestamp);
6082 }
6083 }
6084
6085 @Override
6086 public void notifyAppTransitionFinished() {
6087 synchronized (mGlobalLock) {
6088 mStackSupervisor.notifyAppTransitionDone();
6089 }
6090 }
6091
6092 @Override
6093 public void notifyAppTransitionCancelled() {
6094 synchronized (mGlobalLock) {
6095 mStackSupervisor.notifyAppTransitionDone();
6096 }
6097 }
6098
6099 @Override
6100 public List<IBinder> getTopVisibleActivities() {
6101 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006102 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006103 }
6104 }
6105
6106 @Override
6107 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6108 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006109 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 }
6111 }
6112
6113 @Override
6114 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6115 Bundle bOptions) {
6116 Preconditions.checkNotNull(intents, "intents");
6117 final String[] resolvedTypes = new String[intents.length];
6118
6119 // UID of the package on user userId.
6120 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6121 // packageUid may not be initialized.
6122 int packageUid = 0;
6123 final long ident = Binder.clearCallingIdentity();
6124
6125 try {
6126 for (int i = 0; i < intents.length; i++) {
6127 resolvedTypes[i] =
6128 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6129 }
6130
6131 packageUid = AppGlobals.getPackageManager().getPackageUid(
6132 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6133 } catch (RemoteException e) {
6134 // Shouldn't happen.
6135 } finally {
6136 Binder.restoreCallingIdentity(ident);
6137 }
6138
Riddle Hsu591bf612019-02-14 17:55:31 +08006139 return getActivityStartController().startActivitiesInPackage(
6140 packageUid, packageName,
6141 intents, resolvedTypes, null /* resultTo */,
6142 SafeActivityOptions.fromBundle(bOptions), userId,
6143 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6144 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 }
6146
6147 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006148 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6149 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6150 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6151 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006152 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006153 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006154 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6155 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6156 userId, validateIncomingUser, originatingPendingIntent,
6157 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006158 }
6159 }
6160
6161 @Override
6162 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6163 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6164 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6165 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006166 PendingIntentRecord originatingPendingIntent,
6167 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006168 synchronized (mGlobalLock) {
6169 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6170 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6171 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006172 validateIncomingUser, originatingPendingIntent,
6173 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006174 }
6175 }
6176
6177 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6179 Intent intent, Bundle options, int userId) {
6180 return ActivityTaskManagerService.this.startActivityAsUser(
6181 caller, callerPacakge, intent,
6182 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6183 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6184 false /*validateIncomingUser*/);
6185 }
6186
6187 @Override
lumark588a3e82018-07-20 18:53:54 +08006188 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 synchronized (mGlobalLock) {
6190
6191 // We might change the visibilities here, so prepare an empty app transition which
6192 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006193 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006194 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006195 if (activityDisplay == null) {
6196 return;
6197 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006198 final DisplayContent dc = activityDisplay.mDisplayContent;
6199 final boolean wasTransitionSet =
6200 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006202 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006203 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006204 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205
6206 // If there was a transition set already we don't want to interfere with it as we
6207 // might be starting it too early.
6208 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006209 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006210 }
6211 }
6212 if (callback != null) {
6213 callback.run();
6214 }
6215 }
6216
6217 @Override
6218 public void notifyKeyguardTrustedChanged() {
6219 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006220 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006221 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 }
6223 }
6224 }
6225
6226 /**
6227 * Called after virtual display Id is updated by
6228 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6229 * {@param vrVr2dDisplayId}.
6230 */
6231 @Override
6232 public void setVr2dDisplayId(int vr2dDisplayId) {
6233 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6234 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006235 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 }
6237 }
6238
6239 @Override
6240 public void setFocusedActivity(IBinder token) {
6241 synchronized (mGlobalLock) {
6242 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6243 if (r == null) {
6244 throw new IllegalArgumentException(
6245 "setFocusedActivity: No activity record matching token=" + token);
6246 }
Louis Chang19443452018-10-09 12:10:21 +08006247 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006248 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250 }
6251 }
6252
6253 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006255 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 }
6257
6258 @Override
6259 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006260 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006261 }
6262
6263 @Override
6264 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006265 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006266 }
6267
6268 @Override
6269 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6270 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6271 }
6272
6273 @Override
6274 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006275 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006277
6278 @Override
6279 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6280 synchronized (mGlobalLock) {
6281 mActiveVoiceInteractionServiceComponent = component;
6282 }
6283 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006284
6285 @Override
6286 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6287 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6288 return;
6289 }
6290 synchronized (mGlobalLock) {
6291 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6292 if (types == null) {
6293 if (uid < 0) {
6294 return;
6295 }
6296 types = new ArrayMap<>();
6297 mAllowAppSwitchUids.put(userId, types);
6298 }
6299 if (uid < 0) {
6300 types.remove(type);
6301 } else {
6302 types.put(type, uid);
6303 }
6304 }
6305 }
6306
6307 @Override
6308 public void onUserStopped(int userId) {
6309 synchronized (mGlobalLock) {
6310 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6311 mAllowAppSwitchUids.remove(userId);
6312 }
6313 }
6314
6315 @Override
6316 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6317 synchronized (mGlobalLock) {
6318 return ActivityTaskManagerService.this.isGetTasksAllowed(
6319 caller, callingPid, callingUid);
6320 }
6321 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006322
Riddle Hsua0536432019-02-16 00:38:59 +08006323 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006324 @Override
6325 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006326 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006327 mProcessNames.put(proc.mName, proc.mUid, proc);
6328 }
6329 }
6330
Riddle Hsua0536432019-02-16 00:38:59 +08006331 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006332 @Override
6333 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006334 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006335 mProcessNames.remove(name, uid);
6336 }
6337 }
6338
Riddle Hsua0536432019-02-16 00:38:59 +08006339 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006340 @Override
6341 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006343 if (proc == mHomeProcess) {
6344 mHomeProcess = null;
6345 }
6346 if (proc == mPreviousProcess) {
6347 mPreviousProcess = null;
6348 }
6349 }
6350 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006351
Riddle Hsua0536432019-02-16 00:38:59 +08006352 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006353 @Override
6354 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006355 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006356 return mTopProcessState;
6357 }
6358 }
6359
Riddle Hsua0536432019-02-16 00:38:59 +08006360 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006361 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006362 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006363 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006364 return proc == mHeavyWeightProcess;
6365 }
6366 }
6367
Riddle Hsua0536432019-02-16 00:38:59 +08006368 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006369 @Override
6370 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006371 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006372 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6373 }
6374 }
6375
6376 @Override
6377 public void finishHeavyWeightApp() {
6378 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006379 if (mHeavyWeightProcess != null) {
6380 mHeavyWeightProcess.finishActivities();
6381 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006382 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6383 mHeavyWeightProcess);
6384 }
6385 }
6386
Riddle Hsua0536432019-02-16 00:38:59 +08006387 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006388 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006389 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006390 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006391 return isSleepingLocked();
6392 }
6393 }
6394
6395 @Override
6396 public boolean isShuttingDown() {
6397 synchronized (mGlobalLock) {
6398 return mShuttingDown;
6399 }
6400 }
6401
6402 @Override
6403 public boolean shuttingDown(boolean booted, int timeout) {
6404 synchronized (mGlobalLock) {
6405 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006406 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006407 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006408 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006409 return mStackSupervisor.shutdownLocked(timeout);
6410 }
6411 }
6412
6413 @Override
6414 public void enableScreenAfterBoot(boolean booted) {
6415 synchronized (mGlobalLock) {
6416 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6417 SystemClock.uptimeMillis());
6418 mWindowManager.enableScreenAfterBoot();
6419 updateEventDispatchingLocked(booted);
6420 }
6421 }
6422
6423 @Override
6424 public boolean showStrictModeViolationDialog() {
6425 synchronized (mGlobalLock) {
6426 return mShowDialogs && !mSleeping && !mShuttingDown;
6427 }
6428 }
6429
6430 @Override
6431 public void showSystemReadyErrorDialogsIfNeeded() {
6432 synchronized (mGlobalLock) {
6433 try {
6434 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6435 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6436 + " data partition or your device will be unstable.");
6437 mUiHandler.post(() -> {
6438 if (mShowDialogs) {
6439 AlertDialog d = new BaseErrorDialog(mUiContext);
6440 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6441 d.setCancelable(false);
6442 d.setTitle(mUiContext.getText(R.string.android_system_label));
6443 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6444 d.setButton(DialogInterface.BUTTON_POSITIVE,
6445 mUiContext.getText(R.string.ok),
6446 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6447 d.show();
6448 }
6449 });
6450 }
6451 } catch (RemoteException e) {
6452 }
6453
6454 if (!Build.isBuildConsistent()) {
6455 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6456 mUiHandler.post(() -> {
6457 if (mShowDialogs) {
6458 AlertDialog d = new BaseErrorDialog(mUiContext);
6459 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6460 d.setCancelable(false);
6461 d.setTitle(mUiContext.getText(R.string.android_system_label));
6462 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6463 d.setButton(DialogInterface.BUTTON_POSITIVE,
6464 mUiContext.getText(R.string.ok),
6465 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6466 d.show();
6467 }
6468 });
6469 }
6470 }
6471 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006472
6473 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006474 public void onProcessMapped(int pid, WindowProcessController proc) {
6475 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006476 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006477 }
6478 }
6479
6480 @Override
6481 public void onProcessUnMapped(int pid) {
6482 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006483 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006484 }
6485 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006486
6487 @Override
6488 public void onPackageDataCleared(String name) {
6489 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006490 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006491 mAppWarnings.onPackageDataCleared(name);
6492 }
6493 }
6494
6495 @Override
6496 public void onPackageUninstalled(String name) {
6497 synchronized (mGlobalLock) {
6498 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006499 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006500 }
6501 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006502
6503 @Override
6504 public void onPackageAdded(String name, boolean replacing) {
6505 synchronized (mGlobalLock) {
6506 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6507 }
6508 }
6509
6510 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006511 public void onPackageReplaced(ApplicationInfo aInfo) {
6512 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006513 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006514 }
6515 }
6516
6517 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006518 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6519 synchronized (mGlobalLock) {
6520 return compatibilityInfoForPackageLocked(ai);
6521 }
6522 }
6523
Yunfan Chen75157d72018-07-27 14:47:21 +09006524 /**
6525 * Set the corresponding display information for the process global configuration. To be
6526 * called when we need to show IME on a different display.
6527 *
6528 * @param pid The process id associated with the IME window.
6529 * @param displayId The ID of the display showing the IME.
6530 */
6531 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006532 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006533 // Don't update process-level configuration for Multi-Client IME process since other
6534 // IMEs on other displays will also receive this configuration change due to IME
6535 // services use the same application config/context.
6536 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006537
Yunfan Chen75157d72018-07-27 14:47:21 +09006538 if (pid == MY_PID || pid < 0) {
6539 if (DEBUG_CONFIGURATION) {
6540 Slog.w(TAG,
6541 "Trying to update display configuration for system/invalid process.");
6542 }
6543 return;
6544 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006545 synchronized (mGlobalLock) {
6546 final ActivityDisplay activityDisplay =
6547 mRootActivityContainer.getActivityDisplay(displayId);
6548 if (activityDisplay == null) {
6549 // Call might come when display is not yet added or has been removed.
6550 if (DEBUG_CONFIGURATION) {
6551 Slog.w(TAG, "Trying to update display configuration for non-existing "
6552 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006553 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006554 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006555 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006556 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006557 if (process == null) {
6558 if (DEBUG_CONFIGURATION) {
6559 Slog.w(TAG, "Trying to update display configuration for invalid "
6560 + "process, pid=" + pid);
6561 }
6562 return;
6563 }
6564 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6565 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006566 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006567
6568 @Override
6569 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6570 int requestCode, int resultCode, Intent data) {
6571 synchronized (mGlobalLock) {
6572 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006573 if (r != null && r.getActivityStack() != null) {
6574 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6575 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006576 }
6577 }
6578 }
6579
6580 @Override
6581 public void clearPendingResultForActivity(IBinder activityToken,
6582 WeakReference<PendingIntentRecord> pir) {
6583 synchronized (mGlobalLock) {
6584 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6585 if (r != null && r.pendingResults != null) {
6586 r.pendingResults.remove(pir);
6587 }
6588 }
6589 }
6590
6591 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006592 public ActivityTokens getTopActivityForTask(int taskId) {
6593 synchronized (mGlobalLock) {
6594 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6595 if (taskRecord == null) {
6596 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6597 + " Requested task not found");
6598 return null;
6599 }
6600 final ActivityRecord activity = taskRecord.getTopActivity();
6601 if (activity == null) {
6602 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6603 + " Requested activity not found");
6604 return null;
6605 }
6606 if (!activity.attachedToProcess()) {
6607 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6608 + activity);
6609 return null;
6610 }
6611 return new ActivityTokens(activity.appToken, activity.assistToken,
6612 activity.app.getThread());
6613 }
6614 }
6615
6616 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006617 public IIntentSender getIntentSender(int type, String packageName,
6618 int callingUid, int userId, IBinder token, String resultWho,
6619 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6620 Bundle bOptions) {
6621 synchronized (mGlobalLock) {
6622 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6623 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6624 }
6625 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006626
6627 @Override
6628 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6629 synchronized (mGlobalLock) {
6630 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6631 if (r == null) {
6632 return null;
6633 }
6634 if (r.mServiceConnectionsHolder == null) {
6635 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6636 ActivityTaskManagerService.this, r);
6637 }
6638
6639 return r.mServiceConnectionsHolder;
6640 }
6641 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006642
6643 @Override
6644 public Intent getHomeIntent() {
6645 synchronized (mGlobalLock) {
6646 return ActivityTaskManagerService.this.getHomeIntent();
6647 }
6648 }
6649
6650 @Override
6651 public boolean startHomeActivity(int userId, String reason) {
6652 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006653 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006654 }
6655 }
6656
6657 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006658 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006659 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006660 synchronized (mGlobalLock) {
6661 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006662 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006663 }
Chilun8b1f1be2019-03-13 17:14:36 +08006664 }
6665
6666 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006667 public boolean startHomeOnAllDisplays(int userId, String reason) {
6668 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006669 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006670 }
6671 }
6672
Riddle Hsua0536432019-02-16 00:38:59 +08006673 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006674 @Override
6675 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006676 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006677 if (mFactoryTest == FACTORY_TEST_OFF) {
6678 return false;
6679 }
6680 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6681 && wpc.mName.equals(mTopComponent.getPackageName())) {
6682 return true;
6683 }
6684 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6685 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6686 }
6687 }
6688
6689 @Override
6690 public void updateTopComponentForFactoryTest() {
6691 synchronized (mGlobalLock) {
6692 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6693 return;
6694 }
6695 final ResolveInfo ri = mContext.getPackageManager()
6696 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6697 final CharSequence errorMsg;
6698 if (ri != null) {
6699 final ActivityInfo ai = ri.activityInfo;
6700 final ApplicationInfo app = ai.applicationInfo;
6701 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6702 mTopAction = Intent.ACTION_FACTORY_TEST;
6703 mTopData = null;
6704 mTopComponent = new ComponentName(app.packageName, ai.name);
6705 errorMsg = null;
6706 } else {
6707 errorMsg = mContext.getResources().getText(
6708 com.android.internal.R.string.factorytest_not_system);
6709 }
6710 } else {
6711 errorMsg = mContext.getResources().getText(
6712 com.android.internal.R.string.factorytest_no_action);
6713 }
6714 if (errorMsg == null) {
6715 return;
6716 }
6717
6718 mTopAction = null;
6719 mTopData = null;
6720 mTopComponent = null;
6721 mUiHandler.post(() -> {
6722 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6723 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006724 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006725 });
6726 }
6727 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006728
Riddle Hsua0536432019-02-16 00:38:59 +08006729 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 @Override
6731 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6732 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006733 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006735 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006736
6737 wpc.clearRecentTasks();
6738 wpc.clearActivities();
6739
6740 if (wpc.isInstrumenting()) {
6741 finishInstrumentationCallback.run();
6742 }
6743
Jorim Jaggid0752812018-10-16 16:07:20 +02006744 if (!restarting && hasVisibleActivities) {
6745 mWindowManager.deferSurfaceLayout();
6746 try {
6747 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6748 // If there was nothing to resume, and we are not already restarting
6749 // this process, but there is a visible activity that is hosted by the
6750 // process...then make sure all visible activities are running, taking
6751 // care of restarting this process.
6752 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6753 !PRESERVE_WINDOWS);
6754 }
6755 } finally {
6756 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006757 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 }
6759 }
6760 }
6761
6762 @Override
6763 public void closeSystemDialogs(String reason) {
6764 enforceNotIsolatedCaller("closeSystemDialogs");
6765
6766 final int pid = Binder.getCallingPid();
6767 final int uid = Binder.getCallingUid();
6768 final long origId = Binder.clearCallingIdentity();
6769 try {
6770 synchronized (mGlobalLock) {
6771 // Only allow this from foreground processes, so that background
6772 // applications can't abuse it to prevent system UI from being shown.
6773 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006774 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006775 if (!proc.isPerceptible()) {
6776 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6777 + " from background process " + proc);
6778 return;
6779 }
6780 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781 mWindowManager.closeSystemDialogs(reason);
6782
Wale Ogunwaled32da472018-11-16 07:19:28 -08006783 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006785 // Call into AM outside the synchronized block.
6786 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 } finally {
6788 Binder.restoreCallingIdentity(origId);
6789 }
6790 }
6791
6792 @Override
6793 public void cleanupDisabledPackageComponents(
6794 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6795 synchronized (mGlobalLock) {
6796 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006797 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006799 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800 mStackSupervisor.scheduleIdleLocked();
6801 }
6802
6803 // Clean-up disabled tasks
6804 getRecentTasks().cleanupDisabledPackageTasksLocked(
6805 packageName, disabledClasses, userId);
6806 }
6807 }
6808
6809 @Override
6810 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6811 int userId) {
6812 synchronized (mGlobalLock) {
6813
6814 boolean didSomething =
6815 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006816 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 null, doit, evenPersistent, userId);
6818 return didSomething;
6819 }
6820 }
6821
6822 @Override
6823 public void resumeTopActivities(boolean scheduleIdle) {
6824 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006825 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006826 if (scheduleIdle) {
6827 mStackSupervisor.scheduleIdleLocked();
6828 }
6829 }
6830 }
6831
Riddle Hsua0536432019-02-16 00:38:59 +08006832 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 @Override
6834 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006835 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6837 }
6838 }
6839
Riddle Hsua0536432019-02-16 00:38:59 +08006840 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006841 @Override
6842 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006843 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006844 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 }
6846 }
6847
6848 @Override
6849 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6850 try {
6851 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6852 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6853 }
6854 } catch (RemoteException ex) {
6855 throw new SecurityException("Fail to check is caller a privileged app", ex);
6856 }
6857
6858 synchronized (mGlobalLock) {
6859 final long ident = Binder.clearCallingIdentity();
6860 try {
6861 if (mAmInternal.shouldConfirmCredentials(userId)) {
6862 if (mKeyguardController.isKeyguardLocked()) {
6863 // Showing launcher to avoid user entering credential twice.
6864 startHomeActivity(currentUserId, "notifyLockedProfile");
6865 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006866 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868 } finally {
6869 Binder.restoreCallingIdentity(ident);
6870 }
6871 }
6872 }
6873
6874 @Override
6875 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6876 mAmInternal.enforceCallingPermission(
6877 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6878
6879 synchronized (mGlobalLock) {
6880 final long ident = Binder.clearCallingIdentity();
6881 try {
6882 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6883 FLAG_ACTIVITY_TASK_ON_HOME);
6884 ActivityOptions activityOptions = options != null
6885 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006886 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006887 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006888 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006889 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006890 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006891 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6892 UserHandle.CURRENT);
6893 } finally {
6894 Binder.restoreCallingIdentity(ident);
6895 }
6896 }
6897 }
6898
6899 @Override
6900 public void writeActivitiesToProto(ProtoOutputStream proto) {
6901 synchronized (mGlobalLock) {
6902 // The output proto of "activity --proto activities"
6903 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006904 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006905 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6906 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 }
6908 }
6909
6910 @Override
6911 public void saveANRState(String reason) {
6912 synchronized (mGlobalLock) {
6913 final StringWriter sw = new StringWriter();
6914 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6915 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6916 if (reason != null) {
6917 pw.println(" Reason: " + reason);
6918 }
6919 pw.println();
6920 getActivityStartController().dump(pw, " ", null);
6921 pw.println();
6922 pw.println("-------------------------------------------------------------------------------");
6923 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6924 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6925 "" /* header */);
6926 pw.println();
6927 pw.close();
6928
6929 mLastANRState = sw.toString();
6930 }
6931 }
6932
6933 @Override
6934 public void clearSavedANRState() {
6935 synchronized (mGlobalLock) {
6936 mLastANRState = null;
6937 }
6938 }
6939
6940 @Override
6941 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6942 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6943 synchronized (mGlobalLock) {
6944 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6945 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6946 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6947 dumpLastANRLocked(pw);
6948 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6949 dumpLastANRTracesLocked(pw);
6950 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6951 dumpActivityStarterLocked(pw, dumpPackage);
6952 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6953 dumpActivityContainersLocked(pw);
6954 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6955 if (getRecentTasks() != null) {
6956 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6957 }
6958 }
6959 }
6960 }
6961
6962 @Override
6963 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6964 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6965 int wakefulness) {
6966 synchronized (mGlobalLock) {
6967 if (mHomeProcess != null && (dumpPackage == null
6968 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6969 if (needSep) {
6970 pw.println();
6971 needSep = false;
6972 }
6973 pw.println(" mHomeProcess: " + mHomeProcess);
6974 }
6975 if (mPreviousProcess != null && (dumpPackage == null
6976 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6977 if (needSep) {
6978 pw.println();
6979 needSep = false;
6980 }
6981 pw.println(" mPreviousProcess: " + mPreviousProcess);
6982 }
6983 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6984 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6985 StringBuilder sb = new StringBuilder(128);
6986 sb.append(" mPreviousProcessVisibleTime: ");
6987 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6988 pw.println(sb);
6989 }
6990 if (mHeavyWeightProcess != null && (dumpPackage == null
6991 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6992 if (needSep) {
6993 pw.println();
6994 needSep = false;
6995 }
6996 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6997 }
6998 if (dumpPackage == null) {
6999 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007000 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007001 }
7002 if (dumpAll) {
7003 if (dumpPackage == null) {
7004 pw.println(" mConfigWillChange: "
7005 + getTopDisplayFocusedStack().mConfigWillChange);
7006 }
7007 if (mCompatModePackages.getPackages().size() > 0) {
7008 boolean printed = false;
7009 for (Map.Entry<String, Integer> entry
7010 : mCompatModePackages.getPackages().entrySet()) {
7011 String pkg = entry.getKey();
7012 int mode = entry.getValue();
7013 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7014 continue;
7015 }
7016 if (!printed) {
7017 pw.println(" mScreenCompatPackages:");
7018 printed = true;
7019 }
7020 pw.println(" " + pkg + ": " + mode);
7021 }
7022 }
7023 }
7024
7025 if (dumpPackage == null) {
7026 pw.println(" mWakefulness="
7027 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007028 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007029 if (mRunningVoice != null) {
7030 pw.println(" mRunningVoice=" + mRunningVoice);
7031 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7032 }
7033 pw.println(" mSleeping=" + mSleeping);
7034 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7035 pw.println(" mVrController=" + mVrController);
7036 }
7037 if (mCurAppTimeTracker != null) {
7038 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7039 }
7040 if (mAllowAppSwitchUids.size() > 0) {
7041 boolean printed = false;
7042 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7043 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7044 for (int j = 0; j < types.size(); j++) {
7045 if (dumpPackage == null ||
7046 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7047 if (needSep) {
7048 pw.println();
7049 needSep = false;
7050 }
7051 if (!printed) {
7052 pw.println(" mAllowAppSwitchUids:");
7053 printed = true;
7054 }
7055 pw.print(" User ");
7056 pw.print(mAllowAppSwitchUids.keyAt(i));
7057 pw.print(": Type ");
7058 pw.print(types.keyAt(j));
7059 pw.print(" = ");
7060 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7061 pw.println();
7062 }
7063 }
7064 }
7065 }
7066 if (dumpPackage == null) {
7067 if (mController != null) {
7068 pw.println(" mController=" + mController
7069 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7070 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007071 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7072 pw.println(" mLaunchingActivityWakeLock="
7073 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007074 }
7075
7076 return needSep;
7077 }
7078 }
7079
7080 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007081 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7082 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 synchronized (mGlobalLock) {
7084 if (dumpPackage == null) {
7085 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7086 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007087 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7088 if (mRunningVoice != null) {
7089 final long vrToken = proto.start(
7090 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7091 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7092 mRunningVoice.toString());
7093 mVoiceWakeLock.writeToProto(
7094 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7095 proto.end(vrToken);
7096 }
7097 mVrController.writeToProto(proto,
7098 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 if (mController != null) {
7100 final long token = proto.start(CONTROLLER);
7101 proto.write(CONTROLLER, mController.toString());
7102 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7103 proto.end(token);
7104 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007105 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7106 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7107 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007108 }
7109
7110 if (mHomeProcess != null && (dumpPackage == null
7111 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007112 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114
7115 if (mPreviousProcess != null && (dumpPackage == null
7116 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007117 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007118 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7119 }
7120
7121 if (mHeavyWeightProcess != null && (dumpPackage == null
7122 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007123 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 }
7125
7126 for (Map.Entry<String, Integer> entry
7127 : mCompatModePackages.getPackages().entrySet()) {
7128 String pkg = entry.getKey();
7129 int mode = entry.getValue();
7130 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7131 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7132 proto.write(PACKAGE, pkg);
7133 proto.write(MODE, mode);
7134 proto.end(compatToken);
7135 }
7136 }
7137
7138 if (mCurAppTimeTracker != null) {
7139 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7140 }
7141
7142 }
7143 }
7144
7145 @Override
7146 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7147 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7148 boolean dumpFocusedStackOnly) {
7149 synchronized (mGlobalLock) {
7150 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7151 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7152 }
7153 }
7154
7155 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007156 public void dumpForOom(PrintWriter pw) {
7157 synchronized (mGlobalLock) {
7158 pw.println(" mHomeProcess: " + mHomeProcess);
7159 pw.println(" mPreviousProcess: " + mPreviousProcess);
7160 if (mHeavyWeightProcess != null) {
7161 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7162 }
7163 }
7164 }
7165
7166 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 public boolean canGcNow() {
7168 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007169 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 }
7171 }
7172
Riddle Hsua0536432019-02-16 00:38:59 +08007173 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 @Override
7175 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007176 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007177 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007178 return top != null ? top.app : null;
7179 }
7180 }
7181
Riddle Hsua0536432019-02-16 00:38:59 +08007182 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 @Override
7184 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007185 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007186 if (mRootActivityContainer != null) {
7187 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 }
7189 }
7190 }
7191
7192 @Override
7193 public void scheduleDestroyAllActivities(String reason) {
7194 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007195 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007196 }
7197 }
7198
7199 @Override
7200 public void removeUser(int userId) {
7201 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007202 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 }
7204 }
7205
7206 @Override
7207 public boolean switchUser(int userId, UserState userState) {
7208 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007209 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 }
7211 }
7212
7213 @Override
7214 public void onHandleAppCrash(WindowProcessController wpc) {
7215 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007216 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 }
7218 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007219
7220 @Override
7221 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7222 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007223 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007224 }
7225 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007226
Riddle Hsua0536432019-02-16 00:38:59 +08007227 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007228 @Override
7229 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007230 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007231 }
7232
Riddle Hsua0536432019-02-16 00:38:59 +08007233 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007234 @Override
7235 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007236 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007237 }
7238
Riddle Hsua0536432019-02-16 00:38:59 +08007239 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007240 @Override
7241 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007242 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007243 }
7244
Riddle Hsua0536432019-02-16 00:38:59 +08007245 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007246 @Override
7247 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007248 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007249 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007250
7251 @Override
7252 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007253 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007254 mPendingTempWhitelist.put(uid, tag);
7255 }
7256 }
7257
7258 @Override
7259 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007260 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007261 mPendingTempWhitelist.remove(uid);
7262 }
7263 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007264
7265 @Override
7266 public boolean handleAppCrashInActivityController(String processName, int pid,
7267 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7268 Runnable killCrashingAppCallback) {
7269 synchronized (mGlobalLock) {
7270 if (mController == null) {
7271 return false;
7272 }
7273
7274 try {
7275 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7276 stackTrace)) {
7277 killCrashingAppCallback.run();
7278 return true;
7279 }
7280 } catch (RemoteException e) {
7281 mController = null;
7282 Watchdog.getInstance().setActivityController(null);
7283 }
7284 return false;
7285 }
7286 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007287
7288 @Override
7289 public void removeRecentTasksByPackageName(String packageName, int userId) {
7290 synchronized (mGlobalLock) {
7291 mRecentTasks.removeTasksByPackageName(packageName, userId);
7292 }
7293 }
7294
7295 @Override
7296 public void cleanupRecentTasksForUser(int userId) {
7297 synchronized (mGlobalLock) {
7298 mRecentTasks.cleanupLocked(userId);
7299 }
7300 }
7301
7302 @Override
7303 public void loadRecentTasksForUser(int userId) {
7304 synchronized (mGlobalLock) {
7305 mRecentTasks.loadUserRecentsLocked(userId);
7306 }
7307 }
7308
7309 @Override
7310 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7311 synchronized (mGlobalLock) {
7312 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7313 }
7314 }
7315
7316 @Override
7317 public void flushRecentTasks() {
7318 mRecentTasks.flush();
7319 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007320
7321 @Override
7322 public WindowProcessController getHomeProcess() {
7323 synchronized (mGlobalLock) {
7324 return mHomeProcess;
7325 }
7326 }
7327
7328 @Override
7329 public WindowProcessController getPreviousProcess() {
7330 synchronized (mGlobalLock) {
7331 return mPreviousProcess;
7332 }
7333 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007334
7335 @Override
7336 public void clearLockedTasks(String reason) {
7337 synchronized (mGlobalLock) {
7338 getLockTaskController().clearLockedTasks(reason);
7339 }
7340 }
7341
7342 @Override
7343 public void updateUserConfiguration() {
7344 synchronized (mGlobalLock) {
7345 final Configuration configuration = new Configuration(getGlobalConfiguration());
7346 final int currentUserId = mAmInternal.getCurrentUserId();
7347 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7348 configuration, currentUserId, Settings.System.canWrite(mContext));
7349 updateConfigurationLocked(configuration, null /* starting */,
7350 false /* initLocale */, false /* persistent */, currentUserId,
7351 false /* deferResume */);
7352 }
7353 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007354
7355 @Override
7356 public boolean canShowErrorDialogs() {
7357 synchronized (mGlobalLock) {
7358 return mShowDialogs && !mSleeping && !mShuttingDown
7359 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7360 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7361 mAmInternal.getCurrentUserId())
7362 && !(UserManager.isDeviceInDemoMode(mContext)
7363 && mAmInternal.getCurrentUser().isDemo());
7364 }
7365 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007366
7367 @Override
7368 public void setProfileApp(String profileApp) {
7369 synchronized (mGlobalLock) {
7370 mProfileApp = profileApp;
7371 }
7372 }
7373
7374 @Override
7375 public void setProfileProc(WindowProcessController wpc) {
7376 synchronized (mGlobalLock) {
7377 mProfileProc = wpc;
7378 }
7379 }
7380
7381 @Override
7382 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7383 synchronized (mGlobalLock) {
7384 mProfilerInfo = profilerInfo;
7385 }
7386 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007387
7388 @Override
7389 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7390 synchronized (mGlobalLock) {
7391 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7392 }
7393 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007394
7395 @Override
7396 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7397 synchronized (mGlobalLock) {
7398 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7399 }
7400 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007401
7402 @Override
7403 public boolean isUidForeground(int uid) {
7404 synchronized (mGlobalLock) {
7405 return ActivityTaskManagerService.this.isUidForeground(uid);
7406 }
7407 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007408
7409 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007410 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007411 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007412 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007413 }
7414 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007415
7416 @Override
7417 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007418 // Translate package names into UIDs
7419 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007420 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007421 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7422 if (uid >= 0) {
7423 result.add(uid);
7424 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007425 }
7426 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007427 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007428 }
7429 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007430 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007431}