blob: 5fabde45db55bb5619082d2361257e0e04bcfe30 [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;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700263import com.android.server.pm.UserManagerService;
264import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266
Wale Ogunwale31913b52018-10-13 08:29:31 -0700267import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700270import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700273import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700274import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700275import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700277import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700278import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400280import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700283import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Map;
285import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286
287/**
288 * System service for managing activities and their containers (task, stacks, displays,... ).
289 *
290 * {@hide}
291 */
292public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700293 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700295 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
296 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
297 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
298 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
299 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700300 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700302 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700303 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 /** Used to indicate that an app transition should be animated. */
308 static final boolean ANIMATE = true;
309
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700310 /** Hardware-reported OpenGLES version. */
311 final int GL_ES_VERSION;
312
Wale Ogunwale31913b52018-10-13 08:29:31 -0700313 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
314 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
315 public static final String DUMP_LASTANR_CMD = "lastanr" ;
316 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
317 public static final String DUMP_STARTER_CMD = "starter" ;
318 public static final String DUMP_CONTAINERS_CMD = "containers" ;
319 public static final String DUMP_RECENTS_CMD = "recents" ;
320 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
321
Wale Ogunwale64258362018-10-16 15:13:37 -0700322 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
323 public static final int RELAUNCH_REASON_NONE = 0;
324 /** This activity is being relaunched due to windowing mode change. */
325 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
326 /** This activity is being relaunched due to a free-resize operation. */
327 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
328
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700329 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700330
Wale Ogunwalef6733932018-06-27 05:14:34 -0700331 /**
332 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
333 * change at runtime. Use mContext for non-UI purposes.
334 */
335 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700336 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700337 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700340 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700341 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800342 @VisibleForTesting
343 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 PowerManagerInternal mPowerManagerInternal;
345 private UsageStatsManagerInternal mUsageStatsInternal;
346
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700347 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 IntentFirewall mIntentFirewall;
349
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700350 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800351 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700352 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800353 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700355 private UserManagerService mUserManager;
356 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700357 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700358 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
359 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700360 /** All processes currently running that might have a window organized by name. */
361 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700362 /** All processes we currently have running mapped by pid */
363 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700364 /** This is the process holding what we currently consider to be the "home" activity. */
365 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700366 /** The currently running heavy-weight process, if any. */
367 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700368 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700369 /**
370 * This is the process holding the activity the user last visited that is in a different process
371 * from the one they are currently in.
372 */
373 WindowProcessController mPreviousProcess;
374 /** The time at which the previous process was last visible. */
375 long mPreviousProcessVisibleTime;
376
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 /** List of intents that were used to start the most recent tasks. */
378 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700379 /** State of external calls telling us if the device is awake or asleep. */
380 private boolean mKeyguardShown = false;
381
382 // Wrapper around VoiceInteractionServiceManager
383 private AssistUtils mAssistUtils;
384
385 // VoiceInteraction session ID that changes for each new request except when
386 // being called for multi-window assist in a single session.
387 private int mViSessionId = 1000;
388
389 // How long to wait in getAssistContextExtras for the activity and foreground services
390 // to respond with the result.
391 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
392
393 // How long top wait when going through the modern assist (which doesn't need to block
394 // on getting this result before starting to launch its UI).
395 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
396
397 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
398 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
399
Alison Cichowlas3e340502018-08-07 17:15:01 -0400400 // Permission tokens are used to temporarily granted a trusted app the ability to call
401 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
402 // showing any appropriate error messages to the user.
403 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
404 10 * MINUTE_IN_MILLIS;
405
406 // How long before the service actually expires a token. This is slightly longer than
407 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
408 // expiration exception.
409 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
410 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
411
412 // How long the service will remember expired tokens, for the purpose of providing error
413 // messaging when a client uses an expired token.
414 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
415 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
416
417 // Activity tokens of system activities that are delegating their call to
418 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
419 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
420
421 // Permission tokens that have expired, but we remember for error reporting.
422 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700424 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
425
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700426 // Keeps track of the active voice interaction service component, notified from
427 // VoiceInteractionManagerService
428 ComponentName mActiveVoiceInteractionServiceComponent;
429
Wale Ogunwalee2172292018-10-25 10:11:10 -0700430 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700431 KeyguardController mKeyguardController;
432 private final ClientLifecycleManager mLifecycleManager;
433 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700434 /** The controller for all operations related to locktask. */
435 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700436 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700438 boolean mSuppressResizeConfigChanges;
439
440 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
441 new UpdateConfigurationResult();
442
443 static final class UpdateConfigurationResult {
444 // Configuration changes that were updated.
445 int changes;
446 // If the activity was relaunched to match the new configuration.
447 boolean activityRelaunched;
448
449 void reset() {
450 changes = 0;
451 activityRelaunched = false;
452 }
453 }
454
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700455 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700456 private int mConfigurationSeq;
457 // To cache the list of supported system locales
458 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700459
460 /**
461 * Temp object used when global and/or display override configuration is updated. It is also
462 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
463 * anyone...
464 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700465 private Configuration mTempConfig = new Configuration();
466
Wale Ogunwalef6733932018-06-27 05:14:34 -0700467 /** Temporary to avoid allocations. */
468 final StringBuilder mStringBuilder = new StringBuilder(256);
469
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700470 // Amount of time after a call to stopAppSwitches() during which we will
471 // prevent further untrusted switches from happening.
472 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
473
474 /**
475 * The time at which we will allow normal application switches again,
476 * after a call to {@link #stopAppSwitches()}.
477 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 /**
480 * This is set to true after the first switch after mAppSwitchesAllowedTime
481 * is set; any switches after that will clear the time.
482 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484
485 IActivityController mController = null;
486 boolean mControllerIsAMonkey = false;
487
Wale Ogunwale214f3482018-10-04 11:00:47 -0700488 final int mFactoryTest;
489
490 /** Used to control how we initialize the service. */
491 ComponentName mTopComponent;
492 String mTopAction = Intent.ACTION_MAIN;
493 String mTopData;
494
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800495 /** Profiling app information. */
496 String mProfileApp = null;
497 WindowProcessController mProfileProc = null;
498 ProfilerInfo mProfilerInfo = null;
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700501 * Dump of the activity state at the time of the last ANR. Cleared after
502 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
503 */
504 String mLastANRState;
505
506 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 * Used to retain an update lock when the foreground activity is in
508 * immersive mode.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
512 /**
513 * Packages that are being allowed to perform unrestricted app switches. Mapping is
514 * User -> Type -> uid.
515 */
516 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
517
518 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700519 private int mThumbnailWidth;
520 private int mThumbnailHeight;
521 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Flag that indicates if multi-window is enabled.
525 *
526 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
527 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
528 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
529 * At least one of the forms of multi-window must be enabled in order for this flag to be
530 * initialized to 'true'.
531 *
532 * @see #mSupportsSplitScreenMultiWindow
533 * @see #mSupportsFreeformWindowManagement
534 * @see #mSupportsPictureInPicture
535 * @see #mSupportsMultiDisplay
536 */
537 boolean mSupportsMultiWindow;
538 boolean mSupportsSplitScreenMultiWindow;
539 boolean mSupportsFreeformWindowManagement;
540 boolean mSupportsPictureInPicture;
541 boolean mSupportsMultiDisplay;
542 boolean mForceResizableActivities;
543
544 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
545
546 // VR Vr2d Display Id.
547 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700548
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 /**
550 * Set while we are wanting to sleep, to prevent any
551 * activities from being started/resumed.
552 *
553 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
554 *
555 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
556 * while in the sleep state until there is a pending transition out of sleep, in which case
557 * mSleeping is set to false, and remains false while awake.
558 *
559 * Whether mSleeping can quickly toggled between true/false without the device actually
560 * display changing states is undefined.
561 */
562 private boolean mSleeping = false;
563
564 /**
565 * The process state used for processes that are running the top activities.
566 * This changes between TOP and TOP_SLEEPING to following mSleeping.
567 */
568 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
569
570 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
571 // automatically. Important for devices without direct input devices.
572 private boolean mShowDialogs = true;
573
574 /** Set if we are shutting down the system, similar to sleeping. */
575 boolean mShuttingDown = false;
576
577 /**
578 * We want to hold a wake lock while running a voice interaction session, since
579 * this may happen with the screen off and we need to keep the CPU running to
580 * be able to continue to interact with the user.
581 */
582 PowerManager.WakeLock mVoiceWakeLock;
583
584 /**
585 * Set while we are running a voice interaction. This overrides sleeping while it is active.
586 */
587 IVoiceInteractionSession mRunningVoice;
588
589 /**
590 * The last resumed activity. This is identical to the current resumed activity most
591 * of the time but could be different when we're pausing one activity before we resume
592 * another activity.
593 */
594 ActivityRecord mLastResumedActivity;
595
596 /**
597 * The activity that is currently being traced as the active resumed activity.
598 *
599 * @see #updateResumedAppTrace
600 */
601 private @Nullable ActivityRecord mTracedResumedActivity;
602
603 /** If non-null, we are tracking the time the user spends in the currently focused app. */
604 AppTimeTracker mCurAppTimeTracker;
605
Wale Ogunwale008163e2018-07-23 23:11:08 -0700606 private AppWarnings mAppWarnings;
607
Wale Ogunwale53783742018-09-16 10:21:51 -0700608 /**
609 * Packages that the user has asked to have run in screen size
610 * compatibility mode instead of filling the screen.
611 */
612 CompatModePackages mCompatModePackages;
613
Wale Ogunwalef6733932018-06-27 05:14:34 -0700614 private FontScaleSettingObserver mFontScaleSettingObserver;
615
616 private final class FontScaleSettingObserver extends ContentObserver {
617 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
618 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
619
620 public FontScaleSettingObserver() {
621 super(mH);
622 final ContentResolver resolver = mContext.getContentResolver();
623 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
624 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
625 UserHandle.USER_ALL);
626 }
627
628 @Override
629 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
630 if (mFontScaleUri.equals(uri)) {
631 updateFontScaleIfNeeded(userId);
632 } else if (mHideErrorDialogsUri.equals(uri)) {
633 synchronized (mGlobalLock) {
634 updateShouldShowDialogsLocked(getGlobalConfiguration());
635 }
636 }
637 }
638 }
639
Charles Chen8d98dd22018-12-26 17:36:54 +0800640 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
641 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700642 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700643 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700644 mSystemThread = ActivityThread.currentActivityThread();
645 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700646 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800647 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700648 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700649 }
650
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700651 public void onSystemReady() {
652 synchronized (mGlobalLock) {
653 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
654 PackageManager.FEATURE_CANT_SAVE_STATE);
655 mAssistUtils = new AssistUtils(mContext);
656 mVrController.onSystemReady();
657 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700658 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700659 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700660 }
661
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700662 public void onInitPowerManagement() {
663 synchronized (mGlobalLock) {
664 mStackSupervisor.initPowerManagement();
665 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
666 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
667 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
668 mVoiceWakeLock.setReferenceCounted(false);
669 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 mFontScaleSettingObserver = new FontScaleSettingObserver();
674 }
675
Wale Ogunwale59507092018-10-29 09:00:30 -0700676 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700677 final boolean freeformWindowManagement =
678 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
679 || Settings.Global.getInt(
680 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
681
682 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
683 final boolean supportsPictureInPicture = supportsMultiWindow &&
684 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
685 final boolean supportsSplitScreenMultiWindow =
686 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
687 final boolean supportsMultiDisplay = mContext.getPackageManager()
688 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700689 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
690 final boolean forceResizable = Settings.Global.getInt(
691 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700692 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700693
694 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900695 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700696
697 final Configuration configuration = new Configuration();
698 Settings.System.getConfiguration(resolver, configuration);
699 if (forceRtl) {
700 // This will take care of setting the correct layout direction flags
701 configuration.setLayoutDirection(configuration.locale);
702 }
703
704 synchronized (mGlobalLock) {
705 mForceResizableActivities = forceResizable;
706 final boolean multiWindowFormEnabled = freeformWindowManagement
707 || supportsSplitScreenMultiWindow
708 || supportsPictureInPicture
709 || supportsMultiDisplay;
710 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
711 mSupportsMultiWindow = true;
712 mSupportsFreeformWindowManagement = freeformWindowManagement;
713 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
714 mSupportsPictureInPicture = supportsPictureInPicture;
715 mSupportsMultiDisplay = supportsMultiDisplay;
716 } else {
717 mSupportsMultiWindow = false;
718 mSupportsFreeformWindowManagement = false;
719 mSupportsSplitScreenMultiWindow = false;
720 mSupportsPictureInPicture = false;
721 mSupportsMultiDisplay = false;
722 }
723 mWindowManager.setForceResizableTasks(mForceResizableActivities);
724 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700725 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
726 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727 // This happens before any activities are started, so we can change global configuration
728 // in-place.
729 updateConfigurationLocked(configuration, null, true);
730 final Configuration globalConfig = getGlobalConfiguration();
731 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
732
733 // Load resources only after the current configuration has been set.
734 final Resources res = mContext.getResources();
735 mThumbnailWidth = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_width);
737 mThumbnailHeight = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_height);
739
740 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
741 mFullscreenThumbnailScale = (float) res
742 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
743 (float) globalConfig.screenWidthDp;
744 } else {
745 mFullscreenThumbnailScale = res.getFraction(
746 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
747 }
748 }
749 }
750
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800751 public WindowManagerGlobalLock getGlobalLock() {
752 return mGlobalLock;
753 }
754
Riddle Hsud93a6c42018-11-29 21:50:06 +0800755 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
756 Looper looper) {
757 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700759 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700760 final File systemDir = SystemServiceManager.ensureSystemDir();
761 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
762 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700763 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700764
765 mTempConfig.setToDefaults();
766 mTempConfig.setLocales(LocaleList.getDefault());
767 mConfigurationSeq = mTempConfig.seq = 1;
768 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800769 mRootActivityContainer = new RootActivityContainer(this);
770 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700771
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700772 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700774 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700775 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700776 mRecentTasks = createRecentTasks();
777 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700779 mKeyguardController = mStackSupervisor.getKeyguardController();
780 }
781
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700782 public void onActivityManagerInternalAdded() {
783 synchronized (mGlobalLock) {
784 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
785 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
786 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700787 }
788
Yunfan Chen75157d72018-07-27 14:47:21 +0900789 int increaseConfigurationSeqLocked() {
790 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
791 return mConfigurationSeq;
792 }
793
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700794 protected ActivityStackSupervisor createStackSupervisor() {
795 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
796 supervisor.initialize();
797 return supervisor;
798 }
799
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700800 public void setWindowManager(WindowManagerService wm) {
801 synchronized (mGlobalLock) {
802 mWindowManager = wm;
803 mLockTaskController.setWindowManager(wm);
804 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800805 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700806 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700807 }
808
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700809 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
810 synchronized (mGlobalLock) {
811 mUsageStatsInternal = usageStatsManager;
812 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700813 }
814
Wale Ogunwalef6733932018-06-27 05:14:34 -0700815 UserManagerService getUserManager() {
816 if (mUserManager == null) {
817 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
818 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
819 }
820 return mUserManager;
821 }
822
823 AppOpsService getAppOpsService() {
824 if (mAppOpsService == null) {
825 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
826 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
827 }
828 return mAppOpsService;
829 }
830
831 boolean hasUserRestriction(String restriction, int userId) {
832 return getUserManager().hasUserRestriction(restriction, userId);
833 }
834
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700835 protected RecentTasks createRecentTasks() {
836 return new RecentTasks(this, mStackSupervisor);
837 }
838
839 RecentTasks getRecentTasks() {
840 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700841 }
842
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700843 ClientLifecycleManager getLifecycleManager() {
844 return mLifecycleManager;
845 }
846
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700847 ActivityStartController getActivityStartController() {
848 return mActivityStartController;
849 }
850
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700851 TaskChangeNotificationController getTaskChangeNotificationController() {
852 return mTaskChangeNotificationController;
853 }
854
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700855 LockTaskController getLockTaskController() {
856 return mLockTaskController;
857 }
858
Yunfan Chen75157d72018-07-27 14:47:21 +0900859 /**
860 * Return the global configuration used by the process corresponding to the input pid. This is
861 * usually the global configuration with some overrides specific to that process.
862 */
863 Configuration getGlobalConfigurationForCallingPid() {
864 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800865 return getGlobalConfigurationForPid(pid);
866 }
867
868 /**
869 * Return the global configuration used by the process corresponding to the given pid.
870 */
871 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900872 if (pid == MY_PID || pid < 0) {
873 return getGlobalConfiguration();
874 }
875 synchronized (mGlobalLock) {
876 final WindowProcessController app = mPidMap.get(pid);
877 return app != null ? app.getConfiguration() : getGlobalConfiguration();
878 }
879 }
880
881 /**
882 * Return the device configuration info used by the process corresponding to the input pid.
883 * The value is consistent with the global configuration for the process.
884 */
885 @Override
886 public ConfigurationInfo getDeviceConfigurationInfo() {
887 ConfigurationInfo config = new ConfigurationInfo();
888 synchronized (mGlobalLock) {
889 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
890 config.reqTouchScreen = globalConfig.touchscreen;
891 config.reqKeyboardType = globalConfig.keyboard;
892 config.reqNavigation = globalConfig.navigation;
893 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
894 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
895 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
896 }
897 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
898 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
899 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
900 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700901 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900902 }
903 return config;
904 }
905
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700906 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700907 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700908 }
909
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700910 public static final class Lifecycle extends SystemService {
911 private final ActivityTaskManagerService mService;
912
913 public Lifecycle(Context context) {
914 super(context);
915 mService = new ActivityTaskManagerService(context);
916 }
917
918 @Override
919 public void onStart() {
920 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700921 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700922 }
923
Garfield Tan891146c2018-10-09 12:14:00 -0700924 @Override
925 public void onUnlockUser(int userId) {
926 synchronized (mService.getGlobalLock()) {
927 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
928 }
929 }
930
931 @Override
932 public void onCleanupUser(int userId) {
933 synchronized (mService.getGlobalLock()) {
934 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
935 }
936 }
937
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700938 public ActivityTaskManagerService getService() {
939 return mService;
940 }
941 }
942
943 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700944 public final int startActivity(IApplicationThread caller, String callingPackage,
945 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
946 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
947 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
948 resultWho, requestCode, startFlags, profilerInfo, bOptions,
949 UserHandle.getCallingUserId());
950 }
951
952 @Override
953 public final int startActivities(IApplicationThread caller, String callingPackage,
954 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
955 int userId) {
956 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700957 enforceNotIsolatedCaller(reason);
958 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700959 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000960 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
961 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
962 reason, null /* originatingPendingIntent */,
963 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700964 }
965
966 @Override
967 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
968 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
969 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
970 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
971 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
972 true /*validateIncomingUser*/);
973 }
974
975 int startActivityAsUser(IApplicationThread caller, String callingPackage,
976 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
977 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
978 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700979 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700981 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700982 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
983
984 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700985 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 .setCaller(caller)
987 .setCallingPackage(callingPackage)
988 .setResolvedType(resolvedType)
989 .setResultTo(resultTo)
990 .setResultWho(resultWho)
991 .setRequestCode(requestCode)
992 .setStartFlags(startFlags)
993 .setProfilerInfo(profilerInfo)
994 .setActivityOptions(bOptions)
995 .setMayWait(userId)
996 .execute();
997
998 }
999
1000 @Override
1001 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1002 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001003 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1004 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001005 // Refuse possible leaked file descriptors
1006 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1007 throw new IllegalArgumentException("File descriptors passed in Intent");
1008 }
1009
1010 if (!(target instanceof PendingIntentRecord)) {
1011 throw new IllegalArgumentException("Bad PendingIntent object");
1012 }
1013
1014 PendingIntentRecord pir = (PendingIntentRecord)target;
1015
1016 synchronized (mGlobalLock) {
1017 // If this is coming from the currently resumed activity, it is
1018 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001019 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 if (stack.mResumedActivity != null &&
1021 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001022 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 }
1024 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001025 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1031 Bundle bOptions) {
1032 // Refuse possible leaked file descriptors
1033 if (intent != null && intent.hasFileDescriptors()) {
1034 throw new IllegalArgumentException("File descriptors passed in Intent");
1035 }
1036 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1037
1038 synchronized (mGlobalLock) {
1039 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1040 if (r == null) {
1041 SafeActivityOptions.abort(options);
1042 return false;
1043 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001044 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // The caller is not running... d'oh!
1046 SafeActivityOptions.abort(options);
1047 return false;
1048 }
1049 intent = new Intent(intent);
1050 // The caller is not allowed to change the data.
1051 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1052 // And we are resetting to find the next component...
1053 intent.setComponent(null);
1054
1055 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1056
1057 ActivityInfo aInfo = null;
1058 try {
1059 List<ResolveInfo> resolves =
1060 AppGlobals.getPackageManager().queryIntentActivities(
1061 intent, r.resolvedType,
1062 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1063 UserHandle.getCallingUserId()).getList();
1064
1065 // Look for the original activity in the list...
1066 final int N = resolves != null ? resolves.size() : 0;
1067 for (int i=0; i<N; i++) {
1068 ResolveInfo rInfo = resolves.get(i);
1069 if (rInfo.activityInfo.packageName.equals(r.packageName)
1070 && rInfo.activityInfo.name.equals(r.info.name)) {
1071 // We found the current one... the next matching is
1072 // after it.
1073 i++;
1074 if (i<N) {
1075 aInfo = resolves.get(i).activityInfo;
1076 }
1077 if (debug) {
1078 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1079 + "/" + r.info.name);
1080 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1081 ? "null" : aInfo.packageName + "/" + aInfo.name));
1082 }
1083 break;
1084 }
1085 }
1086 } catch (RemoteException e) {
1087 }
1088
1089 if (aInfo == null) {
1090 // Nobody who is next!
1091 SafeActivityOptions.abort(options);
1092 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1093 return false;
1094 }
1095
1096 intent.setComponent(new ComponentName(
1097 aInfo.applicationInfo.packageName, aInfo.name));
1098 intent.setFlags(intent.getFlags()&~(
1099 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1100 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1101 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1102 FLAG_ACTIVITY_NEW_TASK));
1103
1104 // Okay now we need to start the new activity, replacing the currently running activity.
1105 // This is a little tricky because we want to start the new one as if the current one is
1106 // finished, but not finish the current one first so that there is no flicker.
1107 // And thus...
1108 final boolean wasFinishing = r.finishing;
1109 r.finishing = true;
1110
1111 // Propagate reply information over to the new activity.
1112 final ActivityRecord resultTo = r.resultTo;
1113 final String resultWho = r.resultWho;
1114 final int requestCode = r.requestCode;
1115 r.resultTo = null;
1116 if (resultTo != null) {
1117 resultTo.removeResultsLocked(r, resultWho, requestCode);
1118 }
1119
1120 final long origId = Binder.clearCallingIdentity();
1121 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001122 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 .setResolvedType(r.resolvedType)
1126 .setActivityInfo(aInfo)
1127 .setResultTo(resultTo != null ? resultTo.appToken : null)
1128 .setResultWho(resultWho)
1129 .setRequestCode(requestCode)
1130 .setCallingPid(-1)
1131 .setCallingUid(r.launchedFromUid)
1132 .setCallingPackage(r.launchedFromPackage)
1133 .setRealCallingPid(-1)
1134 .setRealCallingUid(r.launchedFromUid)
1135 .setActivityOptions(options)
1136 .execute();
1137 Binder.restoreCallingIdentity(origId);
1138
1139 r.finishing = wasFinishing;
1140 if (res != ActivityManager.START_SUCCESS) {
1141 return false;
1142 }
1143 return true;
1144 }
1145 }
1146
1147 @Override
1148 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1149 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1150 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1151 final WaitResult res = new WaitResult();
1152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001153 enforceNotIsolatedCaller("startActivityAndWait");
1154 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1155 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001156 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001157 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001158 .setCaller(caller)
1159 .setCallingPackage(callingPackage)
1160 .setResolvedType(resolvedType)
1161 .setResultTo(resultTo)
1162 .setResultWho(resultWho)
1163 .setRequestCode(requestCode)
1164 .setStartFlags(startFlags)
1165 .setActivityOptions(bOptions)
1166 .setMayWait(userId)
1167 .setProfilerInfo(profilerInfo)
1168 .setWaitResult(res)
1169 .execute();
1170 }
1171 return res;
1172 }
1173
1174 @Override
1175 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1176 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1177 int startFlags, Configuration config, Bundle bOptions, int userId) {
1178 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001179 enforceNotIsolatedCaller("startActivityWithConfig");
1180 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1181 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001183 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001184 .setCaller(caller)
1185 .setCallingPackage(callingPackage)
1186 .setResolvedType(resolvedType)
1187 .setResultTo(resultTo)
1188 .setResultWho(resultWho)
1189 .setRequestCode(requestCode)
1190 .setStartFlags(startFlags)
1191 .setGlobalConfiguration(config)
1192 .setActivityOptions(bOptions)
1193 .setMayWait(userId)
1194 .execute();
1195 }
1196 }
1197
Alison Cichowlas3e340502018-08-07 17:15:01 -04001198
1199 @Override
1200 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1201 int callingUid = Binder.getCallingUid();
1202 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1203 throw new SecurityException("Only the system process can request a permission token, "
1204 + "received request from uid: " + callingUid);
1205 }
1206 IBinder permissionToken = new Binder();
1207 synchronized (mGlobalLock) {
1208 mStartActivitySources.put(permissionToken, delegatorToken);
1209 }
1210
1211 Message expireMsg = PooledLambda.obtainMessage(
1212 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1213 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1214
1215 Message forgetMsg = PooledLambda.obtainMessage(
1216 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1217 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1218
1219 return permissionToken;
1220 }
1221
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 @Override
1223 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1224 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001225 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1226 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001228 // permission grants) as any app that may launch one of your own activities. So we only
1229 // allow this in two cases:
1230 // 1) The caller is an activity that is part of the core framework, and then only when it
1231 // is running as the system.
1232 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1233 // can only be requested by a system activity, which may then delegate this call to
1234 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 final ActivityRecord sourceRecord;
1236 final int targetUid;
1237 final String targetPackage;
1238 final boolean isResolver;
1239 synchronized (mGlobalLock) {
1240 if (resultTo == null) {
1241 throw new SecurityException("Must be called from an activity");
1242 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001243 final IBinder sourceToken;
1244 if (permissionToken != null) {
1245 // To even attempt to use a permissionToken, an app must also have this signature
1246 // permission.
1247 mAmInternal.enforceCallingPermission(
1248 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1249 "startActivityAsCaller");
1250 // If called with a permissionToken, we want the sourceRecord from the delegator
1251 // activity that requested this token.
1252 sourceToken = mStartActivitySources.remove(permissionToken);
1253 if (sourceToken == null) {
1254 // Invalid permissionToken, check if it recently expired.
1255 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1256 throw new SecurityException("Called with expired permission token: "
1257 + permissionToken);
1258 } else {
1259 throw new SecurityException("Called with invalid permission token: "
1260 + permissionToken);
1261 }
1262 }
1263 } else {
1264 // This method was called directly by the source.
1265 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267
Wale Ogunwaled32da472018-11-16 07:19:28 -08001268 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269 if (sourceRecord == null) {
1270 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 }
1272 if (sourceRecord.app == null) {
1273 throw new SecurityException("Called without a process attached to activity");
1274 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001275
1276 // Whether called directly or from a delegate, the source activity must be from the
1277 // android package.
1278 if (!sourceRecord.info.packageName.equals("android")) {
1279 throw new SecurityException("Must be called from an activity that is "
1280 + "declared in the android package");
1281 }
1282
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001283 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 // This is still okay, as long as this activity is running under the
1285 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001286 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001288 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 + " must be system uid or original calling uid "
1290 + sourceRecord.launchedFromUid);
1291 }
1292 }
1293 if (ignoreTargetSecurity) {
1294 if (intent.getComponent() == null) {
1295 throw new SecurityException(
1296 "Component must be specified with ignoreTargetSecurity");
1297 }
1298 if (intent.getSelector() != null) {
1299 throw new SecurityException(
1300 "Selector not allowed with ignoreTargetSecurity");
1301 }
1302 }
1303 targetUid = sourceRecord.launchedFromUid;
1304 targetPackage = sourceRecord.launchedFromPackage;
1305 isResolver = sourceRecord.isResolverOrChildActivity();
1306 }
1307
1308 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001309 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 }
1311
1312 // TODO: Switch to user app stacks here.
1313 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001314 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001315 .setCallingUid(targetUid)
1316 .setCallingPackage(targetPackage)
1317 .setResolvedType(resolvedType)
1318 .setResultTo(resultTo)
1319 .setResultWho(resultWho)
1320 .setRequestCode(requestCode)
1321 .setStartFlags(startFlags)
1322 .setActivityOptions(bOptions)
1323 .setMayWait(userId)
1324 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1325 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1326 .execute();
1327 } catch (SecurityException e) {
1328 // XXX need to figure out how to propagate to original app.
1329 // A SecurityException here is generally actually a fault of the original
1330 // calling activity (such as a fairly granting permissions), so propagate it
1331 // back to them.
1332 /*
1333 StringBuilder msg = new StringBuilder();
1334 msg.append("While launching");
1335 msg.append(intent.toString());
1336 msg.append(": ");
1337 msg.append(e.getMessage());
1338 */
1339 throw e;
1340 }
1341 }
1342
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001343 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1344 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1345 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1346 }
1347
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 @Override
1349 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1350 Intent intent, String resolvedType, IVoiceInteractionSession session,
1351 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1352 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 if (session == null || interactor == null) {
1355 throw new NullPointerException("null session or interactor");
1356 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001357 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001359 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 .setCallingUid(callingUid)
1361 .setCallingPackage(callingPackage)
1362 .setResolvedType(resolvedType)
1363 .setVoiceSession(session)
1364 .setVoiceInteractor(interactor)
1365 .setStartFlags(startFlags)
1366 .setProfilerInfo(profilerInfo)
1367 .setActivityOptions(bOptions)
1368 .setMayWait(userId)
1369 .execute();
1370 }
1371
1372 @Override
1373 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1374 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001375 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1376 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(callingUid)
1380 .setCallingPackage(callingPackage)
1381 .setResolvedType(resolvedType)
1382 .setActivityOptions(bOptions)
1383 .setMayWait(userId)
1384 .execute();
1385 }
1386
1387 @Override
1388 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1389 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001390 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 final int callingPid = Binder.getCallingPid();
1392 final long origId = Binder.clearCallingIdentity();
1393 try {
1394 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001395 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1396 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397
1398 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1400 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1402 recentsUid, assistDataReceiver);
1403 }
1404 } finally {
1405 Binder.restoreCallingIdentity(origId);
1406 }
1407 }
1408
1409 @Override
1410 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 "startActivityFromRecents()");
1413
1414 final int callingPid = Binder.getCallingPid();
1415 final int callingUid = Binder.getCallingUid();
1416 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1417 final long origId = Binder.clearCallingIdentity();
1418 try {
1419 synchronized (mGlobalLock) {
1420 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1421 safeOptions);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(origId);
1425 }
1426 }
1427
1428 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001429 * Public API to check if the client is allowed to start an activity on specified display.
1430 *
1431 * If the target display is private or virtual, some restrictions will apply.
1432 *
1433 * @param displayId Target display id.
1434 * @param intent Intent used to launch the activity.
1435 * @param resolvedType The MIME type of the intent.
1436 * @param userId The id of the user for whom the call is made.
1437 * @return {@code true} if a call to start an activity on the target display should succeed and
1438 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1439 */
1440 @Override
1441 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1442 String resolvedType, int userId) {
1443 final int callingUid = Binder.getCallingUid();
1444 final int callingPid = Binder.getCallingPid();
1445 final long origId = Binder.clearCallingIdentity();
1446
1447 try {
1448 // Collect information about the target of the Intent.
1449 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1450 0 /* startFlags */, null /* profilerInfo */, userId,
1451 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1452 UserHandle.USER_NULL));
1453 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1454
1455 synchronized (mGlobalLock) {
1456 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1457 aInfo);
1458 }
1459 } finally {
1460 Binder.restoreCallingIdentity(origId);
1461 }
1462 }
1463
1464 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 * This is the internal entry point for handling Activity.finish().
1466 *
1467 * @param token The Binder token referencing the Activity we want to finish.
1468 * @param resultCode Result code, if any, from this Activity.
1469 * @param resultData Result data (Intent), if any, from this Activity.
1470 * @param finishTask Whether to finish the task associated with this Activity.
1471 *
1472 * @return Returns true if the activity successfully finished, or false if it is still running.
1473 */
1474 @Override
1475 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1476 int finishTask) {
1477 // Refuse possible leaked file descriptors
1478 if (resultData != null && resultData.hasFileDescriptors()) {
1479 throw new IllegalArgumentException("File descriptors passed in Intent");
1480 }
1481
1482 synchronized (mGlobalLock) {
1483 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1484 if (r == null) {
1485 return true;
1486 }
1487 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001488 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 ActivityRecord rootR = tr.getRootActivity();
1490 if (rootR == null) {
1491 Slog.w(TAG, "Finishing task with all activities already finished");
1492 }
1493 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1494 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001495 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 return false;
1497 }
1498
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1500 // We should consolidate.
1501 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001503 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 if (next != null) {
1505 // ask watcher if this is allowed
1506 boolean resumeOK = true;
1507 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 Watchdog.getInstance().setActivityController(null);
1512 }
1513
1514 if (!resumeOK) {
1515 Slog.i(TAG, "Not finishing activity because controller resumed");
1516 return false;
1517 }
1518 }
1519 }
1520 final long origId = Binder.clearCallingIdentity();
1521 try {
1522 boolean res;
1523 final boolean finishWithRootActivity =
1524 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1525 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1526 || (finishWithRootActivity && r == rootR)) {
1527 // If requested, remove the task that is associated to this activity only if it
1528 // was the root activity in the task. The result code and data is ignored
1529 // because we don't support returning them across task boundaries. Also, to
1530 // keep backwards compatibility we remove the task from recents when finishing
1531 // task with root activity.
1532 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1533 finishWithRootActivity, "finish-activity");
1534 if (!res) {
1535 Slog.i(TAG, "Removing task failed to finish activity");
1536 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001537 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001538 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 } else {
1540 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1541 resultData, "app-request", true);
1542 if (!res) {
1543 Slog.i(TAG, "Failed to finish by app-request");
1544 }
1545 }
1546 return res;
1547 } finally {
1548 Binder.restoreCallingIdentity(origId);
1549 }
1550 }
1551 }
1552
1553 @Override
1554 public boolean finishActivityAffinity(IBinder token) {
1555 synchronized (mGlobalLock) {
1556 final long origId = Binder.clearCallingIdentity();
1557 try {
1558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1559 if (r == null) {
1560 return false;
1561 }
1562
1563 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1564 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001565 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001566 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 return false;
1568 }
1569 return task.getStack().finishActivityAffinityLocked(r);
1570 } finally {
1571 Binder.restoreCallingIdentity(origId);
1572 }
1573 }
1574 }
1575
1576 @Override
1577 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1578 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001579 try {
1580 WindowProcessController proc = null;
1581 synchronized (mGlobalLock) {
1582 ActivityStack stack = ActivityRecord.getStackLocked(token);
1583 if (stack == null) {
1584 return;
1585 }
1586 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1587 false /* fromTimeout */, false /* processPausingActivities */, config);
1588 if (r != null) {
1589 proc = r.app;
1590 }
1591 if (stopProfiling && proc != null) {
1592 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 }
1594 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001595 } finally {
1596 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 }
1599
1600 @Override
1601 public final void activityResumed(IBinder token) {
1602 final long origId = Binder.clearCallingIdentity();
1603 synchronized (mGlobalLock) {
1604 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001605 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 }
1607 Binder.restoreCallingIdentity(origId);
1608 }
1609
1610 @Override
1611 public final void activityPaused(IBinder token) {
1612 final long origId = Binder.clearCallingIdentity();
1613 synchronized (mGlobalLock) {
1614 ActivityStack stack = ActivityRecord.getStackLocked(token);
1615 if (stack != null) {
1616 stack.activityPausedLocked(token, false);
1617 }
1618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityStopped(IBinder token, Bundle icicle,
1624 PersistableBundle persistentState, CharSequence description) {
1625 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1626
1627 // Refuse possible leaked file descriptors
1628 if (icicle != null && icicle.hasFileDescriptors()) {
1629 throw new IllegalArgumentException("File descriptors passed in Bundle");
1630 }
1631
1632 final long origId = Binder.clearCallingIdentity();
1633
1634 synchronized (mGlobalLock) {
1635 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1636 if (r != null) {
1637 r.activityStoppedLocked(icicle, persistentState, description);
1638 }
1639 }
1640
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001641 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642
1643 Binder.restoreCallingIdentity(origId);
1644 }
1645
1646 @Override
1647 public final void activityDestroyed(IBinder token) {
1648 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1649 synchronized (mGlobalLock) {
1650 ActivityStack stack = ActivityRecord.getStackLocked(token);
1651 if (stack != null) {
1652 stack.activityDestroyedLocked(token, "activityDestroyed");
1653 }
1654 }
1655 }
1656
1657 @Override
1658 public final void activityRelaunched(IBinder token) {
1659 final long origId = Binder.clearCallingIdentity();
1660 synchronized (mGlobalLock) {
1661 mStackSupervisor.activityRelaunchedLocked(token);
1662 }
1663 Binder.restoreCallingIdentity(origId);
1664 }
1665
1666 public final void activitySlept(IBinder token) {
1667 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1668
1669 final long origId = Binder.clearCallingIdentity();
1670
1671 synchronized (mGlobalLock) {
1672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1673 if (r != null) {
1674 mStackSupervisor.activitySleptLocked(r);
1675 }
1676 }
1677
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680
1681 @Override
1682 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1683 synchronized (mGlobalLock) {
1684 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r == null) {
1686 return;
1687 }
1688 final long origId = Binder.clearCallingIdentity();
1689 try {
1690 r.setRequestedOrientation(requestedOrientation);
1691 } finally {
1692 Binder.restoreCallingIdentity(origId);
1693 }
1694 }
1695 }
1696
1697 @Override
1698 public int getRequestedOrientation(IBinder token) {
1699 synchronized (mGlobalLock) {
1700 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1701 if (r == null) {
1702 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1703 }
1704 return r.getRequestedOrientation();
1705 }
1706 }
1707
1708 @Override
1709 public void setImmersive(IBinder token, boolean immersive) {
1710 synchronized (mGlobalLock) {
1711 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1712 if (r == null) {
1713 throw new IllegalArgumentException();
1714 }
1715 r.immersive = immersive;
1716
1717 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001718 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001720 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 }
1722 }
1723 }
1724
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001725 void applyUpdateLockStateLocked(ActivityRecord r) {
1726 // Modifications to the UpdateLock state are done on our handler, outside
1727 // the activity manager's locks. The new state is determined based on the
1728 // state *now* of the relevant activity record. The object is passed to
1729 // the handler solely for logging detail, not to be consulted/modified.
1730 final boolean nextState = r != null && r.immersive;
1731 mH.post(() -> {
1732 if (mUpdateLock.isHeld() != nextState) {
1733 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1734 "Applying new update lock state '" + nextState + "' for " + r);
1735 if (nextState) {
1736 mUpdateLock.acquire();
1737 } else {
1738 mUpdateLock.release();
1739 }
1740 }
1741 });
1742 }
1743
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 @Override
1745 public boolean isImmersive(IBinder token) {
1746 synchronized (mGlobalLock) {
1747 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1748 if (r == null) {
1749 throw new IllegalArgumentException();
1750 }
1751 return r.immersive;
1752 }
1753 }
1754
1755 @Override
1756 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001759 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 return (r != null) ? r.immersive : false;
1761 }
1762 }
1763
1764 @Override
1765 public void overridePendingTransition(IBinder token, String packageName,
1766 int enterAnim, int exitAnim) {
1767 synchronized (mGlobalLock) {
1768 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1769 if (self == null) {
1770 return;
1771 }
1772
1773 final long origId = Binder.clearCallingIdentity();
1774
1775 if (self.isState(
1776 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001777 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001778 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
1780
1781 Binder.restoreCallingIdentity(origId);
1782 }
1783 }
1784
1785 @Override
1786 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001787 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001789 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 if (r == null) {
1791 return ActivityManager.COMPAT_MODE_UNKNOWN;
1792 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001793 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001794 }
1795 }
1796
1797 @Override
1798 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001801 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001803 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 if (r == null) {
1805 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1806 return;
1807 }
1808 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001809 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 }
1811 }
1812
1813 @Override
1814 public int getLaunchedFromUid(IBinder activityToken) {
1815 ActivityRecord srec;
1816 synchronized (mGlobalLock) {
1817 srec = ActivityRecord.forTokenLocked(activityToken);
1818 }
1819 if (srec == null) {
1820 return -1;
1821 }
1822 return srec.launchedFromUid;
1823 }
1824
1825 @Override
1826 public String getLaunchedFromPackage(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return null;
1833 }
1834 return srec.launchedFromPackage;
1835 }
1836
1837 @Override
1838 public boolean convertFromTranslucent(IBinder token) {
1839 final long origId = Binder.clearCallingIdentity();
1840 try {
1841 synchronized (mGlobalLock) {
1842 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1843 if (r == null) {
1844 return false;
1845 }
1846 final boolean translucentChanged = r.changeWindowTranslucency(true);
1847 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001848 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001850 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 return translucentChanged;
1852 }
1853 } finally {
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856 }
1857
1858 @Override
1859 public boolean convertToTranslucent(IBinder token, Bundle options) {
1860 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1861 final long origId = Binder.clearCallingIdentity();
1862 try {
1863 synchronized (mGlobalLock) {
1864 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1865 if (r == null) {
1866 return false;
1867 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001868 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 int index = task.mActivities.lastIndexOf(r);
1870 if (index > 0) {
1871 ActivityRecord under = task.mActivities.get(index - 1);
1872 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1873 }
1874 final boolean translucentChanged = r.changeWindowTranslucency(false);
1875 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001876 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001878 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001879 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 return translucentChanged;
1881 }
1882 } finally {
1883 Binder.restoreCallingIdentity(origId);
1884 }
1885 }
1886
1887 @Override
1888 public void notifyActivityDrawn(IBinder token) {
1889 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1890 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001891 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001893 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 }
1895 }
1896 }
1897
1898 @Override
1899 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1900 synchronized (mGlobalLock) {
1901 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1902 if (r == null) {
1903 return;
1904 }
1905 r.reportFullyDrawnLocked(restoredFromBundle);
1906 }
1907 }
1908
1909 @Override
1910 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1911 synchronized (mGlobalLock) {
1912 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1913 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1914 return stack.mDisplayId;
1915 }
1916 return DEFAULT_DISPLAY;
1917 }
1918 }
1919
1920 @Override
1921 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 long ident = Binder.clearCallingIdentity();
1924 try {
1925 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001926 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001928 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 return null;
1931 }
1932 } finally {
1933 Binder.restoreCallingIdentity(ident);
1934 }
1935 }
1936
1937 @Override
1938 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1941 final long callingId = Binder.clearCallingIdentity();
1942 try {
1943 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001944 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 if (stack == null) {
1946 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1947 return;
1948 }
1949 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001950 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001951 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 }
1953 }
1954 } finally {
1955 Binder.restoreCallingIdentity(callingId);
1956 }
1957 }
1958
1959 @Override
1960 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1963 final long callingId = Binder.clearCallingIdentity();
1964 try {
1965 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001966 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001967 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001968 if (task == null) {
1969 return;
1970 }
1971 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001972 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001973 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 }
1975 }
1976 } finally {
1977 Binder.restoreCallingIdentity(callingId);
1978 }
1979 }
1980
1981 @Override
1982 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001983 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001984 synchronized (mGlobalLock) {
1985 final long ident = Binder.clearCallingIdentity();
1986 try {
1987 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1988 "remove-task");
1989 } finally {
1990 Binder.restoreCallingIdentity(ident);
1991 }
1992 }
1993 }
1994
1995 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001996 public void removeAllVisibleRecentTasks() {
1997 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1998 synchronized (mGlobalLock) {
1999 final long ident = Binder.clearCallingIdentity();
2000 try {
2001 getRecentTasks().removeAllVisibleTasks();
2002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
2005 }
2006 }
2007
2008 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2010 synchronized (mGlobalLock) {
2011 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2012 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002013 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 }
2015 }
2016 return false;
2017 }
2018
2019 @Override
2020 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2021 Intent resultData) {
2022
2023 synchronized (mGlobalLock) {
2024 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2025 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002026 return r.getActivityStack().navigateUpToLocked(
2027 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 return false;
2030 }
2031 }
2032
2033 /**
2034 * Attempts to move a task backwards in z-order (the order of activities within the task is
2035 * unchanged).
2036 *
2037 * There are several possible results of this call:
2038 * - if the task is locked, then we will show the lock toast
2039 * - if there is a task behind the provided task, then that task is made visible and resumed as
2040 * this task is moved to the back
2041 * - otherwise, if there are no other tasks in the stack:
2042 * - if this task is in the pinned stack, then we remove the stack completely, which will
2043 * have the effect of moving the task to the top or bottom of the fullscreen stack
2044 * (depending on whether it is visible)
2045 * - otherwise, we simply return home and hide this task
2046 *
2047 * @param token A reference to the activity we wish to move
2048 * @param nonRoot If false then this only works if the activity is the root
2049 * of a task; if true it will work for any activity in a task.
2050 * @return Returns true if the move completed, false if not.
2051 */
2052 @Override
2053 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 synchronized (mGlobalLock) {
2056 final long origId = Binder.clearCallingIdentity();
2057 try {
2058 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 if (task != null) {
2061 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(origId);
2065 }
2066 }
2067 return false;
2068 }
2069
2070 @Override
2071 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 long ident = Binder.clearCallingIdentity();
2074 Rect rect = new Rect();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2079 if (task == null) {
2080 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2081 return rect;
2082 }
2083 if (task.getStack() != null) {
2084 // Return the bounds from window manager since it will be adjusted for various
2085 // things like the presense of a docked stack for tasks that aren't resizeable.
2086 task.getWindowContainerBounds(rect);
2087 } else {
2088 // Task isn't in window manager yet since it isn't associated with a stack.
2089 // Return the persist value from activity manager
2090 if (!task.matchParentBounds()) {
2091 rect.set(task.getBounds());
2092 } else if (task.mLastNonFullscreenBounds != null) {
2093 rect.set(task.mLastNonFullscreenBounds);
2094 }
2095 }
2096 }
2097 } finally {
2098 Binder.restoreCallingIdentity(ident);
2099 }
2100 return rect;
2101 }
2102
2103 @Override
2104 public ActivityManager.TaskDescription getTaskDescription(int id) {
2105 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002106 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002108 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2110 if (tr != null) {
2111 return tr.lastTaskDescription;
2112 }
2113 }
2114 return null;
2115 }
2116
2117 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002118 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2119 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2120 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2121 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2122 return;
2123 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002124 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002125 synchronized (mGlobalLock) {
2126 final long ident = Binder.clearCallingIdentity();
2127 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002128 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002129 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 if (task == null) {
2131 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2132 return;
2133 }
2134
2135 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2136 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2137
2138 if (!task.isActivityTypeStandardOrUndefined()) {
2139 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2140 + " non-standard task " + taskId + " to windowing mode="
2141 + windowingMode);
2142 }
2143
2144 final ActivityStack stack = task.getStack();
2145 if (toTop) {
2146 stack.moveToFront("setTaskWindowingMode", task);
2147 }
2148 stack.setWindowingMode(windowingMode);
2149 } finally {
2150 Binder.restoreCallingIdentity(ident);
2151 }
2152 }
2153 }
2154
2155 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 ActivityRecord r = getCallingRecordLocked(token);
2159 return r != null ? r.info.packageName : null;
2160 }
2161 }
2162
2163 @Override
2164 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002165 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 ActivityRecord r = getCallingRecordLocked(token);
2167 return r != null ? r.intent.getComponent() : null;
2168 }
2169 }
2170
2171 private ActivityRecord getCallingRecordLocked(IBinder token) {
2172 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2173 if (r == null) {
2174 return null;
2175 }
2176 return r.resultTo;
2177 }
2178
2179 @Override
2180 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002181 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182
2183 synchronized (mGlobalLock) {
2184 final long origId = Binder.clearCallingIdentity();
2185 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002186 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002187 } finally {
2188 Binder.restoreCallingIdentity(origId);
2189 }
2190 }
2191 }
2192
2193 /**
2194 * TODO: Add mController hook
2195 */
2196 @Override
2197 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002198 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199
2200 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2201 synchronized (mGlobalLock) {
2202 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2203 false /* fromRecents */);
2204 }
2205 }
2206
2207 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2208 boolean fromRecents) {
2209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 Binder.getCallingUid(), -1, -1, "Task to front")) {
2212 SafeActivityOptions.abort(options);
2213 return;
2214 }
2215 final long origId = Binder.clearCallingIdentity();
2216 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002217 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 if (task == null) {
2219 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002220 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 return;
2222 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002223 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002225 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 return;
2227 }
2228 ActivityOptions realOptions = options != null
2229 ? options.getOptions(mStackSupervisor)
2230 : null;
2231 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2232 false /* forceNonResizable */);
2233
2234 final ActivityRecord topActivity = task.getTopActivity();
2235 if (topActivity != null) {
2236
2237 // We are reshowing a task, use a starting window to hide the initial draw delay
2238 // so the transition can start earlier.
2239 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2240 true /* taskSwitch */, fromRecents);
2241 }
2242 } finally {
2243 Binder.restoreCallingIdentity(origId);
2244 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 }
2246
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2248 int callingPid, int callingUid, String name) {
2249 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2250 return true;
2251 }
2252
2253 if (getRecentTasks().isCallerRecents(sourceUid)) {
2254 return true;
2255 }
2256
2257 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2258 if (perm == PackageManager.PERMISSION_GRANTED) {
2259 return true;
2260 }
2261 if (checkAllowAppSwitchUid(sourceUid)) {
2262 return true;
2263 }
2264
2265 // If the actual IPC caller is different from the logical source, then
2266 // also see if they are allowed to control app switches.
2267 if (callingUid != -1 && callingUid != sourceUid) {
2268 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2269 if (perm == PackageManager.PERMISSION_GRANTED) {
2270 return true;
2271 }
2272 if (checkAllowAppSwitchUid(callingUid)) {
2273 return true;
2274 }
2275 }
2276
2277 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2278 return false;
2279 }
2280
2281 private boolean checkAllowAppSwitchUid(int uid) {
2282 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2283 if (types != null) {
2284 for (int i = types.size() - 1; i >= 0; i--) {
2285 if (types.valueAt(i).intValue() == uid) {
2286 return true;
2287 }
2288 }
2289 }
2290 return false;
2291 }
2292
2293 @Override
2294 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2295 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2296 "setActivityController()");
2297 synchronized (mGlobalLock) {
2298 mController = controller;
2299 mControllerIsAMonkey = imAMonkey;
2300 Watchdog.getInstance().setActivityController(controller);
2301 }
2302 }
2303
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002304 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 synchronized (mGlobalLock) {
2306 return mController != null && mControllerIsAMonkey;
2307 }
2308 }
2309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 @Override
2311 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2312 synchronized (mGlobalLock) {
2313 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2314 }
2315 }
2316
2317 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002318 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2319 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2320 }
2321
2322 @Override
2323 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2324 @WindowConfiguration.ActivityType int ignoreActivityType,
2325 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2326 final int callingUid = Binder.getCallingUid();
2327 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2328
2329 synchronized (mGlobalLock) {
2330 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002332 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002334 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 ignoreWindowingMode, callingUid, allowed);
2336 }
2337
2338 return list;
2339 }
2340
2341 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002342 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2343 synchronized (mGlobalLock) {
2344 final long origId = Binder.clearCallingIdentity();
2345 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2346 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002347 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348 }
2349 Binder.restoreCallingIdentity(origId);
2350 }
2351 }
2352
2353 @Override
2354 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002355 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 ActivityStack stack = ActivityRecord.getStackLocked(token);
2357 if (stack != null) {
2358 return stack.willActivityBeVisibleLocked(token);
2359 }
2360 return false;
2361 }
2362 }
2363
2364 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002365 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 synchronized (mGlobalLock) {
2368 final long ident = Binder.clearCallingIdentity();
2369 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002370 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002371 if (task == null) {
2372 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2373 return;
2374 }
2375
2376 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2377 + " to stackId=" + stackId + " toTop=" + toTop);
2378
Wale Ogunwaled32da472018-11-16 07:19:28 -08002379 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002380 if (stack == null) {
2381 throw new IllegalStateException(
2382 "moveTaskToStack: No stack for stackId=" + stackId);
2383 }
2384 if (!stack.isActivityTypeStandardOrUndefined()) {
2385 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2386 + taskId + " to stack " + stackId);
2387 }
2388 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002389 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002390 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2391 }
2392 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2393 "moveTaskToStack");
2394 } finally {
2395 Binder.restoreCallingIdentity(ident);
2396 }
2397 }
2398 }
2399
2400 @Override
2401 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2402 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002403 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002404
2405 final long ident = Binder.clearCallingIdentity();
2406 try {
2407 synchronized (mGlobalLock) {
2408 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002409 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002410 if (stack == null) {
2411 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2412 return;
2413 }
2414 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2415 throw new IllegalArgumentException("Stack: " + stackId
2416 + " doesn't support animated resize.");
2417 }
2418 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2419 animationDuration, false /* fromFullscreen */);
2420 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002421 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 if (stack == null) {
2423 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2424 return;
2425 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002426 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002427 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2428 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2429 }
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(ident);
2433 }
2434 }
2435
2436 /**
2437 * Moves the specified task to the primary-split-screen stack.
2438 *
2439 * @param taskId Id of task to move.
2440 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2441 * exist already. See
2442 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2443 * and
2444 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2445 * @param toTop If the task and stack should be moved to the top.
2446 * @param animate Whether we should play an animation for the moving the task.
2447 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2448 * stack. Pass {@code null} to use default bounds.
2449 * @param showRecents If the recents activity should be shown on the other side of the task
2450 * going into split-screen mode.
2451 */
2452 @Override
2453 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2454 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002456 "setTaskWindowingModeSplitScreenPrimary()");
2457 synchronized (mGlobalLock) {
2458 final long ident = Binder.clearCallingIdentity();
2459 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002460 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002461 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002462 if (task == null) {
2463 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2464 return false;
2465 }
2466 if (DEBUG_STACK) Slog.d(TAG_STACK,
2467 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2468 + " to createMode=" + createMode + " toTop=" + toTop);
2469 if (!task.isActivityTypeStandardOrUndefined()) {
2470 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2471 + " non-standard task " + taskId + " to split-screen windowing mode");
2472 }
2473
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002474 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002475 final int windowingMode = task.getWindowingMode();
2476 final ActivityStack stack = task.getStack();
2477 if (toTop) {
2478 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2479 }
2480 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002481 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2482 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002483 return windowingMode != task.getWindowingMode();
2484 } finally {
2485 Binder.restoreCallingIdentity(ident);
2486 }
2487 }
2488 }
2489
2490 /**
2491 * Removes stacks in the input windowing modes from the system if they are of activity type
2492 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2493 */
2494 @Override
2495 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 "removeStacksInWindowingModes()");
2498
2499 synchronized (mGlobalLock) {
2500 final long ident = Binder.clearCallingIdentity();
2501 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002502 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
2506 }
2507 }
2508
2509 @Override
2510 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002511 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002512 "removeStacksWithActivityTypes()");
2513
2514 synchronized (mGlobalLock) {
2515 final long ident = Binder.clearCallingIdentity();
2516 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002517 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002518 } finally {
2519 Binder.restoreCallingIdentity(ident);
2520 }
2521 }
2522 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523
2524 @Override
2525 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2526 int userId) {
2527 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002528 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2529 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002531 final boolean detailed = checkGetTasksPermission(
2532 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2533 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 == PackageManager.PERMISSION_GRANTED;
2535
2536 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002537 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 callingUid);
2539 }
2540 }
2541
2542 @Override
2543 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002545 long ident = Binder.clearCallingIdentity();
2546 try {
2547 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002549 }
2550 } finally {
2551 Binder.restoreCallingIdentity(ident);
2552 }
2553 }
2554
2555 @Override
2556 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 long ident = Binder.clearCallingIdentity();
2559 try {
2560 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002561 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 }
2563 } finally {
2564 Binder.restoreCallingIdentity(ident);
2565 }
2566 }
2567
2568 @Override
2569 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002571 final long callingUid = Binder.getCallingUid();
2572 final long origId = Binder.clearCallingIdentity();
2573 try {
2574 synchronized (mGlobalLock) {
2575 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002576 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2578 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2579 }
2580 } finally {
2581 Binder.restoreCallingIdentity(origId);
2582 }
2583 }
2584
2585 @Override
2586 public void startLockTaskModeByToken(IBinder token) {
2587 synchronized (mGlobalLock) {
2588 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2589 if (r == null) {
2590 return;
2591 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002592 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 }
2594 }
2595
2596 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002597 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 // This makes inner call to look as if it was initiated by system.
2600 long ident = Binder.clearCallingIdentity();
2601 try {
2602 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002603 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002604 MATCH_TASK_IN_STACKS_ONLY);
2605 if (task == null) {
2606 return;
2607 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608
2609 // When starting lock task mode the stack must be in front and focused
2610 task.getStack().moveToFront("startSystemLockTaskMode");
2611 startLockTaskModeLocked(task, true /* isSystemCaller */);
2612 }
2613 } finally {
2614 Binder.restoreCallingIdentity(ident);
2615 }
2616 }
2617
2618 @Override
2619 public void stopLockTaskModeByToken(IBinder token) {
2620 synchronized (mGlobalLock) {
2621 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2622 if (r == null) {
2623 return;
2624 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002625 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002626 }
2627 }
2628
2629 /**
2630 * This API should be called by SystemUI only when user perform certain action to dismiss
2631 * lock task mode. We should only dismiss pinned lock task mode in this case.
2632 */
2633 @Override
2634 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002635 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002636 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2637 }
2638
2639 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2640 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2641 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2642 return;
2643 }
2644
Wale Ogunwaled32da472018-11-16 07:19:28 -08002645 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 if (stack == null || task != stack.topTask()) {
2647 throw new IllegalArgumentException("Invalid task, not in foreground");
2648 }
2649
2650 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2651 // system or a specific app.
2652 // * System-initiated requests will only start the pinned mode (screen pinning)
2653 // * App-initiated requests
2654 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2655 // - will start the pinned mode, otherwise
2656 final int callingUid = Binder.getCallingUid();
2657 long ident = Binder.clearCallingIdentity();
2658 try {
2659 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002660 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002662 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 } finally {
2664 Binder.restoreCallingIdentity(ident);
2665 }
2666 }
2667
2668 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2669 final int callingUid = Binder.getCallingUid();
2670 long ident = Binder.clearCallingIdentity();
2671 try {
2672 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002673 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 }
2675 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2676 // task and jumping straight into a call in the case of emergency call back.
2677 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2678 if (tm != null) {
2679 tm.showInCallScreen(false);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
2685
2686 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002687 public void updateLockTaskPackages(int userId, String[] packages) {
2688 final int callingUid = Binder.getCallingUid();
2689 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2690 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2691 "updateLockTaskPackages()");
2692 }
2693 synchronized (this) {
2694 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2695 + Arrays.toString(packages));
2696 getLockTaskController().updateLockTaskPackages(userId, packages);
2697 }
2698 }
2699
2700 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 public boolean isInLockTaskMode() {
2702 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2703 }
2704
2705 @Override
2706 public int getLockTaskModeState() {
2707 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002708 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 }
2710 }
2711
2712 @Override
2713 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2714 synchronized (mGlobalLock) {
2715 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2716 if (r != null) {
2717 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002718 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002719 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002720 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 }
2722 }
2723 }
2724
2725 @Override
2726 public Bundle getActivityOptions(IBinder token) {
2727 final long origId = Binder.clearCallingIdentity();
2728 try {
2729 synchronized (mGlobalLock) {
2730 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2731 if (r != null) {
2732 final ActivityOptions activityOptions = r.takeOptionsLocked();
2733 return activityOptions == null ? null : activityOptions.toBundle();
2734 }
2735 return null;
2736 }
2737 } finally {
2738 Binder.restoreCallingIdentity(origId);
2739 }
2740 }
2741
2742 @Override
2743 public List<IBinder> getAppTasks(String callingPackage) {
2744 int callingUid = Binder.getCallingUid();
2745 long ident = Binder.clearCallingIdentity();
2746 try {
2747 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002748 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002749 }
2750 } finally {
2751 Binder.restoreCallingIdentity(ident);
2752 }
2753 }
2754
2755 @Override
2756 public void finishVoiceTask(IVoiceInteractionSession session) {
2757 synchronized (mGlobalLock) {
2758 final long origId = Binder.clearCallingIdentity();
2759 try {
2760 // TODO: VI Consider treating local voice interactions and voice tasks
2761 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002762 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 } finally {
2764 Binder.restoreCallingIdentity(origId);
2765 }
2766 }
2767
2768 }
2769
2770 @Override
2771 public boolean isTopOfTask(IBinder token) {
2772 synchronized (mGlobalLock) {
2773 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002774 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 }
2776 }
2777
2778 @Override
2779 public void notifyLaunchTaskBehindComplete(IBinder token) {
2780 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2781 }
2782
2783 @Override
2784 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002785 mH.post(() -> {
2786 synchronized (mGlobalLock) {
2787 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002788 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002789 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002790 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002791 } catch (RemoteException e) {
2792 }
2793 }
2794 }
2795
2796 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798
2799 /** Called from an app when assist data is ready. */
2800 @Override
2801 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2802 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 synchronized (pae) {
2805 pae.result = extras;
2806 pae.structure = structure;
2807 pae.content = content;
2808 if (referrer != null) {
2809 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2810 }
2811 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002812 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002813 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2814 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 structure.setHomeActivity(pae.isHome);
2816 }
2817 pae.haveResult = true;
2818 pae.notifyAll();
2819 if (pae.intent == null && pae.receiver == null) {
2820 // Caller is just waiting for the result.
2821 return;
2822 }
2823 }
2824 // We are now ready to launch the assist activity.
2825 IAssistDataReceiver sendReceiver = null;
2826 Bundle sendBundle = null;
2827 synchronized (mGlobalLock) {
2828 buildAssistBundleLocked(pae, extras);
2829 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002830 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002831 if (!exists) {
2832 // Timed out.
2833 return;
2834 }
2835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002836 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 // Caller wants result sent back to them.
2838 sendBundle = new Bundle();
2839 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2840 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2841 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2842 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2843 }
2844 }
2845 if (sendReceiver != null) {
2846 try {
2847 sendReceiver.onHandleAssistData(sendBundle);
2848 } catch (RemoteException e) {
2849 }
2850 return;
2851 }
2852
2853 final long ident = Binder.clearCallingIdentity();
2854 try {
2855 if (TextUtils.equals(pae.intent.getAction(),
2856 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2857 pae.intent.putExtras(pae.extras);
2858 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2859 } else {
2860 pae.intent.replaceExtras(pae.extras);
2861 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2862 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2863 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002864 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865
2866 try {
2867 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2868 } catch (ActivityNotFoundException e) {
2869 Slog.w(TAG, "No activity to handle assist action.", e);
2870 }
2871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(ident);
2874 }
2875 }
2876
2877 @Override
2878 public int addAppTask(IBinder activityToken, Intent intent,
2879 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2880 final int callingUid = Binder.getCallingUid();
2881 final long callingIdent = Binder.clearCallingIdentity();
2882
2883 try {
2884 synchronized (mGlobalLock) {
2885 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2886 if (r == null) {
2887 throw new IllegalArgumentException("Activity does not exist; token="
2888 + activityToken);
2889 }
2890 ComponentName comp = intent.getComponent();
2891 if (comp == null) {
2892 throw new IllegalArgumentException("Intent " + intent
2893 + " must specify explicit component");
2894 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002895 if (thumbnail.getWidth() != mThumbnailWidth
2896 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 throw new IllegalArgumentException("Bad thumbnail size: got "
2898 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002899 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 }
2901 if (intent.getSelector() != null) {
2902 intent.setSelector(null);
2903 }
2904 if (intent.getSourceBounds() != null) {
2905 intent.setSourceBounds(null);
2906 }
2907 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2908 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2909 // The caller has added this as an auto-remove task... that makes no
2910 // sense, so turn off auto-remove.
2911 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2912 }
2913 }
2914 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2915 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2916 if (ainfo.applicationInfo.uid != callingUid) {
2917 throw new SecurityException(
2918 "Can't add task for another application: target uid="
2919 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2920 }
2921
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002922 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002926 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 // The app has too many tasks already and we can't add any more
2928 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2929 return INVALID_TASK_ID;
2930 }
2931 task.lastTaskDescription.copyFrom(description);
2932
2933 // TODO: Send the thumbnail to WM to store it.
2934
2935 return task.taskId;
2936 }
2937 } finally {
2938 Binder.restoreCallingIdentity(callingIdent);
2939 }
2940 }
2941
2942 @Override
2943 public Point getAppTaskThumbnailSize() {
2944 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002945 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 }
2948
2949 @Override
2950 public void setTaskResizeable(int taskId, int resizeableMode) {
2951 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002952 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2954 if (task == null) {
2955 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2956 return;
2957 }
2958 task.setResizeMode(resizeableMode);
2959 }
2960 }
2961
2962 @Override
2963 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002964 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 long ident = Binder.clearCallingIdentity();
2966 try {
2967 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002968 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002969 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 if (task == null) {
2971 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2972 return;
2973 }
2974 // Place the task in the right stack if it isn't there already based on
2975 // the requested bounds.
2976 // The stack transition logic is:
2977 // - a null bounds on a freeform task moves that task to fullscreen
2978 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2979 // that task to freeform
2980 // - otherwise the task is not moved
2981 ActivityStack stack = task.getStack();
2982 if (!task.getWindowConfiguration().canResizeTask()) {
2983 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2984 }
2985 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2986 stack = stack.getDisplay().getOrCreateStack(
2987 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2988 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2989 stack = stack.getDisplay().getOrCreateStack(
2990 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2991 }
2992
2993 // Reparent the task to the right stack if necessary
2994 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2995 if (stack != task.getStack()) {
2996 // Defer resume until the task is resized below
2997 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2998 DEFER_RESUME, "resizeTask");
2999 preserveWindow = false;
3000 }
3001
3002 // After reparenting (which only resizes the task to the stack bounds), resize the
3003 // task to the actual bounds provided
3004 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3005 }
3006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
3009 }
3010
3011 @Override
3012 public boolean releaseActivityInstance(IBinder token) {
3013 synchronized (mGlobalLock) {
3014 final long origId = Binder.clearCallingIdentity();
3015 try {
3016 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3017 if (r == null) {
3018 return false;
3019 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003020 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 } finally {
3022 Binder.restoreCallingIdentity(origId);
3023 }
3024 }
3025 }
3026
3027 @Override
3028 public void releaseSomeActivities(IApplicationThread appInt) {
3029 synchronized (mGlobalLock) {
3030 final long origId = Binder.clearCallingIdentity();
3031 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003032 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003033 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 } finally {
3035 Binder.restoreCallingIdentity(origId);
3036 }
3037 }
3038 }
3039
3040 @Override
3041 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003042 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003043 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 != PackageManager.PERMISSION_GRANTED) {
3045 throw new SecurityException("Requires permission "
3046 + android.Manifest.permission.DEVICE_POWER);
3047 }
3048
3049 synchronized (mGlobalLock) {
3050 long ident = Binder.clearCallingIdentity();
3051 if (mKeyguardShown != keyguardShowing) {
3052 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003053 final Message msg = PooledLambda.obtainMessage(
3054 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3055 keyguardShowing);
3056 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003057 }
3058 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003059 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003060 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 } finally {
3062 Binder.restoreCallingIdentity(ident);
3063 }
3064 }
3065
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003066 mH.post(() -> {
3067 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3068 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3069 }
3070 });
3071 }
3072
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003073 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 mH.post(() -> {
3075 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3076 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3077 }
3078 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 }
3080
3081 @Override
3082 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003083 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3084 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085
3086 final File passedIconFile = new File(filePath);
3087 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3088 passedIconFile.getName());
3089 if (!legitIconFile.getPath().equals(filePath)
3090 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3091 throw new IllegalArgumentException("Bad file path: " + filePath
3092 + " passed for userId " + userId);
3093 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003094 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 }
3096
3097 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3100 final ActivityOptions activityOptions = safeOptions != null
3101 ? safeOptions.getOptions(mStackSupervisor)
3102 : null;
3103 if (activityOptions == null
3104 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3105 || activityOptions.getCustomInPlaceResId() == 0) {
3106 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3107 "with valid animation");
3108 }
lumark588a3e82018-07-20 18:53:54 +08003109 // Get top display of front most application.
3110 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3111 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003112 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3113 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3114 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003115 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003116 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003117 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 }
3119
3120 @Override
3121 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 synchronized (mGlobalLock) {
3124 final long ident = Binder.clearCallingIdentity();
3125 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003126 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 if (stack == null) {
3128 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3129 return;
3130 }
3131 if (!stack.isActivityTypeStandardOrUndefined()) {
3132 throw new IllegalArgumentException(
3133 "Removing non-standard stack is not allowed.");
3134 }
3135 mStackSupervisor.removeStack(stack);
3136 } finally {
3137 Binder.restoreCallingIdentity(ident);
3138 }
3139 }
3140 }
3141
3142 @Override
3143 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003144 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145
3146 synchronized (mGlobalLock) {
3147 final long ident = Binder.clearCallingIdentity();
3148 try {
3149 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3150 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003151 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 } finally {
3153 Binder.restoreCallingIdentity(ident);
3154 }
3155 }
3156 }
3157
3158 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 public void exitFreeformMode(IBinder token) {
3160 synchronized (mGlobalLock) {
3161 long ident = Binder.clearCallingIdentity();
3162 try {
3163 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3164 if (r == null) {
3165 throw new IllegalArgumentException(
3166 "exitFreeformMode: No activity record matching token=" + token);
3167 }
3168
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 if (stack == null || !stack.inFreeformWindowingMode()) {
3171 throw new IllegalStateException(
3172 "exitFreeformMode: You can only go fullscreen from freeform.");
3173 }
3174
3175 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3176 } finally {
3177 Binder.restoreCallingIdentity(ident);
3178 }
3179 }
3180 }
3181
3182 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3183 @Override
3184 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003185 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003187 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 }
3189
3190 /** Unregister a task stack listener so that it stops receiving callbacks. */
3191 @Override
3192 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003193 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003195 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 @Override
3199 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3200 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3201 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3202 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3203 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3204 }
3205
3206 @Override
3207 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3208 IBinder activityToken, int flags) {
3209 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3210 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3211 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3212 }
3213
3214 @Override
3215 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3216 Bundle args) {
3217 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3218 true /* focused */, true /* newSessionId */, userHandle, args,
3219 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3220 }
3221
3222 @Override
3223 public Bundle getAssistContextExtras(int requestType) {
3224 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3225 null, null, true /* focused */, true /* newSessionId */,
3226 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3227 if (pae == null) {
3228 return null;
3229 }
3230 synchronized (pae) {
3231 while (!pae.haveResult) {
3232 try {
3233 pae.wait();
3234 } catch (InterruptedException e) {
3235 }
3236 }
3237 }
3238 synchronized (mGlobalLock) {
3239 buildAssistBundleLocked(pae, pae.result);
3240 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 }
3243 return pae.extras;
3244 }
3245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003246 /**
3247 * Binder IPC calls go through the public entry point.
3248 * This can be called with or without the global lock held.
3249 */
3250 private static int checkCallingPermission(String permission) {
3251 return checkPermission(
3252 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3253 }
3254
3255 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003256 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003257 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3258 mAmInternal.enforceCallingPermission(permission, func);
3259 }
3260 }
3261
3262 @VisibleForTesting
3263 int checkGetTasksPermission(String permission, int pid, int uid) {
3264 return checkPermission(permission, pid, uid);
3265 }
3266
3267 static int checkPermission(String permission, int pid, int uid) {
3268 if (permission == null) {
3269 return PackageManager.PERMISSION_DENIED;
3270 }
3271 return checkComponentPermission(permission, pid, uid, -1, true);
3272 }
3273
Wale Ogunwale214f3482018-10-04 11:00:47 -07003274 public static int checkComponentPermission(String permission, int pid, int uid,
3275 int owningUid, boolean exported) {
3276 return ActivityManagerService.checkComponentPermission(
3277 permission, pid, uid, owningUid, exported);
3278 }
3279
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3281 if (getRecentTasks().isCallerRecents(callingUid)) {
3282 // Always allow the recents component to get tasks
3283 return true;
3284 }
3285
3286 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3287 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3288 if (!allowed) {
3289 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3290 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3291 // Temporary compatibility: some existing apps on the system image may
3292 // still be requesting the old permission and not switched to the new
3293 // one; if so, we'll still allow them full access. This means we need
3294 // to see if they are holding the old permission and are a system app.
3295 try {
3296 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3297 allowed = true;
3298 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3299 + " is using old GET_TASKS but privileged; allowing");
3300 }
3301 } catch (RemoteException e) {
3302 }
3303 }
3304 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3305 + " does not hold REAL_GET_TASKS; limiting output");
3306 }
3307 return allowed;
3308 }
3309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3311 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3312 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3313 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 "enqueueAssistContext()");
3316
3317 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003318 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 if (activity == null) {
3320 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3321 return null;
3322 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003323 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3325 return null;
3326 }
3327 if (focused) {
3328 if (activityToken != null) {
3329 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3330 if (activity != caller) {
3331 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3332 + " is not current top " + activity);
3333 return null;
3334 }
3335 }
3336 } else {
3337 activity = ActivityRecord.forTokenLocked(activityToken);
3338 if (activity == null) {
3339 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3340 + " couldn't be found");
3341 return null;
3342 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003343 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3345 return null;
3346 }
3347 }
3348
3349 PendingAssistExtras pae;
3350 Bundle extras = new Bundle();
3351 if (args != null) {
3352 extras.putAll(args);
3353 }
3354 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003355 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356
3357 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3358 userHandle);
3359 pae.isHome = activity.isActivityTypeHome();
3360
3361 // Increment the sessionId if necessary
3362 if (newSessionId) {
3363 mViSessionId++;
3364 }
3365 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003366 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3367 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 } catch (RemoteException e) {
3371 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3372 return null;
3373 }
3374 return pae;
3375 }
3376 }
3377
3378 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3379 if (result != null) {
3380 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3381 }
3382 if (pae.hint != null) {
3383 pae.extras.putBoolean(pae.hint, true);
3384 }
3385 }
3386
3387 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3388 IAssistDataReceiver receiver;
3389 synchronized (mGlobalLock) {
3390 mPendingAssistExtras.remove(pae);
3391 receiver = pae.receiver;
3392 }
3393 if (receiver != null) {
3394 // Caller wants result sent back to them.
3395 Bundle sendBundle = new Bundle();
3396 // At least return the receiver extras
3397 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3398 try {
3399 pae.receiver.onHandleAssistData(sendBundle);
3400 } catch (RemoteException e) {
3401 }
3402 }
3403 }
3404
3405 public class PendingAssistExtras extends Binder implements Runnable {
3406 public final ActivityRecord activity;
3407 public boolean isHome;
3408 public final Bundle extras;
3409 public final Intent intent;
3410 public final String hint;
3411 public final IAssistDataReceiver receiver;
3412 public final int userHandle;
3413 public boolean haveResult = false;
3414 public Bundle result = null;
3415 public AssistStructure structure = null;
3416 public AssistContent content = null;
3417 public Bundle receiverExtras;
3418
3419 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3420 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3421 int _userHandle) {
3422 activity = _activity;
3423 extras = _extras;
3424 intent = _intent;
3425 hint = _hint;
3426 receiver = _receiver;
3427 receiverExtras = _receiverExtras;
3428 userHandle = _userHandle;
3429 }
3430
3431 @Override
3432 public void run() {
3433 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3434 synchronized (this) {
3435 haveResult = true;
3436 notifyAll();
3437 }
3438 pendingAssistExtrasTimedOut(this);
3439 }
3440 }
3441
3442 @Override
3443 public boolean isAssistDataAllowedOnCurrentActivity() {
3444 int userId;
3445 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003446 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3448 return false;
3449 }
3450
3451 final ActivityRecord activity = focusedStack.getTopActivity();
3452 if (activity == null) {
3453 return false;
3454 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003455 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 }
3457 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3458 }
3459
3460 @Override
3461 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3462 long ident = Binder.clearCallingIdentity();
3463 try {
3464 synchronized (mGlobalLock) {
3465 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003466 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 if (top != caller) {
3468 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3469 + " is not current top " + top);
3470 return false;
3471 }
3472 if (!top.nowVisible) {
3473 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3474 + " is not visible");
3475 return false;
3476 }
3477 }
3478 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3479 token);
3480 } finally {
3481 Binder.restoreCallingIdentity(ident);
3482 }
3483 }
3484
3485 @Override
3486 public boolean isRootVoiceInteraction(IBinder token) {
3487 synchronized (mGlobalLock) {
3488 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3489 if (r == null) {
3490 return false;
3491 }
3492 return r.rootVoiceInteraction;
3493 }
3494 }
3495
Wale Ogunwalef6733932018-06-27 05:14:34 -07003496 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3497 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3498 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3499 if (activityToCallback == null) return;
3500 activityToCallback.setVoiceSessionLocked(voiceSession);
3501
3502 // Inform the activity
3503 try {
3504 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3505 voiceInteractor);
3506 long token = Binder.clearCallingIdentity();
3507 try {
3508 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3509 } finally {
3510 Binder.restoreCallingIdentity(token);
3511 }
3512 // TODO: VI Should we cache the activity so that it's easier to find later
3513 // rather than scan through all the stacks and activities?
3514 } catch (RemoteException re) {
3515 activityToCallback.clearVoiceSessionLocked();
3516 // TODO: VI Should this terminate the voice session?
3517 }
3518 }
3519
3520 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3521 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3522 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3523 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3524 boolean wasRunningVoice = mRunningVoice != null;
3525 mRunningVoice = session;
3526 if (!wasRunningVoice) {
3527 mVoiceWakeLock.acquire();
3528 updateSleepIfNeededLocked();
3529 }
3530 }
3531 }
3532
3533 void finishRunningVoiceLocked() {
3534 if (mRunningVoice != null) {
3535 mRunningVoice = null;
3536 mVoiceWakeLock.release();
3537 updateSleepIfNeededLocked();
3538 }
3539 }
3540
3541 @Override
3542 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3543 synchronized (mGlobalLock) {
3544 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3545 if (keepAwake) {
3546 mVoiceWakeLock.acquire();
3547 } else {
3548 mVoiceWakeLock.release();
3549 }
3550 }
3551 }
3552 }
3553
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 @Override
3555 public ComponentName getActivityClassForToken(IBinder token) {
3556 synchronized (mGlobalLock) {
3557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3558 if (r == null) {
3559 return null;
3560 }
3561 return r.intent.getComponent();
3562 }
3563 }
3564
3565 @Override
3566 public String getPackageForToken(IBinder token) {
3567 synchronized (mGlobalLock) {
3568 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3569 if (r == null) {
3570 return null;
3571 }
3572 return r.packageName;
3573 }
3574 }
3575
3576 @Override
3577 public void showLockTaskEscapeMessage(IBinder token) {
3578 synchronized (mGlobalLock) {
3579 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3580 if (r == null) {
3581 return;
3582 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003583 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003584 }
3585 }
3586
3587 @Override
3588 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 final long token = Binder.clearCallingIdentity();
3591 try {
3592 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003593 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 }
3595 } finally {
3596 Binder.restoreCallingIdentity(token);
3597 }
3598 }
3599
3600 /**
3601 * Try to place task to provided position. The final position might be different depending on
3602 * current user and stacks state. The task will be moved to target stack if it's currently in
3603 * different stack.
3604 */
3605 @Override
3606 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003607 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 synchronized (mGlobalLock) {
3609 long ident = Binder.clearCallingIdentity();
3610 try {
3611 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3612 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003613 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 if (task == null) {
3615 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3616 + taskId);
3617 }
3618
Wale Ogunwaled32da472018-11-16 07:19:28 -08003619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620
3621 if (stack == null) {
3622 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3623 + stackId);
3624 }
3625 if (!stack.isActivityTypeStandardOrUndefined()) {
3626 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3627 + " the position of task " + taskId + " in/to non-standard stack");
3628 }
3629
3630 // TODO: Have the callers of this API call a separate reparent method if that is
3631 // what they intended to do vs. having this method also do reparenting.
3632 if (task.getStack() == stack) {
3633 // Change position in current stack.
3634 stack.positionChildAt(task, position);
3635 } else {
3636 // Reparent to new stack.
3637 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3638 !DEFER_RESUME, "positionTaskInStack");
3639 }
3640 } finally {
3641 Binder.restoreCallingIdentity(ident);
3642 }
3643 }
3644 }
3645
3646 @Override
3647 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3648 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3649 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3650 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3651 synchronized (mGlobalLock) {
3652 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3653 if (record == null) {
3654 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3655 + "found for: " + token);
3656 }
3657 record.setSizeConfigurations(horizontalSizeConfiguration,
3658 verticalSizeConfigurations, smallestSizeConfigurations);
3659 }
3660 }
3661
3662 /**
3663 * Dismisses split-screen multi-window mode.
3664 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3665 */
3666 @Override
3667 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003668 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3670 final long ident = Binder.clearCallingIdentity();
3671 try {
3672 synchronized (mGlobalLock) {
3673 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003674 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675 if (stack == null) {
3676 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3677 return;
3678 }
3679
3680 if (toTop) {
3681 // Caller wants the current split-screen primary stack to be the top stack after
3682 // it goes fullscreen, so move it to the front.
3683 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003684 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 // In this case the current split-screen primary stack shouldn't be the top
3686 // stack after it goes fullscreen, but it current has focus, so we move the
3687 // focus to the top-most split-screen secondary stack next to it.
3688 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3689 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3690 if (otherStack != null) {
3691 otherStack.moveToFront("dismissSplitScreenMode_other");
3692 }
3693 }
3694
Evan Rosky10475742018-09-05 19:02:48 -07003695 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 }
3697 } finally {
3698 Binder.restoreCallingIdentity(ident);
3699 }
3700 }
3701
3702 /**
3703 * Dismisses Pip
3704 * @param animate True if the dismissal should be animated.
3705 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3706 * default animation duration should be used.
3707 */
3708 @Override
3709 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 final long ident = Binder.clearCallingIdentity();
3712 try {
3713 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003714 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003715 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 if (stack == null) {
3717 Slog.w(TAG, "dismissPip: pinned stack not found.");
3718 return;
3719 }
3720 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3721 throw new IllegalArgumentException("Stack: " + stack
3722 + " doesn't support animated resize.");
3723 }
3724 if (animate) {
3725 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3726 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3727 } else {
3728 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3729 }
3730 }
3731 } finally {
3732 Binder.restoreCallingIdentity(ident);
3733 }
3734 }
3735
3736 @Override
3737 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003738 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 synchronized (mGlobalLock) {
3740 mSuppressResizeConfigChanges = suppress;
3741 }
3742 }
3743
3744 /**
3745 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3746 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3747 * activity and clearing the task at the same time.
3748 */
3749 @Override
3750 // TODO: API should just be about changing windowing modes...
3751 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003752 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 "moveTasksToFullscreenStack()");
3754 synchronized (mGlobalLock) {
3755 final long origId = Binder.clearCallingIdentity();
3756 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003757 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003758 if (stack != null){
3759 if (!stack.isActivityTypeStandardOrUndefined()) {
3760 throw new IllegalArgumentException(
3761 "You can't move tasks from non-standard stacks.");
3762 }
3763 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3764 }
3765 } finally {
3766 Binder.restoreCallingIdentity(origId);
3767 }
3768 }
3769 }
3770
3771 /**
3772 * Moves the top activity in the input stackId to the pinned stack.
3773 *
3774 * @param stackId Id of stack to move the top activity to pinned stack.
3775 * @param bounds Bounds to use for pinned stack.
3776 *
3777 * @return True if the top activity of the input stack was successfully moved to the pinned
3778 * stack.
3779 */
3780 @Override
3781 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003782 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 "moveTopActivityToPinnedStack()");
3784 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003785 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3787 + "Device doesn't support picture-in-picture mode");
3788 }
3789
3790 long ident = Binder.clearCallingIdentity();
3791 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003792 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 } finally {
3794 Binder.restoreCallingIdentity(ident);
3795 }
3796 }
3797 }
3798
3799 @Override
3800 public boolean isInMultiWindowMode(IBinder token) {
3801 final long origId = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mGlobalLock) {
3804 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return false;
3807 }
3808 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3809 return r.inMultiWindowMode();
3810 }
3811 } finally {
3812 Binder.restoreCallingIdentity(origId);
3813 }
3814 }
3815
3816 @Override
3817 public boolean isInPictureInPictureMode(IBinder token) {
3818 final long origId = Binder.clearCallingIdentity();
3819 try {
3820 synchronized (mGlobalLock) {
3821 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3822 }
3823 } finally {
3824 Binder.restoreCallingIdentity(origId);
3825 }
3826 }
3827
3828 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003829 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3830 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 return false;
3832 }
3833
3834 // If we are animating to fullscreen then we have already dispatched the PIP mode
3835 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003836 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3837 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 }
3839
3840 @Override
3841 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3842 final long origId = Binder.clearCallingIdentity();
3843 try {
3844 synchronized (mGlobalLock) {
3845 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3846 "enterPictureInPictureMode", token, params);
3847
3848 // If the activity is already in picture in picture mode, then just return early
3849 if (isInPictureInPictureMode(r)) {
3850 return true;
3851 }
3852
3853 // Activity supports picture-in-picture, now check that we can enter PiP at this
3854 // point, if it is
3855 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3856 false /* beforeStopping */)) {
3857 return false;
3858 }
3859
3860 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003861 synchronized (mGlobalLock) {
3862 // Only update the saved args from the args that are set
3863 r.pictureInPictureArgs.copyOnlySet(params);
3864 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3865 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3866 // Adjust the source bounds by the insets for the transition down
3867 final Rect sourceBounds = new Rect(
3868 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003869 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003870 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003871 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003872 stack.setPictureInPictureAspectRatio(aspectRatio);
3873 stack.setPictureInPictureActions(actions);
3874 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3875 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3876 logPictureInPictureArgs(params);
3877 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 };
3879
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003880 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003881 // If the keyguard is showing or occluded, then try and dismiss it before
3882 // entering picture-in-picture (this will prompt the user to authenticate if the
3883 // device is currently locked).
3884 dismissKeyguard(token, new KeyguardDismissCallback() {
3885 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003886 public void onDismissSucceeded() {
3887 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 }
3889 }, null /* message */);
3890 } else {
3891 // Enter picture in picture immediately otherwise
3892 enterPipRunnable.run();
3893 }
3894 return true;
3895 }
3896 } finally {
3897 Binder.restoreCallingIdentity(origId);
3898 }
3899 }
3900
3901 @Override
3902 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3903 final long origId = Binder.clearCallingIdentity();
3904 try {
3905 synchronized (mGlobalLock) {
3906 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3907 "setPictureInPictureParams", token, params);
3908
3909 // Only update the saved args from the args that are set
3910 r.pictureInPictureArgs.copyOnlySet(params);
3911 if (r.inPinnedWindowingMode()) {
3912 // If the activity is already in picture-in-picture, update the pinned stack now
3913 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3914 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003915 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 if (!stack.isAnimatingBoundsToFullscreen()) {
3917 stack.setPictureInPictureAspectRatio(
3918 r.pictureInPictureArgs.getAspectRatio());
3919 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3920 }
3921 }
3922 logPictureInPictureArgs(params);
3923 }
3924 } finally {
3925 Binder.restoreCallingIdentity(origId);
3926 }
3927 }
3928
3929 @Override
3930 public int getMaxNumPictureInPictureActions(IBinder token) {
3931 // Currently, this is a static constant, but later, we may change this to be dependent on
3932 // the context of the activity
3933 return 3;
3934 }
3935
3936 private void logPictureInPictureArgs(PictureInPictureParams params) {
3937 if (params.hasSetActions()) {
3938 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3939 params.getActions().size());
3940 }
3941 if (params.hasSetAspectRatio()) {
3942 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3943 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3944 MetricsLogger.action(lm);
3945 }
3946 }
3947
3948 /**
3949 * Checks the state of the system and the activity associated with the given {@param token} to
3950 * verify that picture-in-picture is supported for that activity.
3951 *
3952 * @return the activity record for the given {@param token} if all the checks pass.
3953 */
3954 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3955 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003956 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003957 throw new IllegalStateException(caller
3958 + ": Device doesn't support picture-in-picture mode.");
3959 }
3960
3961 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3962 if (r == null) {
3963 throw new IllegalStateException(caller
3964 + ": Can't find activity for token=" + token);
3965 }
3966
3967 if (!r.supportsPictureInPicture()) {
3968 throw new IllegalStateException(caller
3969 + ": Current activity does not support picture-in-picture.");
3970 }
3971
3972 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003973 && !mWindowManager.isValidPictureInPictureAspectRatio(
3974 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 final float minAspectRatio = mContext.getResources().getFloat(
3976 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3977 final float maxAspectRatio = mContext.getResources().getFloat(
3978 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3979 throw new IllegalArgumentException(String.format(caller
3980 + ": Aspect ratio is too extreme (must be between %f and %f).",
3981 minAspectRatio, maxAspectRatio));
3982 }
3983
3984 // Truncate the number of actions if necessary
3985 params.truncateActions(getMaxNumPictureInPictureActions(token));
3986
3987 return r;
3988 }
3989
3990 @Override
3991 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 synchronized (mGlobalLock) {
3994 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3995 if (r == null) {
3996 throw new IllegalArgumentException("Activity does not exist; token="
3997 + activityToken);
3998 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003999 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 }
4001 }
4002
4003 @Override
4004 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4005 Rect tempDockedTaskInsetBounds,
4006 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 long ident = Binder.clearCallingIdentity();
4009 try {
4010 synchronized (mGlobalLock) {
4011 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4012 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4013 PRESERVE_WINDOWS);
4014 }
4015 } finally {
4016 Binder.restoreCallingIdentity(ident);
4017 }
4018 }
4019
4020 @Override
4021 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 final long ident = Binder.clearCallingIdentity();
4024 try {
4025 synchronized (mGlobalLock) {
4026 mStackSupervisor.setSplitScreenResizing(resizing);
4027 }
4028 } finally {
4029 Binder.restoreCallingIdentity(ident);
4030 }
4031 }
4032
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 /**
4034 * Check that we have the features required for VR-related API calls, and throw an exception if
4035 * not.
4036 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004037 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004038 if (!mContext.getPackageManager().hasSystemFeature(
4039 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4040 throw new UnsupportedOperationException("VR mode not supported on this device!");
4041 }
4042 }
4043
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 @Override
4045 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047
4048 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4049
4050 ActivityRecord r;
4051 synchronized (mGlobalLock) {
4052 r = ActivityRecord.isInStackLocked(token);
4053 }
4054
4055 if (r == null) {
4056 throw new IllegalArgumentException();
4057 }
4058
4059 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004060 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 VrManagerInternal.NO_ERROR) {
4062 return err;
4063 }
4064
4065 // Clear the binder calling uid since this path may call moveToTask().
4066 final long callingId = Binder.clearCallingIdentity();
4067 try {
4068 synchronized (mGlobalLock) {
4069 r.requestedVrComponent = (enabled) ? packageName : null;
4070
4071 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004072 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004073 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 }
4075 return 0;
4076 }
4077 } finally {
4078 Binder.restoreCallingIdentity(callingId);
4079 }
4080 }
4081
4082 @Override
4083 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4084 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4085 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004086 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4088 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4089 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004090 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 || activity.voiceSession != null) {
4092 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4093 return;
4094 }
4095 if (activity.pendingVoiceInteractionStart) {
4096 Slog.w(TAG, "Pending start of voice interaction already.");
4097 return;
4098 }
4099 activity.pendingVoiceInteractionStart = true;
4100 }
4101 LocalServices.getService(VoiceInteractionManagerInternal.class)
4102 .startLocalVoiceInteraction(callingActivity, options);
4103 }
4104
4105 @Override
4106 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4107 LocalServices.getService(VoiceInteractionManagerInternal.class)
4108 .stopLocalVoiceInteraction(callingActivity);
4109 }
4110
4111 @Override
4112 public boolean supportsLocalVoiceInteraction() {
4113 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4114 .supportsLocalVoiceInteraction();
4115 }
4116
4117 /** Notifies all listeners when the pinned stack animation starts. */
4118 @Override
4119 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004120 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 }
4122
4123 /** Notifies all listeners when the pinned stack animation ends. */
4124 @Override
4125 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004126 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 }
4128
4129 @Override
4130 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004131 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 final long ident = Binder.clearCallingIdentity();
4133 try {
4134 synchronized (mGlobalLock) {
4135 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4136 }
4137 } finally {
4138 Binder.restoreCallingIdentity(ident);
4139 }
4140 }
4141
4142 @Override
4143 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004144 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145
4146 synchronized (mGlobalLock) {
4147 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004148 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 // Call might come when display is not yet added or has already been removed.
4150 if (DEBUG_CONFIGURATION) {
4151 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4152 + displayId);
4153 }
4154 return false;
4155 }
4156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004157 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004159 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 }
4161
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004162 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004163 final Message msg = PooledLambda.obtainMessage(
4164 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4165 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 }
4167
4168 final long origId = Binder.clearCallingIdentity();
4169 try {
4170 if (values != null) {
4171 Settings.System.clearConfiguration(values);
4172 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004173 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4175 return mTmpUpdateConfigurationResult.changes != 0;
4176 } finally {
4177 Binder.restoreCallingIdentity(origId);
4178 }
4179 }
4180 }
4181
4182 @Override
4183 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004184 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185
4186 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004187 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004189 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004190 }
4191
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004193 final Message msg = PooledLambda.obtainMessage(
4194 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4195 DEFAULT_DISPLAY);
4196 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 }
4198
4199 final long origId = Binder.clearCallingIdentity();
4200 try {
4201 if (values != null) {
4202 Settings.System.clearConfiguration(values);
4203 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 UserHandle.USER_NULL, false /* deferResume */,
4206 mTmpUpdateConfigurationResult);
4207 return mTmpUpdateConfigurationResult.changes != 0;
4208 } finally {
4209 Binder.restoreCallingIdentity(origId);
4210 }
4211 }
4212 }
4213
4214 @Override
4215 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4216 CharSequence message) {
4217 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004218 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4220 }
4221 final long callingId = Binder.clearCallingIdentity();
4222 try {
4223 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004224 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 }
4226 } finally {
4227 Binder.restoreCallingIdentity(callingId);
4228 }
4229 }
4230
4231 @Override
4232 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 "cancelTaskWindowTransition()");
4235 final long ident = Binder.clearCallingIdentity();
4236 try {
4237 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004238 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 MATCH_TASK_IN_STACKS_ONLY);
4240 if (task == null) {
4241 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4242 return;
4243 }
4244 task.cancelWindowTransition();
4245 }
4246 } finally {
4247 Binder.restoreCallingIdentity(ident);
4248 }
4249 }
4250
4251 @Override
4252 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 final long ident = Binder.clearCallingIdentity();
4255 try {
4256 final TaskRecord task;
4257 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004258 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4260 if (task == null) {
4261 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4262 return null;
4263 }
4264 }
4265 // Don't call this while holding the lock as this operation might hit the disk.
4266 return task.getSnapshot(reducedResolution);
4267 } finally {
4268 Binder.restoreCallingIdentity(ident);
4269 }
4270 }
4271
4272 @Override
4273 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4274 synchronized (mGlobalLock) {
4275 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4276 if (r == null) {
4277 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4278 + token);
4279 return;
4280 }
4281 final long origId = Binder.clearCallingIdentity();
4282 try {
4283 r.setDisablePreviewScreenshots(disable);
4284 } finally {
4285 Binder.restoreCallingIdentity(origId);
4286 }
4287 }
4288 }
4289
4290 /** Return the user id of the last resumed activity. */
4291 @Override
4292 public @UserIdInt
4293 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004294 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004295 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4296 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004297 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004298 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004300 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301 }
4302 }
4303
4304 @Override
4305 public void updateLockTaskFeatures(int userId, int flags) {
4306 final int callingUid = Binder.getCallingUid();
4307 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 "updateLockTaskFeatures()");
4310 }
4311 synchronized (mGlobalLock) {
4312 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4313 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004314 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 }
4316 }
4317
4318 @Override
4319 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4320 synchronized (mGlobalLock) {
4321 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4322 if (r == null) {
4323 return;
4324 }
4325 final long origId = Binder.clearCallingIdentity();
4326 try {
4327 r.setShowWhenLocked(showWhenLocked);
4328 } finally {
4329 Binder.restoreCallingIdentity(origId);
4330 }
4331 }
4332 }
4333
4334 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004335 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4336 synchronized (mGlobalLock) {
4337 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4338 if (r == null) {
4339 return;
4340 }
4341 final long origId = Binder.clearCallingIdentity();
4342 try {
4343 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4344 } finally {
4345 Binder.restoreCallingIdentity(origId);
4346 }
4347 }
4348 }
4349
4350 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4352 synchronized (mGlobalLock) {
4353 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4354 if (r == null) {
4355 return;
4356 }
4357 final long origId = Binder.clearCallingIdentity();
4358 try {
4359 r.setTurnScreenOn(turnScreenOn);
4360 } finally {
4361 Binder.restoreCallingIdentity(origId);
4362 }
4363 }
4364 }
4365
4366 @Override
4367 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004368 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 "registerRemoteAnimations");
4370 definition.setCallingPid(Binder.getCallingPid());
4371 synchronized (mGlobalLock) {
4372 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4373 if (r == null) {
4374 return;
4375 }
4376 final long origId = Binder.clearCallingIdentity();
4377 try {
4378 r.registerRemoteAnimations(definition);
4379 } finally {
4380 Binder.restoreCallingIdentity(origId);
4381 }
4382 }
4383 }
4384
4385 @Override
4386 public void registerRemoteAnimationForNextActivityStart(String packageName,
4387 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 "registerRemoteAnimationForNextActivityStart");
4390 adapter.setCallingPid(Binder.getCallingPid());
4391 synchronized (mGlobalLock) {
4392 final long origId = Binder.clearCallingIdentity();
4393 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004394 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 packageName, adapter);
4396 } finally {
4397 Binder.restoreCallingIdentity(origId);
4398 }
4399 }
4400 }
4401
Evan Rosky966759f2019-01-15 10:33:58 -08004402 @Override
4403 public void registerRemoteAnimationsForDisplay(int displayId,
4404 RemoteAnimationDefinition definition) {
4405 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4406 "registerRemoteAnimations");
4407 definition.setCallingPid(Binder.getCallingPid());
4408 synchronized (mGlobalLock) {
4409 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4410 if (display == null) {
4411 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4412 return;
4413 }
4414 final long origId = Binder.clearCallingIdentity();
4415 try {
4416 display.mDisplayContent.registerRemoteAnimations(definition);
4417 } finally {
4418 Binder.restoreCallingIdentity(origId);
4419 }
4420 }
4421 }
4422
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4424 @Override
4425 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4426 synchronized (mGlobalLock) {
4427 final long origId = Binder.clearCallingIdentity();
4428 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004429 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 } finally {
4431 Binder.restoreCallingIdentity(origId);
4432 }
4433 }
4434 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004435
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004436 @Override
4437 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004439 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004440 final int pid = Binder.getCallingPid();
4441 final WindowProcessController wpc = mPidMap.get(pid);
4442 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004443 }
4444 }
4445
4446 @Override
4447 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004449 != PERMISSION_GRANTED) {
4450 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4451 + Binder.getCallingPid()
4452 + ", uid=" + Binder.getCallingUid()
4453 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4454 Slog.w(TAG, msg);
4455 throw new SecurityException(msg);
4456 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004458 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004459 final int pid = Binder.getCallingPid();
4460 final WindowProcessController proc = mPidMap.get(pid);
4461 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004462 }
4463 }
4464
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 @Override
4466 public void stopAppSwitches() {
4467 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4468 synchronized (mGlobalLock) {
4469 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4470 mDidAppSwitch = false;
4471 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4472 }
4473 }
4474
4475 @Override
4476 public void resumeAppSwitches() {
4477 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4478 synchronized (mGlobalLock) {
4479 // Note that we don't execute any pending app switches... we will
4480 // let those wait until either the timeout, or the next start
4481 // activity request.
4482 mAppSwitchesAllowedTime = 0;
4483 }
4484 }
4485
4486 void onStartActivitySetDidAppSwitch() {
4487 if (mDidAppSwitch) {
4488 // This is the second allowed switch since we stopped switches, so now just generally
4489 // allow switches. Use case:
4490 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4491 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4492 // anyone to switch again).
4493 mAppSwitchesAllowedTime = 0;
4494 } else {
4495 mDidAppSwitch = true;
4496 }
4497 }
4498
4499 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004500 boolean shouldDisableNonVrUiLocked() {
4501 return mVrController.shouldDisableNonVrUiLocked();
4502 }
4503
Wale Ogunwale53783742018-09-16 10:21:51 -07004504 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004505 // VR apps are expected to run in a main display. If an app is turning on VR for
4506 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4507 // fullscreen stack before enabling VR Mode.
4508 // TODO: The goal of this code is to keep the VR app on the main display. When the
4509 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4510 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4511 // option would be a better choice here.
4512 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4513 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4514 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004515 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004516 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004517 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004518 }
4519 mH.post(() -> {
4520 if (!mVrController.onVrModeChanged(r)) {
4521 return;
4522 }
4523 synchronized (mGlobalLock) {
4524 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4525 mWindowManager.disableNonVrUi(disableNonVrUi);
4526 if (disableNonVrUi) {
4527 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4528 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004529 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004530 }
4531 }
4532 });
4533 }
4534
Wale Ogunwale53783742018-09-16 10:21:51 -07004535 @Override
4536 public int getPackageScreenCompatMode(String packageName) {
4537 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4538 synchronized (mGlobalLock) {
4539 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4540 }
4541 }
4542
4543 @Override
4544 public void setPackageScreenCompatMode(String packageName, int mode) {
4545 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4546 "setPackageScreenCompatMode");
4547 synchronized (mGlobalLock) {
4548 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4549 }
4550 }
4551
4552 @Override
4553 public boolean getPackageAskScreenCompat(String packageName) {
4554 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4555 synchronized (mGlobalLock) {
4556 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4557 }
4558 }
4559
4560 @Override
4561 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4562 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4563 "setPackageAskScreenCompat");
4564 synchronized (mGlobalLock) {
4565 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4566 }
4567 }
4568
Wale Ogunwale64258362018-10-16 15:13:37 -07004569 public static String relaunchReasonToString(int relaunchReason) {
4570 switch (relaunchReason) {
4571 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4572 return "window_resize";
4573 case RELAUNCH_REASON_FREE_RESIZE:
4574 return "free_resize";
4575 default:
4576 return null;
4577 }
4578 }
4579
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004580 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004581 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 }
4583
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004584 /** Pokes the task persister. */
4585 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4586 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4587 }
4588
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004589 boolean isKeyguardLocked() {
4590 return mKeyguardController.isKeyguardLocked();
4591 }
4592
Garfield Tan01548632018-11-27 10:15:48 -08004593 /**
4594 * Clears launch params for the given package.
4595 * @param packageNames the names of the packages of which the launch params are to be cleared
4596 */
4597 @Override
4598 public void clearLaunchParamsForPackages(List<String> packageNames) {
4599 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4600 "clearLaunchParamsForPackages");
4601 synchronized (mGlobalLock) {
4602 for (int i = 0; i < packageNames.size(); ++i) {
4603 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4604 }
4605 }
4606 }
4607
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004608 /**
4609 * Makes the display with the given id a single task instance display. I.e the display can only
4610 * contain one task.
4611 */
4612 @Override
4613 public void setDisplayToSingleTaskInstance(int displayId) {
4614 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4615 "setDisplayToSingleTaskInstance");
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 final ActivityDisplay display =
4619 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4620 if (display != null) {
4621 display.setDisplayToSingleTaskInstance();
4622 }
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627
Wale Ogunwale31913b52018-10-13 08:29:31 -07004628 void dumpLastANRLocked(PrintWriter pw) {
4629 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4630 if (mLastANRState == null) {
4631 pw.println(" <no ANR has occurred since boot>");
4632 } else {
4633 pw.println(mLastANRState);
4634 }
4635 }
4636
4637 void dumpLastANRTracesLocked(PrintWriter pw) {
4638 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4639
4640 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4641 if (ArrayUtils.isEmpty(files)) {
4642 pw.println(" <no ANR has occurred since boot>");
4643 return;
4644 }
4645 // Find the latest file.
4646 File latest = null;
4647 for (File f : files) {
4648 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4649 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004650 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004651 }
4652 pw.print("File: ");
4653 pw.print(latest.getName());
4654 pw.println();
4655 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4656 String line;
4657 while ((line = in.readLine()) != null) {
4658 pw.println(line);
4659 }
4660 } catch (IOException e) {
4661 pw.print("Unable to read: ");
4662 pw.print(e);
4663 pw.println();
4664 }
4665 }
4666
4667 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4668 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4669 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4670 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4671 }
4672
4673 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4674 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4675 pw.println(header);
4676
Wale Ogunwaled32da472018-11-16 07:19:28 -08004677 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004678 dumpPackage);
4679 boolean needSep = printedAnything;
4680
4681 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004682 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004683 " ResumedActivity: ");
4684 if (printed) {
4685 printedAnything = true;
4686 needSep = false;
4687 }
4688
4689 if (dumpPackage == null) {
4690 if (needSep) {
4691 pw.println();
4692 }
4693 printedAnything = true;
4694 mStackSupervisor.dump(pw, " ");
4695 }
4696
4697 if (!printedAnything) {
4698 pw.println(" (nothing)");
4699 }
4700 }
4701
4702 void dumpActivityContainersLocked(PrintWriter pw) {
4703 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004704 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004705 pw.println(" ");
4706 }
4707
4708 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4709 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4710 getActivityStartController().dump(pw, "", dumpPackage);
4711 }
4712
4713 /**
4714 * There are three things that cmd can be:
4715 * - a flattened component name that matches an existing activity
4716 * - the cmd arg isn't the flattened component name of an existing activity:
4717 * dump all activity whose component contains the cmd as a substring
4718 * - A hex number of the ActivityRecord object instance.
4719 *
4720 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4721 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4722 */
4723 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4724 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4725 ArrayList<ActivityRecord> activities;
4726
4727 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004728 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004729 dumpFocusedStackOnly);
4730 }
4731
4732 if (activities.size() <= 0) {
4733 return false;
4734 }
4735
4736 String[] newArgs = new String[args.length - opti];
4737 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4738
4739 TaskRecord lastTask = null;
4740 boolean needSep = false;
4741 for (int i = activities.size() - 1; i >= 0; i--) {
4742 ActivityRecord r = activities.get(i);
4743 if (needSep) {
4744 pw.println();
4745 }
4746 needSep = true;
4747 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004748 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004749 if (lastTask != task) {
4750 lastTask = task;
4751 pw.print("TASK "); pw.print(lastTask.affinity);
4752 pw.print(" id="); pw.print(lastTask.taskId);
4753 pw.print(" userId="); pw.println(lastTask.userId);
4754 if (dumpAll) {
4755 lastTask.dump(pw, " ");
4756 }
4757 }
4758 }
4759 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4760 }
4761 return true;
4762 }
4763
4764 /**
4765 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4766 * there is a thread associated with the activity.
4767 */
4768 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4769 final ActivityRecord r, String[] args, boolean dumpAll) {
4770 String innerPrefix = prefix + " ";
4771 synchronized (mGlobalLock) {
4772 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4773 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4774 pw.print(" pid=");
4775 if (r.hasProcess()) pw.println(r.app.getPid());
4776 else pw.println("(not running)");
4777 if (dumpAll) {
4778 r.dump(pw, innerPrefix);
4779 }
4780 }
4781 if (r.attachedToProcess()) {
4782 // flush anything that is already in the PrintWriter since the thread is going
4783 // to write to the file descriptor directly
4784 pw.flush();
4785 try {
4786 TransferPipe tp = new TransferPipe();
4787 try {
4788 r.app.getThread().dumpActivity(tp.getWriteFd(),
4789 r.appToken, innerPrefix, args);
4790 tp.go(fd);
4791 } finally {
4792 tp.kill();
4793 }
4794 } catch (IOException e) {
4795 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4796 } catch (RemoteException e) {
4797 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4798 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004799 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004800 }
4801
sanryhuang498e77e2018-12-06 14:57:01 +08004802 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4803 boolean testPssMode) {
4804 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4805 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4806 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004807 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004808 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4809 st.toString());
4810 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004811 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4812 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4813 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004814 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4815 testPssMode);
4816 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004817 }
4818
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004819 int getCurrentUserId() {
4820 return mAmInternal.getCurrentUserId();
4821 }
4822
4823 private void enforceNotIsolatedCaller(String caller) {
4824 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4825 throw new SecurityException("Isolated process not allowed to call " + caller);
4826 }
4827 }
4828
Wale Ogunwalef6733932018-06-27 05:14:34 -07004829 public Configuration getConfiguration() {
4830 Configuration ci;
4831 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004832 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004833 ci.userSetLocale = false;
4834 }
4835 return ci;
4836 }
4837
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004838 /**
4839 * Current global configuration information. Contains general settings for the entire system,
4840 * also corresponds to the merged configuration of the default display.
4841 */
4842 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004843 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004844 }
4845
4846 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4847 boolean initLocale) {
4848 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4849 }
4850
4851 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4852 boolean initLocale, boolean deferResume) {
4853 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4854 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4855 UserHandle.USER_NULL, deferResume);
4856 }
4857
Wale Ogunwale59507092018-10-29 09:00:30 -07004858 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004859 final long origId = Binder.clearCallingIdentity();
4860 try {
4861 synchronized (mGlobalLock) {
4862 updateConfigurationLocked(values, null, false, true, userId,
4863 false /* deferResume */);
4864 }
4865 } finally {
4866 Binder.restoreCallingIdentity(origId);
4867 }
4868 }
4869
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004870 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4871 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4872 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4873 deferResume, null /* result */);
4874 }
4875
4876 /**
4877 * Do either or both things: (1) change the current configuration, and (2)
4878 * make sure the given activity is running with the (now) current
4879 * configuration. Returns true if the activity has been left running, or
4880 * false if <var>starting</var> is being destroyed to match the new
4881 * configuration.
4882 *
4883 * @param userId is only used when persistent parameter is set to true to persist configuration
4884 * for that particular user
4885 */
4886 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4887 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4888 ActivityTaskManagerService.UpdateConfigurationResult result) {
4889 int changes = 0;
4890 boolean kept = true;
4891
4892 if (mWindowManager != null) {
4893 mWindowManager.deferSurfaceLayout();
4894 }
4895 try {
4896 if (values != null) {
4897 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4898 deferResume);
4899 }
4900
4901 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4902 } finally {
4903 if (mWindowManager != null) {
4904 mWindowManager.continueSurfaceLayout();
4905 }
4906 }
4907
4908 if (result != null) {
4909 result.changes = changes;
4910 result.activityRelaunched = !kept;
4911 }
4912 return kept;
4913 }
4914
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004915 /** Update default (global) configuration and notify listeners about changes. */
4916 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4917 boolean persistent, int userId, boolean deferResume) {
4918 mTempConfig.setTo(getGlobalConfiguration());
4919 final int changes = mTempConfig.updateFrom(values);
4920 if (changes == 0) {
4921 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4922 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4923 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4924 // (even if there are no actual changes) to unfreeze the window.
4925 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4926 return 0;
4927 }
4928
4929 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4930 "Updating global configuration to: " + values);
4931
4932 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4933 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4934 values.colorMode,
4935 values.densityDpi,
4936 values.fontScale,
4937 values.hardKeyboardHidden,
4938 values.keyboard,
4939 values.keyboardHidden,
4940 values.mcc,
4941 values.mnc,
4942 values.navigation,
4943 values.navigationHidden,
4944 values.orientation,
4945 values.screenHeightDp,
4946 values.screenLayout,
4947 values.screenWidthDp,
4948 values.smallestScreenWidthDp,
4949 values.touchscreen,
4950 values.uiMode);
4951
4952
4953 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4954 final LocaleList locales = values.getLocales();
4955 int bestLocaleIndex = 0;
4956 if (locales.size() > 1) {
4957 if (mSupportedSystemLocales == null) {
4958 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4959 }
4960 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4961 }
4962 SystemProperties.set("persist.sys.locale",
4963 locales.get(bestLocaleIndex).toLanguageTag());
4964 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004965
4966 final Message m = PooledLambda.obtainMessage(
4967 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4968 locales.get(bestLocaleIndex));
4969 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004970 }
4971
Yunfan Chen75157d72018-07-27 14:47:21 +09004972 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004973
4974 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004975 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004976
4977 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4978 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004979 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004980
4981 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004982 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004983
4984 AttributeCache ac = AttributeCache.instance();
4985 if (ac != null) {
4986 ac.updateConfiguration(mTempConfig);
4987 }
4988
4989 // Make sure all resources in our process are updated right now, so that anyone who is going
4990 // to retrieve resource values after we return will be sure to get the new ones. This is
4991 // especially important during boot, where the first config change needs to guarantee all
4992 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004993 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004994
4995 // We need another copy of global config because we're scheduling some calls instead of
4996 // running them in place. We need to be sure that object we send will be handled unchanged.
4997 final Configuration configCopy = new Configuration(mTempConfig);
4998 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004999 final Message msg = PooledLambda.obtainMessage(
5000 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5001 this, userId, configCopy);
5002 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005003 }
5004
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005005 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005006 final int pid = mPidMap.keyAt(i);
5007 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005008 if (DEBUG_CONFIGURATION) {
5009 Slog.v(TAG_CONFIGURATION, "Update process config of "
5010 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005011 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005012 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005013 }
5014
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005015 final Message msg = PooledLambda.obtainMessage(
5016 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5017 mAmInternal, changes, initLocale);
5018 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005019
5020 // Override configuration of the default display duplicates global config, so we need to
5021 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005022 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005023 DEFAULT_DISPLAY);
5024
5025 return changes;
5026 }
5027
5028 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5029 boolean deferResume, int displayId) {
5030 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5031 displayId, null /* result */);
5032 }
5033
5034 /**
5035 * Updates override configuration specific for the selected display. If no config is provided,
5036 * new one will be computed in WM based on current display info.
5037 */
5038 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5039 ActivityRecord starting, boolean deferResume, int displayId,
5040 ActivityTaskManagerService.UpdateConfigurationResult result) {
5041 int changes = 0;
5042 boolean kept = true;
5043
5044 if (mWindowManager != null) {
5045 mWindowManager.deferSurfaceLayout();
5046 }
5047 try {
5048 if (values != null) {
5049 if (displayId == DEFAULT_DISPLAY) {
5050 // Override configuration of the default display duplicates global config, so
5051 // we're calling global config update instead for default display. It will also
5052 // apply the correct override config.
5053 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5054 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5055 } else {
5056 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5057 }
5058 }
5059
5060 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5061 } finally {
5062 if (mWindowManager != null) {
5063 mWindowManager.continueSurfaceLayout();
5064 }
5065 }
5066
5067 if (result != null) {
5068 result.changes = changes;
5069 result.activityRelaunched = !kept;
5070 }
5071 return kept;
5072 }
5073
5074 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5075 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005076 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005077 final int changes = mTempConfig.updateFrom(values);
5078 if (changes != 0) {
5079 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5080 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005081 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005082
5083 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5084 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005085 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086
Wale Ogunwale5c918702018-10-18 11:06:33 -07005087 // Post message to start process to avoid possible deadlock of calling into AMS with
5088 // the ATMS lock held.
5089 final Message msg = PooledLambda.obtainMessage(
5090 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5091 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5092 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005093 }
5094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005095 return changes;
5096 }
5097
Wale Ogunwalef6733932018-06-27 05:14:34 -07005098 private void updateEventDispatchingLocked(boolean booted) {
5099 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5100 }
5101
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005102 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5103 final ContentResolver resolver = mContext.getContentResolver();
5104 Settings.System.putConfigurationForUser(resolver, config, userId);
5105 }
5106
5107 private void sendLocaleToMountDaemonMsg(Locale l) {
5108 try {
5109 IBinder service = ServiceManager.getService("mount");
5110 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5111 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5112 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5113 } catch (RemoteException e) {
5114 Log.e(TAG, "Error storing locale for decryption UI", e);
5115 }
5116 }
5117
Alison Cichowlas3e340502018-08-07 17:15:01 -04005118 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5119 mStartActivitySources.remove(permissionToken);
5120 mExpiredStartAsCallerTokens.add(permissionToken);
5121 }
5122
5123 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5124 mExpiredStartAsCallerTokens.remove(permissionToken);
5125 }
5126
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005127 boolean isActivityStartsLoggingEnabled() {
5128 return mAmInternal.isActivityStartsLoggingEnabled();
5129 }
5130
Michal Karpinski8596ded2018-11-14 14:43:48 +00005131 boolean isBackgroundActivityStartsEnabled() {
5132 return mAmInternal.isBackgroundActivityStartsEnabled();
5133 }
5134
Wale Ogunwalef6733932018-06-27 05:14:34 -07005135 void enableScreenAfterBoot(boolean booted) {
5136 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5137 SystemClock.uptimeMillis());
5138 mWindowManager.enableScreenAfterBoot();
5139
5140 synchronized (mGlobalLock) {
5141 updateEventDispatchingLocked(booted);
5142 }
5143 }
5144
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005145 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5146 if (r == null || !r.hasProcess()) {
5147 return KEY_DISPATCHING_TIMEOUT_MS;
5148 }
5149 return getInputDispatchingTimeoutLocked(r.app);
5150 }
5151
5152 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005153 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005154 }
5155
Wale Ogunwalef6733932018-06-27 05:14:34 -07005156 /**
5157 * Decide based on the configuration whether we should show the ANR,
5158 * crash, etc dialogs. The idea is that if there is no affordance to
5159 * press the on-screen buttons, or the user experience would be more
5160 * greatly impacted than the crash itself, we shouldn't show the dialog.
5161 *
5162 * A thought: SystemUI might also want to get told about this, the Power
5163 * dialog / global actions also might want different behaviors.
5164 */
5165 private void updateShouldShowDialogsLocked(Configuration config) {
5166 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5167 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5168 && config.navigation == Configuration.NAVIGATION_NONAV);
5169 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5170 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5171 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5172 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5173 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5174 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5175 HIDE_ERROR_DIALOGS, 0) != 0;
5176 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5177 }
5178
5179 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5180 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5181 FONT_SCALE, 1.0f, userId);
5182
5183 synchronized (this) {
5184 if (getGlobalConfiguration().fontScale == scaleFactor) {
5185 return;
5186 }
5187
5188 final Configuration configuration
5189 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5190 configuration.fontScale = scaleFactor;
5191 updatePersistentConfiguration(configuration, userId);
5192 }
5193 }
5194
5195 // Actually is sleeping or shutting down or whatever else in the future
5196 // is an inactive state.
5197 boolean isSleepingOrShuttingDownLocked() {
5198 return isSleepingLocked() || mShuttingDown;
5199 }
5200
5201 boolean isSleepingLocked() {
5202 return mSleeping;
5203 }
5204
Riddle Hsu16567132018-08-16 21:37:47 +08005205 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005206 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005207 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005208 if (task.isActivityTypeStandard()) {
5209 if (mCurAppTimeTracker != r.appTimeTracker) {
5210 // We are switching app tracking. Complete the current one.
5211 if (mCurAppTimeTracker != null) {
5212 mCurAppTimeTracker.stop();
5213 mH.obtainMessage(
5214 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005215 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005216 mCurAppTimeTracker = null;
5217 }
5218 if (r.appTimeTracker != null) {
5219 mCurAppTimeTracker = r.appTimeTracker;
5220 startTimeTrackingFocusedActivityLocked();
5221 }
5222 } else {
5223 startTimeTrackingFocusedActivityLocked();
5224 }
5225 } else {
5226 r.appTimeTracker = null;
5227 }
5228 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5229 // TODO: Probably not, because we don't want to resume voice on switching
5230 // back to this activity
5231 if (task.voiceInteractor != null) {
5232 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5233 } else {
5234 finishRunningVoiceLocked();
5235
5236 if (mLastResumedActivity != null) {
5237 final IVoiceInteractionSession session;
5238
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005239 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005240 if (lastResumedActivityTask != null
5241 && lastResumedActivityTask.voiceSession != null) {
5242 session = lastResumedActivityTask.voiceSession;
5243 } else {
5244 session = mLastResumedActivity.voiceSession;
5245 }
5246
5247 if (session != null) {
5248 // We had been in a voice interaction session, but now focused has
5249 // move to something different. Just finish the session, we can't
5250 // return to it and retain the proper state and synchronization with
5251 // the voice interaction service.
5252 finishVoiceTask(session);
5253 }
5254 }
5255 }
5256
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005257 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5258 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005259 }
5260 updateResumedAppTrace(r);
5261 mLastResumedActivity = r;
5262
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005263 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005264
5265 applyUpdateLockStateLocked(r);
5266 applyUpdateVrModeLocked(r);
5267
5268 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005269 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005270 r == null ? "NULL" : r.shortComponentName,
5271 reason);
5272 }
5273
5274 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5275 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005276 final ActivityTaskManagerInternal.SleepToken token =
5277 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 updateSleepIfNeededLocked();
5279 return token;
5280 }
5281 }
5282
5283 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005284 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005285 final boolean wasSleeping = mSleeping;
5286 boolean updateOomAdj = false;
5287
5288 if (!shouldSleep) {
5289 // If wasSleeping is true, we need to wake up activity manager state from when
5290 // we started sleeping. In either case, we need to apply the sleep tokens, which
5291 // will wake up stacks or put them to sleep as appropriate.
5292 if (wasSleeping) {
5293 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005294 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5295 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005296 startTimeTrackingFocusedActivityLocked();
5297 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5298 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5299 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005300 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005301 if (wasSleeping) {
5302 updateOomAdj = true;
5303 }
5304 } else if (!mSleeping && shouldSleep) {
5305 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005306 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5307 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 if (mCurAppTimeTracker != null) {
5309 mCurAppTimeTracker.stop();
5310 }
5311 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5312 mStackSupervisor.goingToSleepLocked();
5313 updateResumedAppTrace(null /* resumed */);
5314 updateOomAdj = true;
5315 }
5316 if (updateOomAdj) {
5317 mH.post(mAmInternal::updateOomAdj);
5318 }
5319 }
5320
5321 void updateOomAdj() {
5322 mH.post(mAmInternal::updateOomAdj);
5323 }
5324
Wale Ogunwale53783742018-09-16 10:21:51 -07005325 void updateCpuStats() {
5326 mH.post(mAmInternal::updateCpuStats);
5327 }
5328
Hui Yu03d12402018-12-06 18:00:37 -08005329 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5330 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005331 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5332 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005333 mH.sendMessage(m);
5334 }
5335
Hui Yu03d12402018-12-06 18:00:37 -08005336 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005337 ComponentName taskRoot = null;
5338 final TaskRecord task = activity.getTaskRecord();
5339 if (task != null) {
5340 final ActivityRecord rootActivity = task.getRootActivity();
5341 if (rootActivity != null) {
5342 taskRoot = rootActivity.mActivityComponent;
5343 }
5344 }
5345
Hui Yu03d12402018-12-06 18:00:37 -08005346 final Message m = PooledLambda.obtainMessage(
5347 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005348 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005349 mH.sendMessage(m);
5350 }
5351
Wale Ogunwale53783742018-09-16 10:21:51 -07005352 void setBooting(boolean booting) {
5353 mAmInternal.setBooting(booting);
5354 }
5355
5356 boolean isBooting() {
5357 return mAmInternal.isBooting();
5358 }
5359
5360 void setBooted(boolean booted) {
5361 mAmInternal.setBooted(booted);
5362 }
5363
5364 boolean isBooted() {
5365 return mAmInternal.isBooted();
5366 }
5367
5368 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5369 mH.post(() -> {
5370 if (finishBooting) {
5371 mAmInternal.finishBooting();
5372 }
5373 if (enableScreen) {
5374 mInternal.enableScreenAfterBoot(isBooted());
5375 }
5376 });
5377 }
5378
5379 void setHeavyWeightProcess(ActivityRecord root) {
5380 mHeavyWeightProcess = root.app;
5381 final Message m = PooledLambda.obtainMessage(
5382 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005383 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005384 mH.sendMessage(m);
5385 }
5386
5387 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5388 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5389 return;
5390 }
5391
5392 mHeavyWeightProcess = null;
5393 final Message m = PooledLambda.obtainMessage(
5394 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5395 proc.mUserId);
5396 mH.sendMessage(m);
5397 }
5398
5399 private void cancelHeavyWeightProcessNotification(int userId) {
5400 final INotificationManager inm = NotificationManager.getService();
5401 if (inm == null) {
5402 return;
5403 }
5404 try {
5405 inm.cancelNotificationWithTag("android", null,
5406 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5407 } catch (RuntimeException e) {
5408 Slog.w(TAG, "Error canceling notification for service", e);
5409 } catch (RemoteException e) {
5410 }
5411
5412 }
5413
5414 private void postHeavyWeightProcessNotification(
5415 WindowProcessController proc, Intent intent, int userId) {
5416 if (proc == null) {
5417 return;
5418 }
5419
5420 final INotificationManager inm = NotificationManager.getService();
5421 if (inm == null) {
5422 return;
5423 }
5424
5425 try {
5426 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5427 String text = mContext.getString(R.string.heavy_weight_notification,
5428 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5429 Notification notification =
5430 new Notification.Builder(context,
5431 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5432 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5433 .setWhen(0)
5434 .setOngoing(true)
5435 .setTicker(text)
5436 .setColor(mContext.getColor(
5437 com.android.internal.R.color.system_notification_accent_color))
5438 .setContentTitle(text)
5439 .setContentText(
5440 mContext.getText(R.string.heavy_weight_notification_detail))
5441 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5442 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5443 new UserHandle(userId)))
5444 .build();
5445 try {
5446 inm.enqueueNotificationWithTag("android", "android", null,
5447 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5448 } catch (RuntimeException e) {
5449 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5450 } catch (RemoteException e) {
5451 }
5452 } catch (PackageManager.NameNotFoundException e) {
5453 Slog.w(TAG, "Unable to create context for heavy notification", e);
5454 }
5455
5456 }
5457
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005458 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5459 IBinder token, String resultWho, int requestCode, Intent[] intents,
5460 String[] resolvedTypes, int flags, Bundle bOptions) {
5461
5462 ActivityRecord activity = null;
5463 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5464 activity = ActivityRecord.isInStackLocked(token);
5465 if (activity == null) {
5466 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5467 return null;
5468 }
5469 if (activity.finishing) {
5470 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5471 return null;
5472 }
5473 }
5474
5475 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5476 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5477 bOptions);
5478 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5479 if (noCreate) {
5480 return rec;
5481 }
5482 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5483 if (activity.pendingResults == null) {
5484 activity.pendingResults = new HashSet<>();
5485 }
5486 activity.pendingResults.add(rec.ref);
5487 }
5488 return rec;
5489 }
5490
Andrii Kulian52d255c2018-07-13 11:32:19 -07005491 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005493 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5495 mCurAppTimeTracker.start(resumedActivity.packageName);
5496 }
5497 }
5498
5499 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5500 if (mTracedResumedActivity != null) {
5501 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5502 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5503 }
5504 if (resumed != null) {
5505 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5506 constructResumedTraceName(resumed.packageName), 0);
5507 }
5508 mTracedResumedActivity = resumed;
5509 }
5510
5511 private String constructResumedTraceName(String packageName) {
5512 return "focused app: " + packageName;
5513 }
5514
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005515 /** Applies latest configuration and/or visibility updates if needed. */
5516 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5517 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005518 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005519 // mainStack is null during startup.
5520 if (mainStack != null) {
5521 if (changes != 0 && starting == null) {
5522 // If the configuration changed, and the caller is not already
5523 // in the process of starting an activity, then find the top
5524 // activity to check if its configuration needs to change.
5525 starting = mainStack.topRunningActivityLocked();
5526 }
5527
5528 if (starting != null) {
5529 kept = starting.ensureActivityConfiguration(changes,
5530 false /* preserveWindow */);
5531 // And we need to make sure at this point that all other activities
5532 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005533 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005534 !PRESERVE_WINDOWS);
5535 }
5536 }
5537
5538 return kept;
5539 }
5540
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005541 void scheduleAppGcsLocked() {
5542 mH.post(() -> mAmInternal.scheduleAppGcs());
5543 }
5544
Wale Ogunwale53783742018-09-16 10:21:51 -07005545 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5546 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5547 }
5548
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005549 /**
5550 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5551 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5552 * on demand.
5553 */
5554 IPackageManager getPackageManager() {
5555 return AppGlobals.getPackageManager();
5556 }
5557
5558 PackageManagerInternal getPackageManagerInternalLocked() {
5559 if (mPmInternal == null) {
5560 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5561 }
5562 return mPmInternal;
5563 }
5564
Wale Ogunwale008163e2018-07-23 23:11:08 -07005565 AppWarnings getAppWarningsLocked() {
5566 return mAppWarnings;
5567 }
5568
Wale Ogunwale214f3482018-10-04 11:00:47 -07005569 Intent getHomeIntent() {
5570 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5571 intent.setComponent(mTopComponent);
5572 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5573 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5574 intent.addCategory(Intent.CATEGORY_HOME);
5575 }
5576 return intent;
5577 }
5578
Chilun2ef71f72018-11-16 17:57:15 +08005579 /**
5580 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5581 * activities.
5582 *
5583 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5584 * component defined in config_secondaryHomeComponent.
5585 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5586 */
5587 Intent getSecondaryHomeIntent(String preferredPackage) {
5588 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5589 if (preferredPackage == null) {
5590 // Using the component stored in config if no package name.
5591 final String secondaryHomeComponent = mContext.getResources().getString(
5592 com.android.internal.R.string.config_secondaryHomeComponent);
5593 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5594 } else {
5595 intent.setPackage(preferredPackage);
5596 }
5597 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5598 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5599 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5600 }
5601 return intent;
5602 }
5603
Wale Ogunwale214f3482018-10-04 11:00:47 -07005604 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5605 if (info == null) return null;
5606 ApplicationInfo newInfo = new ApplicationInfo(info);
5607 newInfo.initForUser(userId);
5608 return newInfo;
5609 }
5610
Wale Ogunwale9c103022018-10-18 07:44:54 -07005611 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005612 if (uid == SYSTEM_UID) {
5613 // The system gets to run in any process. If there are multiple processes with the same
5614 // uid, just pick the first (this should never happen).
5615 final SparseArray<WindowProcessController> procs =
5616 mProcessNames.getMap().get(processName);
5617 if (procs == null) return null;
5618 final int procCount = procs.size();
5619 for (int i = 0; i < procCount; i++) {
5620 final int procUid = procs.keyAt(i);
5621 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5622 // Don't use an app process or different user process for system component.
5623 continue;
5624 }
5625 return procs.valueAt(i);
5626 }
5627 }
5628
5629 return mProcessNames.get(processName, uid);
5630 }
5631
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005632 WindowProcessController getProcessController(IApplicationThread thread) {
5633 if (thread == null) {
5634 return null;
5635 }
5636
5637 final IBinder threadBinder = thread.asBinder();
5638 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5639 for (int i = pmap.size()-1; i >= 0; i--) {
5640 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5641 for (int j = procs.size() - 1; j >= 0; j--) {
5642 final WindowProcessController proc = procs.valueAt(j);
5643 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5644 return proc;
5645 }
5646 }
5647 }
5648
5649 return null;
5650 }
5651
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005652 int getUidStateLocked(int uid) {
5653 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5654 }
5655
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005656 boolean isUidForeground(int uid) {
5657 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5658 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5659 }
5660
Wale Ogunwale9de19442018-10-18 19:05:03 -07005661 /**
5662 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5663 * the whitelist
5664 */
5665 String getPendingTempWhitelistTagForUidLocked(int uid) {
5666 return mPendingTempWhitelist.get(uid);
5667 }
5668
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005669 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5670 if (true || Build.IS_USER) {
5671 return;
5672 }
5673
5674 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5675 StrictMode.allowThreadDiskWrites();
5676 try {
5677 File tracesDir = new File("/data/anr");
5678 File tracesFile = null;
5679 try {
5680 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5681
5682 StringBuilder sb = new StringBuilder();
5683 Time tobj = new Time();
5684 tobj.set(System.currentTimeMillis());
5685 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5686 sb.append(": ");
5687 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5688 sb.append(" since ");
5689 sb.append(msg);
5690 FileOutputStream fos = new FileOutputStream(tracesFile);
5691 fos.write(sb.toString().getBytes());
5692 if (app == null) {
5693 fos.write("\n*** No application process!".getBytes());
5694 }
5695 fos.close();
5696 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5697 } catch (IOException e) {
5698 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5699 return;
5700 }
5701
5702 if (app != null && app.getPid() > 0) {
5703 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5704 firstPids.add(app.getPid());
5705 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5706 }
5707
5708 File lastTracesFile = null;
5709 File curTracesFile = null;
5710 for (int i=9; i>=0; i--) {
5711 String name = String.format(Locale.US, "slow%02d.txt", i);
5712 curTracesFile = new File(tracesDir, name);
5713 if (curTracesFile.exists()) {
5714 if (lastTracesFile != null) {
5715 curTracesFile.renameTo(lastTracesFile);
5716 } else {
5717 curTracesFile.delete();
5718 }
5719 }
5720 lastTracesFile = curTracesFile;
5721 }
5722 tracesFile.renameTo(curTracesFile);
5723 } finally {
5724 StrictMode.setThreadPolicy(oldPolicy);
5725 }
5726 }
5727
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005728 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005729 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005730
5731
Wale Ogunwale98875612018-10-12 07:53:02 -07005732 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5733 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005734
Riddle Hsud93a6c42018-11-29 21:50:06 +08005735 H(Looper looper) {
5736 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005737 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005738
5739 @Override
5740 public void handleMessage(Message msg) {
5741 switch (msg.what) {
5742 case REPORT_TIME_TRACKER_MSG: {
5743 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5744 tracker.deliverResult(mContext);
5745 } break;
5746 }
5747 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005748 }
5749
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005750 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005751 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005752
5753 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005754 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005755 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005756
5757 @Override
5758 public void handleMessage(Message msg) {
5759 switch (msg.what) {
5760 case DISMISS_DIALOG_UI_MSG: {
5761 final Dialog d = (Dialog) msg.obj;
5762 d.dismiss();
5763 break;
5764 }
5765 }
5766 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005767 }
5768
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005769 final class LocalService extends ActivityTaskManagerInternal {
5770 @Override
5771 public SleepToken acquireSleepToken(String tag, int displayId) {
5772 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005773 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005774 }
5775
5776 @Override
5777 public ComponentName getHomeActivityForUser(int userId) {
5778 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005779 final ActivityRecord homeActivity =
5780 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005781 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
5783 }
5784
5785 @Override
5786 public void onLocalVoiceInteractionStarted(IBinder activity,
5787 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5788 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005789 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005790 }
5791 }
5792
5793 @Override
5794 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5795 synchronized (mGlobalLock) {
5796 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5797 reasons, timestamp);
5798 }
5799 }
5800
5801 @Override
5802 public void notifyAppTransitionFinished() {
5803 synchronized (mGlobalLock) {
5804 mStackSupervisor.notifyAppTransitionDone();
5805 }
5806 }
5807
5808 @Override
5809 public void notifyAppTransitionCancelled() {
5810 synchronized (mGlobalLock) {
5811 mStackSupervisor.notifyAppTransitionDone();
5812 }
5813 }
5814
5815 @Override
5816 public List<IBinder> getTopVisibleActivities() {
5817 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005818 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005819 }
5820 }
5821
5822 @Override
5823 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5824 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005825 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005826 }
5827 }
5828
5829 @Override
5830 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5831 Bundle bOptions) {
5832 Preconditions.checkNotNull(intents, "intents");
5833 final String[] resolvedTypes = new String[intents.length];
5834
5835 // UID of the package on user userId.
5836 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5837 // packageUid may not be initialized.
5838 int packageUid = 0;
5839 final long ident = Binder.clearCallingIdentity();
5840
5841 try {
5842 for (int i = 0; i < intents.length; i++) {
5843 resolvedTypes[i] =
5844 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5845 }
5846
5847 packageUid = AppGlobals.getPackageManager().getPackageUid(
5848 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5849 } catch (RemoteException e) {
5850 // Shouldn't happen.
5851 } finally {
5852 Binder.restoreCallingIdentity(ident);
5853 }
5854
5855 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005856 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005857 packageUid, packageName,
5858 intents, resolvedTypes, null /* resultTo */,
5859 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005860 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5861 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005862 }
5863 }
5864
5865 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005866 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5867 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5868 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5869 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005870 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005871 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005872 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5873 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5874 userId, validateIncomingUser, originatingPendingIntent,
5875 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005876 }
5877 }
5878
5879 @Override
5880 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5881 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5882 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5883 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005884 PendingIntentRecord originatingPendingIntent,
5885 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005886 synchronized (mGlobalLock) {
5887 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5888 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5889 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005890 validateIncomingUser, originatingPendingIntent,
5891 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005892 }
5893 }
5894
5895 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005896 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5897 Intent intent, Bundle options, int userId) {
5898 return ActivityTaskManagerService.this.startActivityAsUser(
5899 caller, callerPacakge, intent,
5900 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5901 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5902 false /*validateIncomingUser*/);
5903 }
5904
5905 @Override
lumark588a3e82018-07-20 18:53:54 +08005906 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005907 synchronized (mGlobalLock) {
5908
5909 // We might change the visibilities here, so prepare an empty app transition which
5910 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005911 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005912 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005913 if (activityDisplay == null) {
5914 return;
5915 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005916 final DisplayContent dc = activityDisplay.mDisplayContent;
5917 final boolean wasTransitionSet =
5918 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005919 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005920 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005921 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005922 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005923
5924 // If there was a transition set already we don't want to interfere with it as we
5925 // might be starting it too early.
5926 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005927 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005928 }
5929 }
5930 if (callback != null) {
5931 callback.run();
5932 }
5933 }
5934
5935 @Override
5936 public void notifyKeyguardTrustedChanged() {
5937 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005938 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005939 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005940 }
5941 }
5942 }
5943
5944 /**
5945 * Called after virtual display Id is updated by
5946 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5947 * {@param vrVr2dDisplayId}.
5948 */
5949 @Override
5950 public void setVr2dDisplayId(int vr2dDisplayId) {
5951 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5952 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005953 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005954 }
5955 }
5956
5957 @Override
5958 public void setFocusedActivity(IBinder token) {
5959 synchronized (mGlobalLock) {
5960 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5961 if (r == null) {
5962 throw new IllegalArgumentException(
5963 "setFocusedActivity: No activity record matching token=" + token);
5964 }
Louis Chang19443452018-10-09 12:10:21 +08005965 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005966 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005967 }
5968 }
5969 }
5970
5971 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005972 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005973 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005974 }
5975
5976 @Override
5977 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005978 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005979 }
5980
5981 @Override
5982 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005983 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005984 }
5985
5986 @Override
5987 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5988 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5989 }
5990
5991 @Override
5992 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005993 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005994 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005995
5996 @Override
5997 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5998 synchronized (mGlobalLock) {
5999 mActiveVoiceInteractionServiceComponent = component;
6000 }
6001 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006002
6003 @Override
6004 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6005 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6006 return;
6007 }
6008 synchronized (mGlobalLock) {
6009 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6010 if (types == null) {
6011 if (uid < 0) {
6012 return;
6013 }
6014 types = new ArrayMap<>();
6015 mAllowAppSwitchUids.put(userId, types);
6016 }
6017 if (uid < 0) {
6018 types.remove(type);
6019 } else {
6020 types.put(type, uid);
6021 }
6022 }
6023 }
6024
6025 @Override
6026 public void onUserStopped(int userId) {
6027 synchronized (mGlobalLock) {
6028 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6029 mAllowAppSwitchUids.remove(userId);
6030 }
6031 }
6032
6033 @Override
6034 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6035 synchronized (mGlobalLock) {
6036 return ActivityTaskManagerService.this.isGetTasksAllowed(
6037 caller, callingPid, callingUid);
6038 }
6039 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006040
6041 @Override
6042 public void onProcessAdded(WindowProcessController proc) {
6043 synchronized (mGlobalLock) {
6044 mProcessNames.put(proc.mName, proc.mUid, proc);
6045 }
6046 }
6047
6048 @Override
6049 public void onProcessRemoved(String name, int uid) {
6050 synchronized (mGlobalLock) {
6051 mProcessNames.remove(name, uid);
6052 }
6053 }
6054
6055 @Override
6056 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6057 synchronized (mGlobalLock) {
6058 if (proc == mHomeProcess) {
6059 mHomeProcess = null;
6060 }
6061 if (proc == mPreviousProcess) {
6062 mPreviousProcess = null;
6063 }
6064 }
6065 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006066
6067 @Override
6068 public int getTopProcessState() {
6069 synchronized (mGlobalLock) {
6070 return mTopProcessState;
6071 }
6072 }
6073
6074 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006075 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6076 synchronized (mGlobalLock) {
6077 return proc == mHeavyWeightProcess;
6078 }
6079 }
6080
6081 @Override
6082 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6083 synchronized (mGlobalLock) {
6084 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6085 }
6086 }
6087
6088 @Override
6089 public void finishHeavyWeightApp() {
6090 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006091 if (mHeavyWeightProcess != null) {
6092 mHeavyWeightProcess.finishActivities();
6093 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006094 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6095 mHeavyWeightProcess);
6096 }
6097 }
6098
6099 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006100 public boolean isSleeping() {
6101 synchronized (mGlobalLock) {
6102 return isSleepingLocked();
6103 }
6104 }
6105
6106 @Override
6107 public boolean isShuttingDown() {
6108 synchronized (mGlobalLock) {
6109 return mShuttingDown;
6110 }
6111 }
6112
6113 @Override
6114 public boolean shuttingDown(boolean booted, int timeout) {
6115 synchronized (mGlobalLock) {
6116 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006117 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006118 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006119 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006120 return mStackSupervisor.shutdownLocked(timeout);
6121 }
6122 }
6123
6124 @Override
6125 public void enableScreenAfterBoot(boolean booted) {
6126 synchronized (mGlobalLock) {
6127 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6128 SystemClock.uptimeMillis());
6129 mWindowManager.enableScreenAfterBoot();
6130 updateEventDispatchingLocked(booted);
6131 }
6132 }
6133
6134 @Override
6135 public boolean showStrictModeViolationDialog() {
6136 synchronized (mGlobalLock) {
6137 return mShowDialogs && !mSleeping && !mShuttingDown;
6138 }
6139 }
6140
6141 @Override
6142 public void showSystemReadyErrorDialogsIfNeeded() {
6143 synchronized (mGlobalLock) {
6144 try {
6145 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6146 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6147 + " data partition or your device will be unstable.");
6148 mUiHandler.post(() -> {
6149 if (mShowDialogs) {
6150 AlertDialog d = new BaseErrorDialog(mUiContext);
6151 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6152 d.setCancelable(false);
6153 d.setTitle(mUiContext.getText(R.string.android_system_label));
6154 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6155 d.setButton(DialogInterface.BUTTON_POSITIVE,
6156 mUiContext.getText(R.string.ok),
6157 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6158 d.show();
6159 }
6160 });
6161 }
6162 } catch (RemoteException e) {
6163 }
6164
6165 if (!Build.isBuildConsistent()) {
6166 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6167 mUiHandler.post(() -> {
6168 if (mShowDialogs) {
6169 AlertDialog d = new BaseErrorDialog(mUiContext);
6170 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6171 d.setCancelable(false);
6172 d.setTitle(mUiContext.getText(R.string.android_system_label));
6173 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6174 d.setButton(DialogInterface.BUTTON_POSITIVE,
6175 mUiContext.getText(R.string.ok),
6176 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6177 d.show();
6178 }
6179 });
6180 }
6181 }
6182 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006183
6184 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006185 public void onProcessMapped(int pid, WindowProcessController proc) {
6186 synchronized (mGlobalLock) {
6187 mPidMap.put(pid, proc);
6188 }
6189 }
6190
6191 @Override
6192 public void onProcessUnMapped(int pid) {
6193 synchronized (mGlobalLock) {
6194 mPidMap.remove(pid);
6195 }
6196 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006197
6198 @Override
6199 public void onPackageDataCleared(String name) {
6200 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006201 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006202 mAppWarnings.onPackageDataCleared(name);
6203 }
6204 }
6205
6206 @Override
6207 public void onPackageUninstalled(String name) {
6208 synchronized (mGlobalLock) {
6209 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006210 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006211 }
6212 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006213
6214 @Override
6215 public void onPackageAdded(String name, boolean replacing) {
6216 synchronized (mGlobalLock) {
6217 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6218 }
6219 }
6220
6221 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006222 public void onPackageReplaced(ApplicationInfo aInfo) {
6223 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006224 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006225 }
6226 }
6227
6228 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006229 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6230 synchronized (mGlobalLock) {
6231 return compatibilityInfoForPackageLocked(ai);
6232 }
6233 }
6234
Yunfan Chen75157d72018-07-27 14:47:21 +09006235 /**
6236 * Set the corresponding display information for the process global configuration. To be
6237 * called when we need to show IME on a different display.
6238 *
6239 * @param pid The process id associated with the IME window.
6240 * @param displayId The ID of the display showing the IME.
6241 */
6242 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006243 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006244 if (pid == MY_PID || pid < 0) {
6245 if (DEBUG_CONFIGURATION) {
6246 Slog.w(TAG,
6247 "Trying to update display configuration for system/invalid process.");
6248 }
6249 return;
6250 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006251 synchronized (mGlobalLock) {
6252 final ActivityDisplay activityDisplay =
6253 mRootActivityContainer.getActivityDisplay(displayId);
6254 if (activityDisplay == null) {
6255 // Call might come when display is not yet added or has been removed.
6256 if (DEBUG_CONFIGURATION) {
6257 Slog.w(TAG, "Trying to update display configuration for non-existing "
6258 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006259 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006260 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006261 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006262 final WindowProcessController process = mPidMap.get(pid);
6263 if (process == null) {
6264 if (DEBUG_CONFIGURATION) {
6265 Slog.w(TAG, "Trying to update display configuration for invalid "
6266 + "process, pid=" + pid);
6267 }
6268 return;
6269 }
6270 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6271 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006272 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006273
6274 @Override
6275 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6276 int requestCode, int resultCode, Intent data) {
6277 synchronized (mGlobalLock) {
6278 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006279 if (r != null && r.getActivityStack() != null) {
6280 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6281 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006282 }
6283 }
6284 }
6285
6286 @Override
6287 public void clearPendingResultForActivity(IBinder activityToken,
6288 WeakReference<PendingIntentRecord> pir) {
6289 synchronized (mGlobalLock) {
6290 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6291 if (r != null && r.pendingResults != null) {
6292 r.pendingResults.remove(pir);
6293 }
6294 }
6295 }
6296
6297 @Override
6298 public IIntentSender getIntentSender(int type, String packageName,
6299 int callingUid, int userId, IBinder token, String resultWho,
6300 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6301 Bundle bOptions) {
6302 synchronized (mGlobalLock) {
6303 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6304 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6305 }
6306 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006307
6308 @Override
6309 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6310 synchronized (mGlobalLock) {
6311 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6312 if (r == null) {
6313 return null;
6314 }
6315 if (r.mServiceConnectionsHolder == null) {
6316 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6317 ActivityTaskManagerService.this, r);
6318 }
6319
6320 return r.mServiceConnectionsHolder;
6321 }
6322 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006323
6324 @Override
6325 public Intent getHomeIntent() {
6326 synchronized (mGlobalLock) {
6327 return ActivityTaskManagerService.this.getHomeIntent();
6328 }
6329 }
6330
6331 @Override
6332 public boolean startHomeActivity(int userId, String reason) {
6333 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006334 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006335 }
6336 }
6337
6338 @Override
6339 public boolean startHomeOnAllDisplays(int userId, String reason) {
6340 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006341 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006342 }
6343 }
6344
6345 @Override
6346 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6347 synchronized (mGlobalLock) {
6348 if (mFactoryTest == FACTORY_TEST_OFF) {
6349 return false;
6350 }
6351 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6352 && wpc.mName.equals(mTopComponent.getPackageName())) {
6353 return true;
6354 }
6355 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6356 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6357 }
6358 }
6359
6360 @Override
6361 public void updateTopComponentForFactoryTest() {
6362 synchronized (mGlobalLock) {
6363 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6364 return;
6365 }
6366 final ResolveInfo ri = mContext.getPackageManager()
6367 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6368 final CharSequence errorMsg;
6369 if (ri != null) {
6370 final ActivityInfo ai = ri.activityInfo;
6371 final ApplicationInfo app = ai.applicationInfo;
6372 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6373 mTopAction = Intent.ACTION_FACTORY_TEST;
6374 mTopData = null;
6375 mTopComponent = new ComponentName(app.packageName, ai.name);
6376 errorMsg = null;
6377 } else {
6378 errorMsg = mContext.getResources().getText(
6379 com.android.internal.R.string.factorytest_not_system);
6380 }
6381 } else {
6382 errorMsg = mContext.getResources().getText(
6383 com.android.internal.R.string.factorytest_no_action);
6384 }
6385 if (errorMsg == null) {
6386 return;
6387 }
6388
6389 mTopAction = null;
6390 mTopData = null;
6391 mTopComponent = null;
6392 mUiHandler.post(() -> {
6393 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6394 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006395 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006396 });
6397 }
6398 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006399
6400 @Override
6401 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6402 Runnable finishInstrumentationCallback) {
6403 synchronized (mGlobalLock) {
6404 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006405 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006406
6407 wpc.clearRecentTasks();
6408 wpc.clearActivities();
6409
6410 if (wpc.isInstrumenting()) {
6411 finishInstrumentationCallback.run();
6412 }
6413
Jorim Jaggid0752812018-10-16 16:07:20 +02006414 if (!restarting && hasVisibleActivities) {
6415 mWindowManager.deferSurfaceLayout();
6416 try {
6417 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6418 // If there was nothing to resume, and we are not already restarting
6419 // this process, but there is a visible activity that is hosted by the
6420 // process...then make sure all visible activities are running, taking
6421 // care of restarting this process.
6422 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6423 !PRESERVE_WINDOWS);
6424 }
6425 } finally {
6426 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006427 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006428 }
6429 }
6430 }
6431
6432 @Override
6433 public void closeSystemDialogs(String reason) {
6434 enforceNotIsolatedCaller("closeSystemDialogs");
6435
6436 final int pid = Binder.getCallingPid();
6437 final int uid = Binder.getCallingUid();
6438 final long origId = Binder.clearCallingIdentity();
6439 try {
6440 synchronized (mGlobalLock) {
6441 // Only allow this from foreground processes, so that background
6442 // applications can't abuse it to prevent system UI from being shown.
6443 if (uid >= FIRST_APPLICATION_UID) {
6444 final WindowProcessController proc = mPidMap.get(pid);
6445 if (!proc.isPerceptible()) {
6446 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6447 + " from background process " + proc);
6448 return;
6449 }
6450 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006451 mWindowManager.closeSystemDialogs(reason);
6452
Wale Ogunwaled32da472018-11-16 07:19:28 -08006453 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006454 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006455 // Call into AM outside the synchronized block.
6456 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006457 } finally {
6458 Binder.restoreCallingIdentity(origId);
6459 }
6460 }
6461
6462 @Override
6463 public void cleanupDisabledPackageComponents(
6464 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6465 synchronized (mGlobalLock) {
6466 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006467 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006468 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006469 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006470 mStackSupervisor.scheduleIdleLocked();
6471 }
6472
6473 // Clean-up disabled tasks
6474 getRecentTasks().cleanupDisabledPackageTasksLocked(
6475 packageName, disabledClasses, userId);
6476 }
6477 }
6478
6479 @Override
6480 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6481 int userId) {
6482 synchronized (mGlobalLock) {
6483
6484 boolean didSomething =
6485 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006486 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006487 null, doit, evenPersistent, userId);
6488 return didSomething;
6489 }
6490 }
6491
6492 @Override
6493 public void resumeTopActivities(boolean scheduleIdle) {
6494 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006495 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006496 if (scheduleIdle) {
6497 mStackSupervisor.scheduleIdleLocked();
6498 }
6499 }
6500 }
6501
6502 @Override
6503 public void preBindApplication(WindowProcessController wpc) {
6504 synchronized (mGlobalLock) {
6505 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6506 }
6507 }
6508
6509 @Override
6510 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6511 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006512 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006513 }
6514 }
6515
6516 @Override
6517 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6518 try {
6519 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6520 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6521 }
6522 } catch (RemoteException ex) {
6523 throw new SecurityException("Fail to check is caller a privileged app", ex);
6524 }
6525
6526 synchronized (mGlobalLock) {
6527 final long ident = Binder.clearCallingIdentity();
6528 try {
6529 if (mAmInternal.shouldConfirmCredentials(userId)) {
6530 if (mKeyguardController.isKeyguardLocked()) {
6531 // Showing launcher to avoid user entering credential twice.
6532 startHomeActivity(currentUserId, "notifyLockedProfile");
6533 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006534 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006535 }
6536 } finally {
6537 Binder.restoreCallingIdentity(ident);
6538 }
6539 }
6540 }
6541
6542 @Override
6543 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6544 mAmInternal.enforceCallingPermission(
6545 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6546
6547 synchronized (mGlobalLock) {
6548 final long ident = Binder.clearCallingIdentity();
6549 try {
6550 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6551 FLAG_ACTIVITY_TASK_ON_HOME);
6552 ActivityOptions activityOptions = options != null
6553 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006554 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006555 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006556 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006557 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006558 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006559 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6560 UserHandle.CURRENT);
6561 } finally {
6562 Binder.restoreCallingIdentity(ident);
6563 }
6564 }
6565 }
6566
6567 @Override
6568 public void writeActivitiesToProto(ProtoOutputStream proto) {
6569 synchronized (mGlobalLock) {
6570 // The output proto of "activity --proto activities"
6571 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006572 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006573 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6574 }
6575 }
6576
6577 @Override
6578 public void saveANRState(String reason) {
6579 synchronized (mGlobalLock) {
6580 final StringWriter sw = new StringWriter();
6581 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6582 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6583 if (reason != null) {
6584 pw.println(" Reason: " + reason);
6585 }
6586 pw.println();
6587 getActivityStartController().dump(pw, " ", null);
6588 pw.println();
6589 pw.println("-------------------------------------------------------------------------------");
6590 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6591 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6592 "" /* header */);
6593 pw.println();
6594 pw.close();
6595
6596 mLastANRState = sw.toString();
6597 }
6598 }
6599
6600 @Override
6601 public void clearSavedANRState() {
6602 synchronized (mGlobalLock) {
6603 mLastANRState = null;
6604 }
6605 }
6606
6607 @Override
6608 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6609 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6610 synchronized (mGlobalLock) {
6611 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6612 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6613 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6614 dumpLastANRLocked(pw);
6615 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6616 dumpLastANRTracesLocked(pw);
6617 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6618 dumpActivityStarterLocked(pw, dumpPackage);
6619 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6620 dumpActivityContainersLocked(pw);
6621 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6622 if (getRecentTasks() != null) {
6623 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6624 }
6625 }
6626 }
6627 }
6628
6629 @Override
6630 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6631 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6632 int wakefulness) {
6633 synchronized (mGlobalLock) {
6634 if (mHomeProcess != null && (dumpPackage == null
6635 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6636 if (needSep) {
6637 pw.println();
6638 needSep = false;
6639 }
6640 pw.println(" mHomeProcess: " + mHomeProcess);
6641 }
6642 if (mPreviousProcess != null && (dumpPackage == null
6643 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6644 if (needSep) {
6645 pw.println();
6646 needSep = false;
6647 }
6648 pw.println(" mPreviousProcess: " + mPreviousProcess);
6649 }
6650 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6651 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6652 StringBuilder sb = new StringBuilder(128);
6653 sb.append(" mPreviousProcessVisibleTime: ");
6654 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6655 pw.println(sb);
6656 }
6657 if (mHeavyWeightProcess != null && (dumpPackage == null
6658 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6659 if (needSep) {
6660 pw.println();
6661 needSep = false;
6662 }
6663 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6664 }
6665 if (dumpPackage == null) {
6666 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006667 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006668 }
6669 if (dumpAll) {
6670 if (dumpPackage == null) {
6671 pw.println(" mConfigWillChange: "
6672 + getTopDisplayFocusedStack().mConfigWillChange);
6673 }
6674 if (mCompatModePackages.getPackages().size() > 0) {
6675 boolean printed = false;
6676 for (Map.Entry<String, Integer> entry
6677 : mCompatModePackages.getPackages().entrySet()) {
6678 String pkg = entry.getKey();
6679 int mode = entry.getValue();
6680 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6681 continue;
6682 }
6683 if (!printed) {
6684 pw.println(" mScreenCompatPackages:");
6685 printed = true;
6686 }
6687 pw.println(" " + pkg + ": " + mode);
6688 }
6689 }
6690 }
6691
6692 if (dumpPackage == null) {
6693 pw.println(" mWakefulness="
6694 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006695 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006696 if (mRunningVoice != null) {
6697 pw.println(" mRunningVoice=" + mRunningVoice);
6698 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6699 }
6700 pw.println(" mSleeping=" + mSleeping);
6701 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6702 pw.println(" mVrController=" + mVrController);
6703 }
6704 if (mCurAppTimeTracker != null) {
6705 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6706 }
6707 if (mAllowAppSwitchUids.size() > 0) {
6708 boolean printed = false;
6709 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6710 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6711 for (int j = 0; j < types.size(); j++) {
6712 if (dumpPackage == null ||
6713 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6714 if (needSep) {
6715 pw.println();
6716 needSep = false;
6717 }
6718 if (!printed) {
6719 pw.println(" mAllowAppSwitchUids:");
6720 printed = true;
6721 }
6722 pw.print(" User ");
6723 pw.print(mAllowAppSwitchUids.keyAt(i));
6724 pw.print(": Type ");
6725 pw.print(types.keyAt(j));
6726 pw.print(" = ");
6727 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6728 pw.println();
6729 }
6730 }
6731 }
6732 }
6733 if (dumpPackage == null) {
6734 if (mController != null) {
6735 pw.println(" mController=" + mController
6736 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6737 }
6738 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6739 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6740 }
6741
6742 return needSep;
6743 }
6744 }
6745
6746 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006747 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6748 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 synchronized (mGlobalLock) {
6750 if (dumpPackage == null) {
6751 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6752 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006753 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6754 if (mRunningVoice != null) {
6755 final long vrToken = proto.start(
6756 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6757 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6758 mRunningVoice.toString());
6759 mVoiceWakeLock.writeToProto(
6760 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6761 proto.end(vrToken);
6762 }
6763 mVrController.writeToProto(proto,
6764 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 if (mController != null) {
6766 final long token = proto.start(CONTROLLER);
6767 proto.write(CONTROLLER, mController.toString());
6768 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6769 proto.end(token);
6770 }
6771 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6772 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6773 }
6774
6775 if (mHomeProcess != null && (dumpPackage == null
6776 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006777 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 }
6779
6780 if (mPreviousProcess != null && (dumpPackage == null
6781 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006782 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6784 }
6785
6786 if (mHeavyWeightProcess != null && (dumpPackage == null
6787 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006788 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 }
6790
6791 for (Map.Entry<String, Integer> entry
6792 : mCompatModePackages.getPackages().entrySet()) {
6793 String pkg = entry.getKey();
6794 int mode = entry.getValue();
6795 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6796 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6797 proto.write(PACKAGE, pkg);
6798 proto.write(MODE, mode);
6799 proto.end(compatToken);
6800 }
6801 }
6802
6803 if (mCurAppTimeTracker != null) {
6804 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6805 }
6806
6807 }
6808 }
6809
6810 @Override
6811 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6812 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6813 boolean dumpFocusedStackOnly) {
6814 synchronized (mGlobalLock) {
6815 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6816 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6817 }
6818 }
6819
6820 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006821 public void dumpForOom(PrintWriter pw) {
6822 synchronized (mGlobalLock) {
6823 pw.println(" mHomeProcess: " + mHomeProcess);
6824 pw.println(" mPreviousProcess: " + mPreviousProcess);
6825 if (mHeavyWeightProcess != null) {
6826 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6827 }
6828 }
6829 }
6830
6831 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 public boolean canGcNow() {
6833 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006834 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835 }
6836 }
6837
6838 @Override
6839 public WindowProcessController getTopApp() {
6840 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006841 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 return top != null ? top.app : null;
6843 }
6844 }
6845
6846 @Override
6847 public void rankTaskLayersIfNeeded() {
6848 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006849 if (mRootActivityContainer != null) {
6850 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 }
6852 }
6853 }
6854
6855 @Override
6856 public void scheduleDestroyAllActivities(String reason) {
6857 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006858 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 }
6860 }
6861
6862 @Override
6863 public void removeUser(int userId) {
6864 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006865 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 }
6867 }
6868
6869 @Override
6870 public boolean switchUser(int userId, UserState userState) {
6871 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006872 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 }
6874 }
6875
6876 @Override
6877 public void onHandleAppCrash(WindowProcessController wpc) {
6878 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006879 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 }
6881 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006882
6883 @Override
6884 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6885 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006886 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006887 }
6888 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006889
6890 @Override
6891 public void onUidActive(int uid, int procState) {
6892 synchronized (mGlobalLock) {
6893 mActiveUids.put(uid, procState);
6894 }
6895 }
6896
6897 @Override
6898 public void onUidInactive(int uid) {
6899 synchronized (mGlobalLock) {
6900 mActiveUids.remove(uid);
6901 }
6902 }
6903
6904 @Override
6905 public void onActiveUidsCleared() {
6906 synchronized (mGlobalLock) {
6907 mActiveUids.clear();
6908 }
6909 }
6910
6911 @Override
6912 public void onUidProcStateChanged(int uid, int procState) {
6913 synchronized (mGlobalLock) {
6914 if (mActiveUids.get(uid) != null) {
6915 mActiveUids.put(uid, procState);
6916 }
6917 }
6918 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006919
6920 @Override
6921 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6922 synchronized (mGlobalLock) {
6923 mPendingTempWhitelist.put(uid, tag);
6924 }
6925 }
6926
6927 @Override
6928 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6929 synchronized (mGlobalLock) {
6930 mPendingTempWhitelist.remove(uid);
6931 }
6932 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006933
6934 @Override
6935 public boolean handleAppCrashInActivityController(String processName, int pid,
6936 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6937 Runnable killCrashingAppCallback) {
6938 synchronized (mGlobalLock) {
6939 if (mController == null) {
6940 return false;
6941 }
6942
6943 try {
6944 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6945 stackTrace)) {
6946 killCrashingAppCallback.run();
6947 return true;
6948 }
6949 } catch (RemoteException e) {
6950 mController = null;
6951 Watchdog.getInstance().setActivityController(null);
6952 }
6953 return false;
6954 }
6955 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006956
6957 @Override
6958 public void removeRecentTasksByPackageName(String packageName, int userId) {
6959 synchronized (mGlobalLock) {
6960 mRecentTasks.removeTasksByPackageName(packageName, userId);
6961 }
6962 }
6963
6964 @Override
6965 public void cleanupRecentTasksForUser(int userId) {
6966 synchronized (mGlobalLock) {
6967 mRecentTasks.cleanupLocked(userId);
6968 }
6969 }
6970
6971 @Override
6972 public void loadRecentTasksForUser(int userId) {
6973 synchronized (mGlobalLock) {
6974 mRecentTasks.loadUserRecentsLocked(userId);
6975 }
6976 }
6977
6978 @Override
6979 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6980 synchronized (mGlobalLock) {
6981 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6982 }
6983 }
6984
6985 @Override
6986 public void flushRecentTasks() {
6987 mRecentTasks.flush();
6988 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006989
6990 @Override
6991 public WindowProcessController getHomeProcess() {
6992 synchronized (mGlobalLock) {
6993 return mHomeProcess;
6994 }
6995 }
6996
6997 @Override
6998 public WindowProcessController getPreviousProcess() {
6999 synchronized (mGlobalLock) {
7000 return mPreviousProcess;
7001 }
7002 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007003
7004 @Override
7005 public void clearLockedTasks(String reason) {
7006 synchronized (mGlobalLock) {
7007 getLockTaskController().clearLockedTasks(reason);
7008 }
7009 }
7010
7011 @Override
7012 public void updateUserConfiguration() {
7013 synchronized (mGlobalLock) {
7014 final Configuration configuration = new Configuration(getGlobalConfiguration());
7015 final int currentUserId = mAmInternal.getCurrentUserId();
7016 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7017 configuration, currentUserId, Settings.System.canWrite(mContext));
7018 updateConfigurationLocked(configuration, null /* starting */,
7019 false /* initLocale */, false /* persistent */, currentUserId,
7020 false /* deferResume */);
7021 }
7022 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007023
7024 @Override
7025 public boolean canShowErrorDialogs() {
7026 synchronized (mGlobalLock) {
7027 return mShowDialogs && !mSleeping && !mShuttingDown
7028 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7029 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7030 mAmInternal.getCurrentUserId())
7031 && !(UserManager.isDeviceInDemoMode(mContext)
7032 && mAmInternal.getCurrentUser().isDemo());
7033 }
7034 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007035
7036 @Override
7037 public void setProfileApp(String profileApp) {
7038 synchronized (mGlobalLock) {
7039 mProfileApp = profileApp;
7040 }
7041 }
7042
7043 @Override
7044 public void setProfileProc(WindowProcessController wpc) {
7045 synchronized (mGlobalLock) {
7046 mProfileProc = wpc;
7047 }
7048 }
7049
7050 @Override
7051 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7052 synchronized (mGlobalLock) {
7053 mProfilerInfo = profilerInfo;
7054 }
7055 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007056
7057 @Override
7058 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7059 synchronized (mGlobalLock) {
7060 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7061 }
7062 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007063
7064 @Override
7065 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7066 synchronized (mGlobalLock) {
7067 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7068 }
7069 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007070
7071 @Override
7072 public boolean isUidForeground(int uid) {
7073 synchronized (mGlobalLock) {
7074 return ActivityTaskManagerService.this.isUidForeground(uid);
7075 }
7076 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007077 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007078}