blob: 09ef4b95e66b2bc961a7e58b3c5f9a91ed3417f7 [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();
Riddle Hsud7088f82019-01-30 13:04:50 +0800352 /**
353 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
354 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
355 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
356 *
357 * @see WindowManagerThreadPriorityBooster
358 */
359 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700360 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800361 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700362 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700363 private UserManagerService mUserManager;
364 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700365 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700366 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
367 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700368 /** All processes currently running that might have a window organized by name. */
369 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700370 /** All processes we currently have running mapped by pid */
371 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700372 /** This is the process holding what we currently consider to be the "home" activity. */
373 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700374 /** The currently running heavy-weight process, if any. */
375 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700376 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /**
378 * This is the process holding the activity the user last visited that is in a different process
379 * from the one they are currently in.
380 */
381 WindowProcessController mPreviousProcess;
382 /** The time at which the previous process was last visible. */
383 long mPreviousProcessVisibleTime;
384
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700385 /** List of intents that were used to start the most recent tasks. */
386 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700387 /** State of external calls telling us if the device is awake or asleep. */
388 private boolean mKeyguardShown = false;
389
390 // Wrapper around VoiceInteractionServiceManager
391 private AssistUtils mAssistUtils;
392
393 // VoiceInteraction session ID that changes for each new request except when
394 // being called for multi-window assist in a single session.
395 private int mViSessionId = 1000;
396
397 // How long to wait in getAssistContextExtras for the activity and foreground services
398 // to respond with the result.
399 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
400
401 // How long top wait when going through the modern assist (which doesn't need to block
402 // on getting this result before starting to launch its UI).
403 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
404
405 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
406 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
407
Alison Cichowlas3e340502018-08-07 17:15:01 -0400408 // Permission tokens are used to temporarily granted a trusted app the ability to call
409 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
410 // showing any appropriate error messages to the user.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
412 10 * MINUTE_IN_MILLIS;
413
414 // How long before the service actually expires a token. This is slightly longer than
415 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
416 // expiration exception.
417 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
418 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
419
420 // How long the service will remember expired tokens, for the purpose of providing error
421 // messaging when a client uses an expired token.
422 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
423 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
424
425 // Activity tokens of system activities that are delegating their call to
426 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
427 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
428
429 // Permission tokens that have expired, but we remember for error reporting.
430 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
431
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700432 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
433
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700434 // Keeps track of the active voice interaction service component, notified from
435 // VoiceInteractionManagerService
436 ComponentName mActiveVoiceInteractionServiceComponent;
437
Wale Ogunwalee2172292018-10-25 10:11:10 -0700438 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439 KeyguardController mKeyguardController;
440 private final ClientLifecycleManager mLifecycleManager;
441 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700442 /** The controller for all operations related to locktask. */
443 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700444 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 boolean mSuppressResizeConfigChanges;
447
448 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
449 new UpdateConfigurationResult();
450
451 static final class UpdateConfigurationResult {
452 // Configuration changes that were updated.
453 int changes;
454 // If the activity was relaunched to match the new configuration.
455 boolean activityRelaunched;
456
457 void reset() {
458 changes = 0;
459 activityRelaunched = false;
460 }
461 }
462
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700463 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700464 private int mConfigurationSeq;
465 // To cache the list of supported system locales
466 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700467
468 /**
469 * Temp object used when global and/or display override configuration is updated. It is also
470 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
471 * anyone...
472 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700473 private Configuration mTempConfig = new Configuration();
474
Wale Ogunwalef6733932018-06-27 05:14:34 -0700475 /** Temporary to avoid allocations. */
476 final StringBuilder mStringBuilder = new StringBuilder(256);
477
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 // Amount of time after a call to stopAppSwitches() during which we will
479 // prevent further untrusted switches from happening.
480 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
481
482 /**
483 * The time at which we will allow normal application switches again,
484 * after a call to {@link #stopAppSwitches()}.
485 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700486 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 /**
488 * This is set to true after the first switch after mAppSwitchesAllowedTime
489 * is set; any switches after that will clear the time.
490 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492
493 IActivityController mController = null;
494 boolean mControllerIsAMonkey = false;
495
Wale Ogunwale214f3482018-10-04 11:00:47 -0700496 final int mFactoryTest;
497
498 /** Used to control how we initialize the service. */
499 ComponentName mTopComponent;
500 String mTopAction = Intent.ACTION_MAIN;
501 String mTopData;
502
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800503 /** Profiling app information. */
504 String mProfileApp = null;
505 WindowProcessController mProfileProc = null;
506 ProfilerInfo mProfilerInfo = null;
507
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700509 * Dump of the activity state at the time of the last ANR. Cleared after
510 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
511 */
512 String mLastANRState;
513
514 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 * Used to retain an update lock when the foreground activity is in
516 * immersive mode.
517 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519
520 /**
521 * Packages that are being allowed to perform unrestricted app switches. Mapping is
522 * User -> Type -> uid.
523 */
524 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
525
526 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700527 private int mThumbnailWidth;
528 private int mThumbnailHeight;
529 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530
531 /**
532 * Flag that indicates if multi-window is enabled.
533 *
534 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
535 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
536 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
537 * At least one of the forms of multi-window must be enabled in order for this flag to be
538 * initialized to 'true'.
539 *
540 * @see #mSupportsSplitScreenMultiWindow
541 * @see #mSupportsFreeformWindowManagement
542 * @see #mSupportsPictureInPicture
543 * @see #mSupportsMultiDisplay
544 */
545 boolean mSupportsMultiWindow;
546 boolean mSupportsSplitScreenMultiWindow;
547 boolean mSupportsFreeformWindowManagement;
548 boolean mSupportsPictureInPicture;
549 boolean mSupportsMultiDisplay;
550 boolean mForceResizableActivities;
551
552 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
553
554 // VR Vr2d Display Id.
555 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700556
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 /**
558 * Set while we are wanting to sleep, to prevent any
559 * activities from being started/resumed.
560 *
561 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
562 *
563 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
564 * while in the sleep state until there is a pending transition out of sleep, in which case
565 * mSleeping is set to false, and remains false while awake.
566 *
567 * Whether mSleeping can quickly toggled between true/false without the device actually
568 * display changing states is undefined.
569 */
570 private boolean mSleeping = false;
571
572 /**
573 * The process state used for processes that are running the top activities.
574 * This changes between TOP and TOP_SLEEPING to following mSleeping.
575 */
576 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
577
578 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
579 // automatically. Important for devices without direct input devices.
580 private boolean mShowDialogs = true;
581
582 /** Set if we are shutting down the system, similar to sleeping. */
583 boolean mShuttingDown = false;
584
585 /**
586 * We want to hold a wake lock while running a voice interaction session, since
587 * this may happen with the screen off and we need to keep the CPU running to
588 * be able to continue to interact with the user.
589 */
590 PowerManager.WakeLock mVoiceWakeLock;
591
592 /**
593 * Set while we are running a voice interaction. This overrides sleeping while it is active.
594 */
595 IVoiceInteractionSession mRunningVoice;
596
597 /**
598 * The last resumed activity. This is identical to the current resumed activity most
599 * of the time but could be different when we're pausing one activity before we resume
600 * another activity.
601 */
602 ActivityRecord mLastResumedActivity;
603
604 /**
605 * The activity that is currently being traced as the active resumed activity.
606 *
607 * @see #updateResumedAppTrace
608 */
609 private @Nullable ActivityRecord mTracedResumedActivity;
610
611 /** If non-null, we are tracking the time the user spends in the currently focused app. */
612 AppTimeTracker mCurAppTimeTracker;
613
Wale Ogunwale008163e2018-07-23 23:11:08 -0700614 private AppWarnings mAppWarnings;
615
Wale Ogunwale53783742018-09-16 10:21:51 -0700616 /**
617 * Packages that the user has asked to have run in screen size
618 * compatibility mode instead of filling the screen.
619 */
620 CompatModePackages mCompatModePackages;
621
Wale Ogunwalef6733932018-06-27 05:14:34 -0700622 private FontScaleSettingObserver mFontScaleSettingObserver;
623
624 private final class FontScaleSettingObserver extends ContentObserver {
625 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
626 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
627
628 public FontScaleSettingObserver() {
629 super(mH);
630 final ContentResolver resolver = mContext.getContentResolver();
631 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
632 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
633 UserHandle.USER_ALL);
634 }
635
636 @Override
637 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
638 if (mFontScaleUri.equals(uri)) {
639 updateFontScaleIfNeeded(userId);
640 } else if (mHideErrorDialogsUri.equals(uri)) {
641 synchronized (mGlobalLock) {
642 updateShouldShowDialogsLocked(getGlobalConfiguration());
643 }
644 }
645 }
646 }
647
Charles Chen8d98dd22018-12-26 17:36:54 +0800648 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
649 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700650 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700651 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700652 mSystemThread = ActivityThread.currentActivityThread();
653 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700654 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800655 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700656 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700657 }
658
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700659 public void onSystemReady() {
660 synchronized (mGlobalLock) {
661 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
662 PackageManager.FEATURE_CANT_SAVE_STATE);
663 mAssistUtils = new AssistUtils(mContext);
664 mVrController.onSystemReady();
665 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700666 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700667 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700668 }
669
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700670 public void onInitPowerManagement() {
671 synchronized (mGlobalLock) {
672 mStackSupervisor.initPowerManagement();
673 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
674 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
675 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
676 mVoiceWakeLock.setReferenceCounted(false);
677 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700678 }
679
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700680 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700681 mFontScaleSettingObserver = new FontScaleSettingObserver();
682 }
683
Wale Ogunwale59507092018-10-29 09:00:30 -0700684 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700685 final boolean freeformWindowManagement =
686 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
687 || Settings.Global.getInt(
688 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
689
690 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
691 final boolean supportsPictureInPicture = supportsMultiWindow &&
692 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
693 final boolean supportsSplitScreenMultiWindow =
694 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
695 final boolean supportsMultiDisplay = mContext.getPackageManager()
696 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700697 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
698 final boolean forceResizable = Settings.Global.getInt(
699 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700700 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700701
702 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900703 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700704
705 final Configuration configuration = new Configuration();
706 Settings.System.getConfiguration(resolver, configuration);
707 if (forceRtl) {
708 // This will take care of setting the correct layout direction flags
709 configuration.setLayoutDirection(configuration.locale);
710 }
711
712 synchronized (mGlobalLock) {
713 mForceResizableActivities = forceResizable;
714 final boolean multiWindowFormEnabled = freeformWindowManagement
715 || supportsSplitScreenMultiWindow
716 || supportsPictureInPicture
717 || supportsMultiDisplay;
718 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
719 mSupportsMultiWindow = true;
720 mSupportsFreeformWindowManagement = freeformWindowManagement;
721 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
722 mSupportsPictureInPicture = supportsPictureInPicture;
723 mSupportsMultiDisplay = supportsMultiDisplay;
724 } else {
725 mSupportsMultiWindow = false;
726 mSupportsFreeformWindowManagement = false;
727 mSupportsSplitScreenMultiWindow = false;
728 mSupportsPictureInPicture = false;
729 mSupportsMultiDisplay = false;
730 }
731 mWindowManager.setForceResizableTasks(mForceResizableActivities);
732 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700733 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
734 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 // This happens before any activities are started, so we can change global configuration
736 // in-place.
737 updateConfigurationLocked(configuration, null, true);
738 final Configuration globalConfig = getGlobalConfiguration();
739 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
740
741 // Load resources only after the current configuration has been set.
742 final Resources res = mContext.getResources();
743 mThumbnailWidth = res.getDimensionPixelSize(
744 com.android.internal.R.dimen.thumbnail_width);
745 mThumbnailHeight = res.getDimensionPixelSize(
746 com.android.internal.R.dimen.thumbnail_height);
747
748 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
749 mFullscreenThumbnailScale = (float) res
750 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
751 (float) globalConfig.screenWidthDp;
752 } else {
753 mFullscreenThumbnailScale = res.getFraction(
754 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
755 }
756 }
757 }
758
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800759 public WindowManagerGlobalLock getGlobalLock() {
760 return mGlobalLock;
761 }
762
Riddle Hsud93a6c42018-11-29 21:50:06 +0800763 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
764 Looper looper) {
765 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700767 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700768 final File systemDir = SystemServiceManager.ensureSystemDir();
769 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
770 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700771 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700772
773 mTempConfig.setToDefaults();
774 mTempConfig.setLocales(LocaleList.getDefault());
775 mConfigurationSeq = mTempConfig.seq = 1;
776 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800777 mRootActivityContainer = new RootActivityContainer(this);
778 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700779
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700780 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700781 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700782 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700783 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700784 mRecentTasks = createRecentTasks();
785 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700786 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700787 mKeyguardController = mStackSupervisor.getKeyguardController();
788 }
789
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700790 public void onActivityManagerInternalAdded() {
791 synchronized (mGlobalLock) {
792 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
793 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
794 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700795 }
796
Yunfan Chen75157d72018-07-27 14:47:21 +0900797 int increaseConfigurationSeqLocked() {
798 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
799 return mConfigurationSeq;
800 }
801
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700802 protected ActivityStackSupervisor createStackSupervisor() {
803 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
804 supervisor.initialize();
805 return supervisor;
806 }
807
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700808 public void setWindowManager(WindowManagerService wm) {
809 synchronized (mGlobalLock) {
810 mWindowManager = wm;
811 mLockTaskController.setWindowManager(wm);
812 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800813 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700814 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700815 }
816
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700817 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
818 synchronized (mGlobalLock) {
819 mUsageStatsInternal = usageStatsManager;
820 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700821 }
822
Wale Ogunwalef6733932018-06-27 05:14:34 -0700823 UserManagerService getUserManager() {
824 if (mUserManager == null) {
825 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
826 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
827 }
828 return mUserManager;
829 }
830
831 AppOpsService getAppOpsService() {
832 if (mAppOpsService == null) {
833 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
834 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
835 }
836 return mAppOpsService;
837 }
838
839 boolean hasUserRestriction(String restriction, int userId) {
840 return getUserManager().hasUserRestriction(restriction, userId);
841 }
842
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700843 protected RecentTasks createRecentTasks() {
844 return new RecentTasks(this, mStackSupervisor);
845 }
846
847 RecentTasks getRecentTasks() {
848 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700849 }
850
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700851 ClientLifecycleManager getLifecycleManager() {
852 return mLifecycleManager;
853 }
854
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700855 ActivityStartController getActivityStartController() {
856 return mActivityStartController;
857 }
858
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700859 TaskChangeNotificationController getTaskChangeNotificationController() {
860 return mTaskChangeNotificationController;
861 }
862
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700863 LockTaskController getLockTaskController() {
864 return mLockTaskController;
865 }
866
Yunfan Chen75157d72018-07-27 14:47:21 +0900867 /**
868 * Return the global configuration used by the process corresponding to the input pid. This is
869 * usually the global configuration with some overrides specific to that process.
870 */
871 Configuration getGlobalConfigurationForCallingPid() {
872 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800873 return getGlobalConfigurationForPid(pid);
874 }
875
876 /**
877 * Return the global configuration used by the process corresponding to the given pid.
878 */
879 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900880 if (pid == MY_PID || pid < 0) {
881 return getGlobalConfiguration();
882 }
883 synchronized (mGlobalLock) {
884 final WindowProcessController app = mPidMap.get(pid);
885 return app != null ? app.getConfiguration() : getGlobalConfiguration();
886 }
887 }
888
889 /**
890 * Return the device configuration info used by the process corresponding to the input pid.
891 * The value is consistent with the global configuration for the process.
892 */
893 @Override
894 public ConfigurationInfo getDeviceConfigurationInfo() {
895 ConfigurationInfo config = new ConfigurationInfo();
896 synchronized (mGlobalLock) {
897 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
898 config.reqTouchScreen = globalConfig.touchscreen;
899 config.reqKeyboardType = globalConfig.keyboard;
900 config.reqNavigation = globalConfig.navigation;
901 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
902 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
903 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
904 }
905 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
906 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
907 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
908 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700909 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900910 }
911 return config;
912 }
913
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700914 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700915 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700916 }
917
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700918 public static final class Lifecycle extends SystemService {
919 private final ActivityTaskManagerService mService;
920
921 public Lifecycle(Context context) {
922 super(context);
923 mService = new ActivityTaskManagerService(context);
924 }
925
926 @Override
927 public void onStart() {
928 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700929 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700930 }
931
Garfield Tan891146c2018-10-09 12:14:00 -0700932 @Override
933 public void onUnlockUser(int userId) {
934 synchronized (mService.getGlobalLock()) {
935 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
936 }
937 }
938
939 @Override
940 public void onCleanupUser(int userId) {
941 synchronized (mService.getGlobalLock()) {
942 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
943 }
944 }
945
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700946 public ActivityTaskManagerService getService() {
947 return mService;
948 }
949 }
950
951 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700952 public final int startActivity(IApplicationThread caller, String callingPackage,
953 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
954 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
955 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
956 resultWho, requestCode, startFlags, profilerInfo, bOptions,
957 UserHandle.getCallingUserId());
958 }
959
960 @Override
961 public final int startActivities(IApplicationThread caller, String callingPackage,
962 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
963 int userId) {
964 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700965 enforceNotIsolatedCaller(reason);
966 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700967 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000968 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
969 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
970 reason, null /* originatingPendingIntent */,
971 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700972 }
973
974 @Override
975 public 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 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
979 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
980 true /*validateIncomingUser*/);
981 }
982
983 int startActivityAsUser(IApplicationThread caller, String callingPackage,
984 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
985 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
986 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700987 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700988
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700989 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700990 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
991
992 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700993 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700994 .setCaller(caller)
995 .setCallingPackage(callingPackage)
996 .setResolvedType(resolvedType)
997 .setResultTo(resultTo)
998 .setResultWho(resultWho)
999 .setRequestCode(requestCode)
1000 .setStartFlags(startFlags)
1001 .setProfilerInfo(profilerInfo)
1002 .setActivityOptions(bOptions)
1003 .setMayWait(userId)
1004 .execute();
1005
1006 }
1007
1008 @Override
1009 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1010 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001011 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1012 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 // Refuse possible leaked file descriptors
1014 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1015 throw new IllegalArgumentException("File descriptors passed in Intent");
1016 }
1017
1018 if (!(target instanceof PendingIntentRecord)) {
1019 throw new IllegalArgumentException("Bad PendingIntent object");
1020 }
1021
1022 PendingIntentRecord pir = (PendingIntentRecord)target;
1023
1024 synchronized (mGlobalLock) {
1025 // If this is coming from the currently resumed activity, it is
1026 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001027 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 if (stack.mResumedActivity != null &&
1029 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001030 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001031 }
1032 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001033 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 }
1036
1037 @Override
1038 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1039 Bundle bOptions) {
1040 // Refuse possible leaked file descriptors
1041 if (intent != null && intent.hasFileDescriptors()) {
1042 throw new IllegalArgumentException("File descriptors passed in Intent");
1043 }
1044 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1045
1046 synchronized (mGlobalLock) {
1047 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1048 if (r == null) {
1049 SafeActivityOptions.abort(options);
1050 return false;
1051 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001052 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001053 // The caller is not running... d'oh!
1054 SafeActivityOptions.abort(options);
1055 return false;
1056 }
1057 intent = new Intent(intent);
1058 // The caller is not allowed to change the data.
1059 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1060 // And we are resetting to find the next component...
1061 intent.setComponent(null);
1062
1063 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1064
1065 ActivityInfo aInfo = null;
1066 try {
1067 List<ResolveInfo> resolves =
1068 AppGlobals.getPackageManager().queryIntentActivities(
1069 intent, r.resolvedType,
1070 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1071 UserHandle.getCallingUserId()).getList();
1072
1073 // Look for the original activity in the list...
1074 final int N = resolves != null ? resolves.size() : 0;
1075 for (int i=0; i<N; i++) {
1076 ResolveInfo rInfo = resolves.get(i);
1077 if (rInfo.activityInfo.packageName.equals(r.packageName)
1078 && rInfo.activityInfo.name.equals(r.info.name)) {
1079 // We found the current one... the next matching is
1080 // after it.
1081 i++;
1082 if (i<N) {
1083 aInfo = resolves.get(i).activityInfo;
1084 }
1085 if (debug) {
1086 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1087 + "/" + r.info.name);
1088 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1089 ? "null" : aInfo.packageName + "/" + aInfo.name));
1090 }
1091 break;
1092 }
1093 }
1094 } catch (RemoteException e) {
1095 }
1096
1097 if (aInfo == null) {
1098 // Nobody who is next!
1099 SafeActivityOptions.abort(options);
1100 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1101 return false;
1102 }
1103
1104 intent.setComponent(new ComponentName(
1105 aInfo.applicationInfo.packageName, aInfo.name));
1106 intent.setFlags(intent.getFlags()&~(
1107 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1108 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1109 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1110 FLAG_ACTIVITY_NEW_TASK));
1111
1112 // Okay now we need to start the new activity, replacing the currently running activity.
1113 // This is a little tricky because we want to start the new one as if the current one is
1114 // finished, but not finish the current one first so that there is no flicker.
1115 // And thus...
1116 final boolean wasFinishing = r.finishing;
1117 r.finishing = true;
1118
1119 // Propagate reply information over to the new activity.
1120 final ActivityRecord resultTo = r.resultTo;
1121 final String resultWho = r.resultWho;
1122 final int requestCode = r.requestCode;
1123 r.resultTo = null;
1124 if (resultTo != null) {
1125 resultTo.removeResultsLocked(r, resultWho, requestCode);
1126 }
1127
1128 final long origId = Binder.clearCallingIdentity();
1129 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001130 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001131 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001132 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001133 .setResolvedType(r.resolvedType)
1134 .setActivityInfo(aInfo)
1135 .setResultTo(resultTo != null ? resultTo.appToken : null)
1136 .setResultWho(resultWho)
1137 .setRequestCode(requestCode)
1138 .setCallingPid(-1)
1139 .setCallingUid(r.launchedFromUid)
1140 .setCallingPackage(r.launchedFromPackage)
1141 .setRealCallingPid(-1)
1142 .setRealCallingUid(r.launchedFromUid)
1143 .setActivityOptions(options)
1144 .execute();
1145 Binder.restoreCallingIdentity(origId);
1146
1147 r.finishing = wasFinishing;
1148 if (res != ActivityManager.START_SUCCESS) {
1149 return false;
1150 }
1151 return true;
1152 }
1153 }
1154
1155 @Override
1156 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1157 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1158 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1159 final WaitResult res = new WaitResult();
1160 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001161 enforceNotIsolatedCaller("startActivityAndWait");
1162 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1163 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001164 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001165 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001166 .setCaller(caller)
1167 .setCallingPackage(callingPackage)
1168 .setResolvedType(resolvedType)
1169 .setResultTo(resultTo)
1170 .setResultWho(resultWho)
1171 .setRequestCode(requestCode)
1172 .setStartFlags(startFlags)
1173 .setActivityOptions(bOptions)
1174 .setMayWait(userId)
1175 .setProfilerInfo(profilerInfo)
1176 .setWaitResult(res)
1177 .execute();
1178 }
1179 return res;
1180 }
1181
1182 @Override
1183 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1184 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1185 int startFlags, Configuration config, Bundle bOptions, int userId) {
1186 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001187 enforceNotIsolatedCaller("startActivityWithConfig");
1188 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1189 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001190 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001191 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 .setCaller(caller)
1193 .setCallingPackage(callingPackage)
1194 .setResolvedType(resolvedType)
1195 .setResultTo(resultTo)
1196 .setResultWho(resultWho)
1197 .setRequestCode(requestCode)
1198 .setStartFlags(startFlags)
1199 .setGlobalConfiguration(config)
1200 .setActivityOptions(bOptions)
1201 .setMayWait(userId)
1202 .execute();
1203 }
1204 }
1205
Alison Cichowlas3e340502018-08-07 17:15:01 -04001206
1207 @Override
1208 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1209 int callingUid = Binder.getCallingUid();
1210 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1211 throw new SecurityException("Only the system process can request a permission token, "
1212 + "received request from uid: " + callingUid);
1213 }
1214 IBinder permissionToken = new Binder();
1215 synchronized (mGlobalLock) {
1216 mStartActivitySources.put(permissionToken, delegatorToken);
1217 }
1218
1219 Message expireMsg = PooledLambda.obtainMessage(
1220 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1221 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1222
1223 Message forgetMsg = PooledLambda.obtainMessage(
1224 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1225 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1226
1227 return permissionToken;
1228 }
1229
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001230 @Override
1231 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1232 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001233 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1234 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001236 // permission grants) as any app that may launch one of your own activities. So we only
1237 // allow this in two cases:
1238 // 1) The caller is an activity that is part of the core framework, and then only when it
1239 // is running as the system.
1240 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1241 // can only be requested by a system activity, which may then delegate this call to
1242 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001243 final ActivityRecord sourceRecord;
1244 final int targetUid;
1245 final String targetPackage;
1246 final boolean isResolver;
1247 synchronized (mGlobalLock) {
1248 if (resultTo == null) {
1249 throw new SecurityException("Must be called from an activity");
1250 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001251 final IBinder sourceToken;
1252 if (permissionToken != null) {
1253 // To even attempt to use a permissionToken, an app must also have this signature
1254 // permission.
1255 mAmInternal.enforceCallingPermission(
1256 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1257 "startActivityAsCaller");
1258 // If called with a permissionToken, we want the sourceRecord from the delegator
1259 // activity that requested this token.
1260 sourceToken = mStartActivitySources.remove(permissionToken);
1261 if (sourceToken == null) {
1262 // Invalid permissionToken, check if it recently expired.
1263 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1264 throw new SecurityException("Called with expired permission token: "
1265 + permissionToken);
1266 } else {
1267 throw new SecurityException("Called with invalid permission token: "
1268 + permissionToken);
1269 }
1270 }
1271 } else {
1272 // This method was called directly by the source.
1273 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001275
Wale Ogunwaled32da472018-11-16 07:19:28 -08001276 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277 if (sourceRecord == null) {
1278 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 }
1280 if (sourceRecord.app == null) {
1281 throw new SecurityException("Called without a process attached to activity");
1282 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283
1284 // Whether called directly or from a delegate, the source activity must be from the
1285 // android package.
1286 if (!sourceRecord.info.packageName.equals("android")) {
1287 throw new SecurityException("Must be called from an activity that is "
1288 + "declared in the android package");
1289 }
1290
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001291 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 // This is still okay, as long as this activity is running under the
1293 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001294 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001295 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001296 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 + " must be system uid or original calling uid "
1298 + sourceRecord.launchedFromUid);
1299 }
1300 }
1301 if (ignoreTargetSecurity) {
1302 if (intent.getComponent() == null) {
1303 throw new SecurityException(
1304 "Component must be specified with ignoreTargetSecurity");
1305 }
1306 if (intent.getSelector() != null) {
1307 throw new SecurityException(
1308 "Selector not allowed with ignoreTargetSecurity");
1309 }
1310 }
1311 targetUid = sourceRecord.launchedFromUid;
1312 targetPackage = sourceRecord.launchedFromPackage;
1313 isResolver = sourceRecord.isResolverOrChildActivity();
1314 }
1315
1316 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001317 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001318 }
1319
1320 // TODO: Switch to user app stacks here.
1321 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001322 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001323 .setCallingUid(targetUid)
1324 .setCallingPackage(targetPackage)
1325 .setResolvedType(resolvedType)
1326 .setResultTo(resultTo)
1327 .setResultWho(resultWho)
1328 .setRequestCode(requestCode)
1329 .setStartFlags(startFlags)
1330 .setActivityOptions(bOptions)
1331 .setMayWait(userId)
1332 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1333 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1334 .execute();
1335 } catch (SecurityException e) {
1336 // XXX need to figure out how to propagate to original app.
1337 // A SecurityException here is generally actually a fault of the original
1338 // calling activity (such as a fairly granting permissions), so propagate it
1339 // back to them.
1340 /*
1341 StringBuilder msg = new StringBuilder();
1342 msg.append("While launching");
1343 msg.append(intent.toString());
1344 msg.append(": ");
1345 msg.append(e.getMessage());
1346 */
1347 throw e;
1348 }
1349 }
1350
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001351 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1352 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1353 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1354 }
1355
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 @Override
1357 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1358 Intent intent, String resolvedType, IVoiceInteractionSession session,
1359 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1360 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001361 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 if (session == null || interactor == null) {
1363 throw new NullPointerException("null session or interactor");
1364 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001365 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(callingUid)
1369 .setCallingPackage(callingPackage)
1370 .setResolvedType(resolvedType)
1371 .setVoiceSession(session)
1372 .setVoiceInteractor(interactor)
1373 .setStartFlags(startFlags)
1374 .setProfilerInfo(profilerInfo)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .execute();
1378 }
1379
1380 @Override
1381 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1382 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001383 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1384 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001386 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 .setCallingUid(callingUid)
1388 .setCallingPackage(callingPackage)
1389 .setResolvedType(resolvedType)
1390 .setActivityOptions(bOptions)
1391 .setMayWait(userId)
1392 .execute();
1393 }
1394
1395 @Override
1396 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1397 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001398 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 final int callingPid = Binder.getCallingPid();
1400 final long origId = Binder.clearCallingIdentity();
1401 try {
1402 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001403 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1404 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405
1406 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001407 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1408 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1410 recentsUid, assistDataReceiver);
1411 }
1412 } finally {
1413 Binder.restoreCallingIdentity(origId);
1414 }
1415 }
1416
1417 @Override
1418 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001419 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 "startActivityFromRecents()");
1421
1422 final int callingPid = Binder.getCallingPid();
1423 final int callingUid = Binder.getCallingUid();
1424 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1425 final long origId = Binder.clearCallingIdentity();
1426 try {
1427 synchronized (mGlobalLock) {
1428 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1429 safeOptions);
1430 }
1431 } finally {
1432 Binder.restoreCallingIdentity(origId);
1433 }
1434 }
1435
1436 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001437 * Public API to check if the client is allowed to start an activity on specified display.
1438 *
1439 * If the target display is private or virtual, some restrictions will apply.
1440 *
1441 * @param displayId Target display id.
1442 * @param intent Intent used to launch the activity.
1443 * @param resolvedType The MIME type of the intent.
1444 * @param userId The id of the user for whom the call is made.
1445 * @return {@code true} if a call to start an activity on the target display should succeed and
1446 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1447 */
1448 @Override
1449 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1450 String resolvedType, int userId) {
1451 final int callingUid = Binder.getCallingUid();
1452 final int callingPid = Binder.getCallingPid();
1453 final long origId = Binder.clearCallingIdentity();
1454
1455 try {
1456 // Collect information about the target of the Intent.
1457 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1458 0 /* startFlags */, null /* profilerInfo */, userId,
1459 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1460 UserHandle.USER_NULL));
1461 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1462
1463 synchronized (mGlobalLock) {
1464 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1465 aInfo);
1466 }
1467 } finally {
1468 Binder.restoreCallingIdentity(origId);
1469 }
1470 }
1471
1472 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 * This is the internal entry point for handling Activity.finish().
1474 *
1475 * @param token The Binder token referencing the Activity we want to finish.
1476 * @param resultCode Result code, if any, from this Activity.
1477 * @param resultData Result data (Intent), if any, from this Activity.
1478 * @param finishTask Whether to finish the task associated with this Activity.
1479 *
1480 * @return Returns true if the activity successfully finished, or false if it is still running.
1481 */
1482 @Override
1483 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1484 int finishTask) {
1485 // Refuse possible leaked file descriptors
1486 if (resultData != null && resultData.hasFileDescriptors()) {
1487 throw new IllegalArgumentException("File descriptors passed in Intent");
1488 }
1489
1490 synchronized (mGlobalLock) {
1491 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1492 if (r == null) {
1493 return true;
1494 }
1495 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001496 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001497 ActivityRecord rootR = tr.getRootActivity();
1498 if (rootR == null) {
1499 Slog.w(TAG, "Finishing task with all activities already finished");
1500 }
1501 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1502 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001503 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 return false;
1505 }
1506
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001507 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1508 // We should consolidate.
1509 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001511 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001512 if (next != null) {
1513 // ask watcher if this is allowed
1514 boolean resumeOK = true;
1515 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001516 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001517 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001518 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 Watchdog.getInstance().setActivityController(null);
1520 }
1521
1522 if (!resumeOK) {
1523 Slog.i(TAG, "Not finishing activity because controller resumed");
1524 return false;
1525 }
1526 }
1527 }
1528 final long origId = Binder.clearCallingIdentity();
1529 try {
1530 boolean res;
1531 final boolean finishWithRootActivity =
1532 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1533 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1534 || (finishWithRootActivity && r == rootR)) {
1535 // If requested, remove the task that is associated to this activity only if it
1536 // was the root activity in the task. The result code and data is ignored
1537 // because we don't support returning them across task boundaries. Also, to
1538 // keep backwards compatibility we remove the task from recents when finishing
1539 // task with root activity.
1540 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1541 finishWithRootActivity, "finish-activity");
1542 if (!res) {
1543 Slog.i(TAG, "Removing task failed to finish activity");
1544 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001545 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001546 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 } else {
1548 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1549 resultData, "app-request", true);
1550 if (!res) {
1551 Slog.i(TAG, "Failed to finish by app-request");
1552 }
1553 }
1554 return res;
1555 } finally {
1556 Binder.restoreCallingIdentity(origId);
1557 }
1558 }
1559 }
1560
1561 @Override
1562 public boolean finishActivityAffinity(IBinder token) {
1563 synchronized (mGlobalLock) {
1564 final long origId = Binder.clearCallingIdentity();
1565 try {
1566 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1567 if (r == null) {
1568 return false;
1569 }
1570
1571 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1572 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001573 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001574 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 return false;
1576 }
1577 return task.getStack().finishActivityAffinityLocked(r);
1578 } finally {
1579 Binder.restoreCallingIdentity(origId);
1580 }
1581 }
1582 }
1583
1584 @Override
1585 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1586 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001587 try {
1588 WindowProcessController proc = null;
1589 synchronized (mGlobalLock) {
1590 ActivityStack stack = ActivityRecord.getStackLocked(token);
1591 if (stack == null) {
1592 return;
1593 }
1594 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1595 false /* fromTimeout */, false /* processPausingActivities */, config);
1596 if (r != null) {
1597 proc = r.app;
1598 }
1599 if (stopProfiling && proc != null) {
1600 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001601 }
1602 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001603 } finally {
1604 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 }
1607
1608 @Override
1609 public final void activityResumed(IBinder token) {
1610 final long origId = Binder.clearCallingIdentity();
1611 synchronized (mGlobalLock) {
1612 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001613 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001614 }
1615 Binder.restoreCallingIdentity(origId);
1616 }
1617
1618 @Override
1619 public final void activityPaused(IBinder token) {
1620 final long origId = Binder.clearCallingIdentity();
1621 synchronized (mGlobalLock) {
1622 ActivityStack stack = ActivityRecord.getStackLocked(token);
1623 if (stack != null) {
1624 stack.activityPausedLocked(token, false);
1625 }
1626 }
1627 Binder.restoreCallingIdentity(origId);
1628 }
1629
1630 @Override
1631 public final void activityStopped(IBinder token, Bundle icicle,
1632 PersistableBundle persistentState, CharSequence description) {
1633 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1634
1635 // Refuse possible leaked file descriptors
1636 if (icicle != null && icicle.hasFileDescriptors()) {
1637 throw new IllegalArgumentException("File descriptors passed in Bundle");
1638 }
1639
1640 final long origId = Binder.clearCallingIdentity();
1641
1642 synchronized (mGlobalLock) {
1643 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1644 if (r != null) {
1645 r.activityStoppedLocked(icicle, persistentState, description);
1646 }
1647 }
1648
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001649 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650
1651 Binder.restoreCallingIdentity(origId);
1652 }
1653
1654 @Override
1655 public final void activityDestroyed(IBinder token) {
1656 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1657 synchronized (mGlobalLock) {
1658 ActivityStack stack = ActivityRecord.getStackLocked(token);
1659 if (stack != null) {
1660 stack.activityDestroyedLocked(token, "activityDestroyed");
1661 }
1662 }
1663 }
1664
1665 @Override
1666 public final void activityRelaunched(IBinder token) {
1667 final long origId = Binder.clearCallingIdentity();
1668 synchronized (mGlobalLock) {
1669 mStackSupervisor.activityRelaunchedLocked(token);
1670 }
1671 Binder.restoreCallingIdentity(origId);
1672 }
1673
1674 public final void activitySlept(IBinder token) {
1675 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1676
1677 final long origId = Binder.clearCallingIdentity();
1678
1679 synchronized (mGlobalLock) {
1680 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1681 if (r != null) {
1682 mStackSupervisor.activitySleptLocked(r);
1683 }
1684 }
1685
1686 Binder.restoreCallingIdentity(origId);
1687 }
1688
1689 @Override
1690 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1691 synchronized (mGlobalLock) {
1692 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1693 if (r == null) {
1694 return;
1695 }
1696 final long origId = Binder.clearCallingIdentity();
1697 try {
1698 r.setRequestedOrientation(requestedOrientation);
1699 } finally {
1700 Binder.restoreCallingIdentity(origId);
1701 }
1702 }
1703 }
1704
1705 @Override
1706 public int getRequestedOrientation(IBinder token) {
1707 synchronized (mGlobalLock) {
1708 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1709 if (r == null) {
1710 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1711 }
1712 return r.getRequestedOrientation();
1713 }
1714 }
1715
1716 @Override
1717 public void setImmersive(IBinder token, boolean immersive) {
1718 synchronized (mGlobalLock) {
1719 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1720 if (r == null) {
1721 throw new IllegalArgumentException();
1722 }
1723 r.immersive = immersive;
1724
1725 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001726 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001727 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001728 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 }
1730 }
1731 }
1732
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001733 void applyUpdateLockStateLocked(ActivityRecord r) {
1734 // Modifications to the UpdateLock state are done on our handler, outside
1735 // the activity manager's locks. The new state is determined based on the
1736 // state *now* of the relevant activity record. The object is passed to
1737 // the handler solely for logging detail, not to be consulted/modified.
1738 final boolean nextState = r != null && r.immersive;
1739 mH.post(() -> {
1740 if (mUpdateLock.isHeld() != nextState) {
1741 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1742 "Applying new update lock state '" + nextState + "' for " + r);
1743 if (nextState) {
1744 mUpdateLock.acquire();
1745 } else {
1746 mUpdateLock.release();
1747 }
1748 }
1749 });
1750 }
1751
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 @Override
1753 public boolean isImmersive(IBinder token) {
1754 synchronized (mGlobalLock) {
1755 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1756 if (r == null) {
1757 throw new IllegalArgumentException();
1758 }
1759 return r.immersive;
1760 }
1761 }
1762
1763 @Override
1764 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001765 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001767 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001768 return (r != null) ? r.immersive : false;
1769 }
1770 }
1771
1772 @Override
1773 public void overridePendingTransition(IBinder token, String packageName,
1774 int enterAnim, int exitAnim) {
1775 synchronized (mGlobalLock) {
1776 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1777 if (self == null) {
1778 return;
1779 }
1780
1781 final long origId = Binder.clearCallingIdentity();
1782
1783 if (self.isState(
1784 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001785 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001786 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
1788
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791 }
1792
1793 @Override
1794 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001795 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001796 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001797 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001798 if (r == null) {
1799 return ActivityManager.COMPAT_MODE_UNKNOWN;
1800 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001801 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 }
1803 }
1804
1805 @Override
1806 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001809 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001811 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001812 if (r == null) {
1813 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1814 return;
1815 }
1816 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001817 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 }
1819 }
1820
1821 @Override
1822 public int getLaunchedFromUid(IBinder activityToken) {
1823 ActivityRecord srec;
1824 synchronized (mGlobalLock) {
1825 srec = ActivityRecord.forTokenLocked(activityToken);
1826 }
1827 if (srec == null) {
1828 return -1;
1829 }
1830 return srec.launchedFromUid;
1831 }
1832
1833 @Override
1834 public String getLaunchedFromPackage(IBinder activityToken) {
1835 ActivityRecord srec;
1836 synchronized (mGlobalLock) {
1837 srec = ActivityRecord.forTokenLocked(activityToken);
1838 }
1839 if (srec == null) {
1840 return null;
1841 }
1842 return srec.launchedFromPackage;
1843 }
1844
1845 @Override
1846 public boolean convertFromTranslucent(IBinder token) {
1847 final long origId = Binder.clearCallingIdentity();
1848 try {
1849 synchronized (mGlobalLock) {
1850 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1851 if (r == null) {
1852 return false;
1853 }
1854 final boolean translucentChanged = r.changeWindowTranslucency(true);
1855 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001856 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001857 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001858 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001859 return translucentChanged;
1860 }
1861 } finally {
1862 Binder.restoreCallingIdentity(origId);
1863 }
1864 }
1865
1866 @Override
1867 public boolean convertToTranslucent(IBinder token, Bundle options) {
1868 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1869 final long origId = Binder.clearCallingIdentity();
1870 try {
1871 synchronized (mGlobalLock) {
1872 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1873 if (r == null) {
1874 return false;
1875 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001876 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 int index = task.mActivities.lastIndexOf(r);
1878 if (index > 0) {
1879 ActivityRecord under = task.mActivities.get(index - 1);
1880 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1881 }
1882 final boolean translucentChanged = r.changeWindowTranslucency(false);
1883 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001884 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001885 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001886 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001887 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 return translucentChanged;
1889 }
1890 } finally {
1891 Binder.restoreCallingIdentity(origId);
1892 }
1893 }
1894
1895 @Override
1896 public void notifyActivityDrawn(IBinder token) {
1897 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1898 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001899 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001901 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 }
1903 }
1904 }
1905
1906 @Override
1907 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1908 synchronized (mGlobalLock) {
1909 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1910 if (r == null) {
1911 return;
1912 }
1913 r.reportFullyDrawnLocked(restoredFromBundle);
1914 }
1915 }
1916
1917 @Override
1918 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1919 synchronized (mGlobalLock) {
1920 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1921 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1922 return stack.mDisplayId;
1923 }
1924 return DEFAULT_DISPLAY;
1925 }
1926 }
1927
1928 @Override
1929 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001930 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 long ident = Binder.clearCallingIdentity();
1932 try {
1933 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001934 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001936 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 }
1938 return null;
1939 }
1940 } finally {
1941 Binder.restoreCallingIdentity(ident);
1942 }
1943 }
1944
1945 @Override
1946 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1949 final long callingId = Binder.clearCallingIdentity();
1950 try {
1951 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001952 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 if (stack == null) {
1954 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1955 return;
1956 }
1957 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001958 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001959 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
1961 }
1962 } finally {
1963 Binder.restoreCallingIdentity(callingId);
1964 }
1965 }
1966
1967 @Override
1968 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001969 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1971 final long callingId = Binder.clearCallingIdentity();
1972 try {
1973 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001974 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001975 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 if (task == null) {
1977 return;
1978 }
1979 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001980 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001981 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983 }
1984 } finally {
1985 Binder.restoreCallingIdentity(callingId);
1986 }
1987 }
1988
1989 @Override
1990 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001991 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 synchronized (mGlobalLock) {
1993 final long ident = Binder.clearCallingIdentity();
1994 try {
1995 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1996 "remove-task");
1997 } finally {
1998 Binder.restoreCallingIdentity(ident);
1999 }
2000 }
2001 }
2002
2003 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002004 public void removeAllVisibleRecentTasks() {
2005 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2006 synchronized (mGlobalLock) {
2007 final long ident = Binder.clearCallingIdentity();
2008 try {
2009 getRecentTasks().removeAllVisibleTasks();
2010 } finally {
2011 Binder.restoreCallingIdentity(ident);
2012 }
2013 }
2014 }
2015
2016 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2018 synchronized (mGlobalLock) {
2019 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2020 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002021 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 }
2023 }
2024 return false;
2025 }
2026
2027 @Override
2028 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2029 Intent resultData) {
2030
2031 synchronized (mGlobalLock) {
2032 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2033 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002034 return r.getActivityStack().navigateUpToLocked(
2035 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002036 }
2037 return false;
2038 }
2039 }
2040
2041 /**
2042 * Attempts to move a task backwards in z-order (the order of activities within the task is
2043 * unchanged).
2044 *
2045 * There are several possible results of this call:
2046 * - if the task is locked, then we will show the lock toast
2047 * - if there is a task behind the provided task, then that task is made visible and resumed as
2048 * this task is moved to the back
2049 * - otherwise, if there are no other tasks in the stack:
2050 * - if this task is in the pinned stack, then we remove the stack completely, which will
2051 * have the effect of moving the task to the top or bottom of the fullscreen stack
2052 * (depending on whether it is visible)
2053 * - otherwise, we simply return home and hide this task
2054 *
2055 * @param token A reference to the activity we wish to move
2056 * @param nonRoot If false then this only works if the activity is the root
2057 * of a task; if true it will work for any activity in a task.
2058 * @return Returns true if the move completed, false if not.
2059 */
2060 @Override
2061 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 synchronized (mGlobalLock) {
2064 final long origId = Binder.clearCallingIdentity();
2065 try {
2066 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002067 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (task != null) {
2069 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2070 }
2071 } finally {
2072 Binder.restoreCallingIdentity(origId);
2073 }
2074 }
2075 return false;
2076 }
2077
2078 @Override
2079 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002080 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 long ident = Binder.clearCallingIdentity();
2082 Rect rect = new Rect();
2083 try {
2084 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002085 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002086 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2087 if (task == null) {
2088 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2089 return rect;
2090 }
2091 if (task.getStack() != null) {
2092 // Return the bounds from window manager since it will be adjusted for various
2093 // things like the presense of a docked stack for tasks that aren't resizeable.
2094 task.getWindowContainerBounds(rect);
2095 } else {
2096 // Task isn't in window manager yet since it isn't associated with a stack.
2097 // Return the persist value from activity manager
2098 if (!task.matchParentBounds()) {
2099 rect.set(task.getBounds());
2100 } else if (task.mLastNonFullscreenBounds != null) {
2101 rect.set(task.mLastNonFullscreenBounds);
2102 }
2103 }
2104 }
2105 } finally {
2106 Binder.restoreCallingIdentity(ident);
2107 }
2108 return rect;
2109 }
2110
2111 @Override
2112 public ActivityManager.TaskDescription getTaskDescription(int id) {
2113 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002114 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002116 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2118 if (tr != null) {
2119 return tr.lastTaskDescription;
2120 }
2121 }
2122 return null;
2123 }
2124
2125 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002126 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2127 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2128 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2129 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2130 return;
2131 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002132 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002133 synchronized (mGlobalLock) {
2134 final long ident = Binder.clearCallingIdentity();
2135 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002136 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002137 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002138 if (task == null) {
2139 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2140 return;
2141 }
2142
2143 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2144 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2145
2146 if (!task.isActivityTypeStandardOrUndefined()) {
2147 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2148 + " non-standard task " + taskId + " to windowing mode="
2149 + windowingMode);
2150 }
2151
2152 final ActivityStack stack = task.getStack();
2153 if (toTop) {
2154 stack.moveToFront("setTaskWindowingMode", task);
2155 }
2156 stack.setWindowingMode(windowingMode);
2157 } finally {
2158 Binder.restoreCallingIdentity(ident);
2159 }
2160 }
2161 }
2162
2163 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 public String getCallingPackage(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.info.packageName : null;
2168 }
2169 }
2170
2171 @Override
2172 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002173 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 ActivityRecord r = getCallingRecordLocked(token);
2175 return r != null ? r.intent.getComponent() : null;
2176 }
2177 }
2178
2179 private ActivityRecord getCallingRecordLocked(IBinder token) {
2180 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2181 if (r == null) {
2182 return null;
2183 }
2184 return r.resultTo;
2185 }
2186
2187 @Override
2188 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002189 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190
2191 synchronized (mGlobalLock) {
2192 final long origId = Binder.clearCallingIdentity();
2193 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002194 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 } finally {
2196 Binder.restoreCallingIdentity(origId);
2197 }
2198 }
2199 }
2200
2201 /**
2202 * TODO: Add mController hook
2203 */
2204 @Override
2205 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002206 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207
2208 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2209 synchronized (mGlobalLock) {
2210 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2211 false /* fromRecents */);
2212 }
2213 }
2214
2215 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2216 boolean fromRecents) {
2217
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002218 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 Binder.getCallingUid(), -1, -1, "Task to front")) {
2220 SafeActivityOptions.abort(options);
2221 return;
2222 }
2223 final long origId = Binder.clearCallingIdentity();
2224 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002225 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 if (task == null) {
2227 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002228 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 return;
2230 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002231 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002233 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002234 return;
2235 }
2236 ActivityOptions realOptions = options != null
2237 ? options.getOptions(mStackSupervisor)
2238 : null;
2239 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2240 false /* forceNonResizable */);
2241
2242 final ActivityRecord topActivity = task.getTopActivity();
2243 if (topActivity != null) {
2244
2245 // We are reshowing a task, use a starting window to hide the initial draw delay
2246 // so the transition can start earlier.
2247 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2248 true /* taskSwitch */, fromRecents);
2249 }
2250 } finally {
2251 Binder.restoreCallingIdentity(origId);
2252 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 }
2254
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002255 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2256 int callingPid, int callingUid, String name) {
2257 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2258 return true;
2259 }
2260
2261 if (getRecentTasks().isCallerRecents(sourceUid)) {
2262 return true;
2263 }
2264
2265 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2266 if (perm == PackageManager.PERMISSION_GRANTED) {
2267 return true;
2268 }
2269 if (checkAllowAppSwitchUid(sourceUid)) {
2270 return true;
2271 }
2272
2273 // If the actual IPC caller is different from the logical source, then
2274 // also see if they are allowed to control app switches.
2275 if (callingUid != -1 && callingUid != sourceUid) {
2276 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2277 if (perm == PackageManager.PERMISSION_GRANTED) {
2278 return true;
2279 }
2280 if (checkAllowAppSwitchUid(callingUid)) {
2281 return true;
2282 }
2283 }
2284
2285 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2286 return false;
2287 }
2288
2289 private boolean checkAllowAppSwitchUid(int uid) {
2290 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2291 if (types != null) {
2292 for (int i = types.size() - 1; i >= 0; i--) {
2293 if (types.valueAt(i).intValue() == uid) {
2294 return true;
2295 }
2296 }
2297 }
2298 return false;
2299 }
2300
2301 @Override
2302 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2303 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2304 "setActivityController()");
2305 synchronized (mGlobalLock) {
2306 mController = controller;
2307 mControllerIsAMonkey = imAMonkey;
2308 Watchdog.getInstance().setActivityController(controller);
2309 }
2310 }
2311
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002312 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002313 synchronized (mGlobalLock) {
2314 return mController != null && mControllerIsAMonkey;
2315 }
2316 }
2317
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002318 @Override
2319 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2320 synchronized (mGlobalLock) {
2321 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2322 }
2323 }
2324
2325 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002326 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2327 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2328 }
2329
2330 @Override
2331 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2332 @WindowConfiguration.ActivityType int ignoreActivityType,
2333 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2334 final int callingUid = Binder.getCallingUid();
2335 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2336
2337 synchronized (mGlobalLock) {
2338 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2339
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002340 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002341 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002342 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002343 ignoreWindowingMode, callingUid, allowed);
2344 }
2345
2346 return list;
2347 }
2348
2349 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2351 synchronized (mGlobalLock) {
2352 final long origId = Binder.clearCallingIdentity();
2353 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2354 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002355 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 }
2357 Binder.restoreCallingIdentity(origId);
2358 }
2359 }
2360
2361 @Override
2362 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002363 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 ActivityStack stack = ActivityRecord.getStackLocked(token);
2365 if (stack != null) {
2366 return stack.willActivityBeVisibleLocked(token);
2367 }
2368 return false;
2369 }
2370 }
2371
2372 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002373 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002375 synchronized (mGlobalLock) {
2376 final long ident = Binder.clearCallingIdentity();
2377 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002378 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 if (task == null) {
2380 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2381 return;
2382 }
2383
2384 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2385 + " to stackId=" + stackId + " toTop=" + toTop);
2386
Wale Ogunwaled32da472018-11-16 07:19:28 -08002387 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002388 if (stack == null) {
2389 throw new IllegalStateException(
2390 "moveTaskToStack: No stack for stackId=" + stackId);
2391 }
2392 if (!stack.isActivityTypeStandardOrUndefined()) {
2393 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2394 + taskId + " to stack " + stackId);
2395 }
2396 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002397 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002398 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2399 }
2400 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2401 "moveTaskToStack");
2402 } finally {
2403 Binder.restoreCallingIdentity(ident);
2404 }
2405 }
2406 }
2407
2408 @Override
2409 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2410 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002411 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002412
2413 final long ident = Binder.clearCallingIdentity();
2414 try {
2415 synchronized (mGlobalLock) {
2416 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002417 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002418 if (stack == null) {
2419 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2420 return;
2421 }
2422 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2423 throw new IllegalArgumentException("Stack: " + stackId
2424 + " doesn't support animated resize.");
2425 }
2426 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2427 animationDuration, false /* fromFullscreen */);
2428 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002429 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002430 if (stack == null) {
2431 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2432 return;
2433 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002434 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002435 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2436 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2437 }
2438 }
2439 } finally {
2440 Binder.restoreCallingIdentity(ident);
2441 }
2442 }
2443
2444 /**
2445 * Moves the specified task to the primary-split-screen stack.
2446 *
2447 * @param taskId Id of task to move.
2448 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2449 * exist already. See
2450 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2451 * and
2452 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2453 * @param toTop If the task and stack should be moved to the top.
2454 * @param animate Whether we should play an animation for the moving the task.
2455 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2456 * stack. Pass {@code null} to use default bounds.
2457 * @param showRecents If the recents activity should be shown on the other side of the task
2458 * going into split-screen mode.
2459 */
2460 @Override
2461 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2462 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002463 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002464 "setTaskWindowingModeSplitScreenPrimary()");
2465 synchronized (mGlobalLock) {
2466 final long ident = Binder.clearCallingIdentity();
2467 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002468 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002469 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002470 if (task == null) {
2471 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2472 return false;
2473 }
2474 if (DEBUG_STACK) Slog.d(TAG_STACK,
2475 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2476 + " to createMode=" + createMode + " toTop=" + toTop);
2477 if (!task.isActivityTypeStandardOrUndefined()) {
2478 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2479 + " non-standard task " + taskId + " to split-screen windowing mode");
2480 }
2481
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002482 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002483 final int windowingMode = task.getWindowingMode();
2484 final ActivityStack stack = task.getStack();
2485 if (toTop) {
2486 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2487 }
2488 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002489 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2490 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002491 return windowingMode != task.getWindowingMode();
2492 } finally {
2493 Binder.restoreCallingIdentity(ident);
2494 }
2495 }
2496 }
2497
2498 /**
2499 * Removes stacks in the input windowing modes from the system if they are of activity type
2500 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2501 */
2502 @Override
2503 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 "removeStacksInWindowingModes()");
2506
2507 synchronized (mGlobalLock) {
2508 final long ident = Binder.clearCallingIdentity();
2509 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002510 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002511 } finally {
2512 Binder.restoreCallingIdentity(ident);
2513 }
2514 }
2515 }
2516
2517 @Override
2518 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002519 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002520 "removeStacksWithActivityTypes()");
2521
2522 synchronized (mGlobalLock) {
2523 final long ident = Binder.clearCallingIdentity();
2524 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002525 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 } finally {
2527 Binder.restoreCallingIdentity(ident);
2528 }
2529 }
2530 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002531
2532 @Override
2533 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2534 int userId) {
2535 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002536 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2537 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002539 final boolean detailed = checkGetTasksPermission(
2540 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2541 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542 == PackageManager.PERMISSION_GRANTED;
2543
2544 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002545 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 callingUid);
2547 }
2548 }
2549
2550 @Override
2551 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002552 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002553 long ident = Binder.clearCallingIdentity();
2554 try {
2555 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002556 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 }
2558 } finally {
2559 Binder.restoreCallingIdentity(ident);
2560 }
2561 }
2562
2563 @Override
2564 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002565 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002566 long ident = Binder.clearCallingIdentity();
2567 try {
2568 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002569 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002570 }
2571 } finally {
2572 Binder.restoreCallingIdentity(ident);
2573 }
2574 }
2575
2576 @Override
2577 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002578 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002579 final long callingUid = Binder.getCallingUid();
2580 final long origId = Binder.clearCallingIdentity();
2581 try {
2582 synchronized (mGlobalLock) {
2583 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002584 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002585 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2586 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2587 }
2588 } finally {
2589 Binder.restoreCallingIdentity(origId);
2590 }
2591 }
2592
2593 @Override
2594 public void startLockTaskModeByToken(IBinder token) {
2595 synchronized (mGlobalLock) {
2596 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2597 if (r == null) {
2598 return;
2599 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002600 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002601 }
2602 }
2603
2604 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002605 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002606 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607 // This makes inner call to look as if it was initiated by system.
2608 long ident = Binder.clearCallingIdentity();
2609 try {
2610 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002611 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002612 MATCH_TASK_IN_STACKS_ONLY);
2613 if (task == null) {
2614 return;
2615 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002616
2617 // When starting lock task mode the stack must be in front and focused
2618 task.getStack().moveToFront("startSystemLockTaskMode");
2619 startLockTaskModeLocked(task, true /* isSystemCaller */);
2620 }
2621 } finally {
2622 Binder.restoreCallingIdentity(ident);
2623 }
2624 }
2625
2626 @Override
2627 public void stopLockTaskModeByToken(IBinder token) {
2628 synchronized (mGlobalLock) {
2629 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2630 if (r == null) {
2631 return;
2632 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002633 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002634 }
2635 }
2636
2637 /**
2638 * This API should be called by SystemUI only when user perform certain action to dismiss
2639 * lock task mode. We should only dismiss pinned lock task mode in this case.
2640 */
2641 @Override
2642 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002643 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002644 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2645 }
2646
2647 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2648 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2649 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2650 return;
2651 }
2652
Wale Ogunwaled32da472018-11-16 07:19:28 -08002653 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 if (stack == null || task != stack.topTask()) {
2655 throw new IllegalArgumentException("Invalid task, not in foreground");
2656 }
2657
2658 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2659 // system or a specific app.
2660 // * System-initiated requests will only start the pinned mode (screen pinning)
2661 // * App-initiated requests
2662 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2663 // - will start the pinned mode, otherwise
2664 final int callingUid = Binder.getCallingUid();
2665 long ident = Binder.clearCallingIdentity();
2666 try {
2667 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002668 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002669
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002670 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002671 } finally {
2672 Binder.restoreCallingIdentity(ident);
2673 }
2674 }
2675
2676 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2677 final int callingUid = Binder.getCallingUid();
2678 long ident = Binder.clearCallingIdentity();
2679 try {
2680 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002681 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 }
2683 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2684 // task and jumping straight into a call in the case of emergency call back.
2685 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2686 if (tm != null) {
2687 tm.showInCallScreen(false);
2688 }
2689 } finally {
2690 Binder.restoreCallingIdentity(ident);
2691 }
2692 }
2693
2694 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002695 public void updateLockTaskPackages(int userId, String[] packages) {
2696 final int callingUid = Binder.getCallingUid();
2697 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2698 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2699 "updateLockTaskPackages()");
2700 }
2701 synchronized (this) {
2702 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2703 + Arrays.toString(packages));
2704 getLockTaskController().updateLockTaskPackages(userId, packages);
2705 }
2706 }
2707
2708 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 public boolean isInLockTaskMode() {
2710 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2711 }
2712
2713 @Override
2714 public int getLockTaskModeState() {
2715 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002716 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002717 }
2718 }
2719
2720 @Override
2721 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2722 synchronized (mGlobalLock) {
2723 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2724 if (r != null) {
2725 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002726 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002727 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002728 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729 }
2730 }
2731 }
2732
2733 @Override
2734 public Bundle getActivityOptions(IBinder token) {
2735 final long origId = Binder.clearCallingIdentity();
2736 try {
2737 synchronized (mGlobalLock) {
2738 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2739 if (r != null) {
2740 final ActivityOptions activityOptions = r.takeOptionsLocked();
2741 return activityOptions == null ? null : activityOptions.toBundle();
2742 }
2743 return null;
2744 }
2745 } finally {
2746 Binder.restoreCallingIdentity(origId);
2747 }
2748 }
2749
2750 @Override
2751 public List<IBinder> getAppTasks(String callingPackage) {
2752 int callingUid = Binder.getCallingUid();
2753 long ident = Binder.clearCallingIdentity();
2754 try {
2755 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002756 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757 }
2758 } finally {
2759 Binder.restoreCallingIdentity(ident);
2760 }
2761 }
2762
2763 @Override
2764 public void finishVoiceTask(IVoiceInteractionSession session) {
2765 synchronized (mGlobalLock) {
2766 final long origId = Binder.clearCallingIdentity();
2767 try {
2768 // TODO: VI Consider treating local voice interactions and voice tasks
2769 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002770 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 } finally {
2772 Binder.restoreCallingIdentity(origId);
2773 }
2774 }
2775
2776 }
2777
2778 @Override
2779 public boolean isTopOfTask(IBinder token) {
2780 synchronized (mGlobalLock) {
2781 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002782 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 }
2784 }
2785
2786 @Override
2787 public void notifyLaunchTaskBehindComplete(IBinder token) {
2788 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2789 }
2790
2791 @Override
2792 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002793 mH.post(() -> {
2794 synchronized (mGlobalLock) {
2795 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002796 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002797 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002798 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002799 } catch (RemoteException e) {
2800 }
2801 }
2802 }
2803
2804 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 }
2806
2807 /** Called from an app when assist data is ready. */
2808 @Override
2809 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2810 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002811 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 synchronized (pae) {
2813 pae.result = extras;
2814 pae.structure = structure;
2815 pae.content = content;
2816 if (referrer != null) {
2817 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2818 }
2819 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002820 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002821 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2822 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 structure.setHomeActivity(pae.isHome);
2824 }
2825 pae.haveResult = true;
2826 pae.notifyAll();
2827 if (pae.intent == null && pae.receiver == null) {
2828 // Caller is just waiting for the result.
2829 return;
2830 }
2831 }
2832 // We are now ready to launch the assist activity.
2833 IAssistDataReceiver sendReceiver = null;
2834 Bundle sendBundle = null;
2835 synchronized (mGlobalLock) {
2836 buildAssistBundleLocked(pae, extras);
2837 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002838 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 if (!exists) {
2840 // Timed out.
2841 return;
2842 }
2843
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002844 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 // Caller wants result sent back to them.
2846 sendBundle = new Bundle();
2847 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2848 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2849 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2850 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2851 }
2852 }
2853 if (sendReceiver != null) {
2854 try {
2855 sendReceiver.onHandleAssistData(sendBundle);
2856 } catch (RemoteException e) {
2857 }
2858 return;
2859 }
2860
2861 final long ident = Binder.clearCallingIdentity();
2862 try {
2863 if (TextUtils.equals(pae.intent.getAction(),
2864 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2865 pae.intent.putExtras(pae.extras);
2866 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2867 } else {
2868 pae.intent.replaceExtras(pae.extras);
2869 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2870 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2871 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002872 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873
2874 try {
2875 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2876 } catch (ActivityNotFoundException e) {
2877 Slog.w(TAG, "No activity to handle assist action.", e);
2878 }
2879 }
2880 } finally {
2881 Binder.restoreCallingIdentity(ident);
2882 }
2883 }
2884
2885 @Override
2886 public int addAppTask(IBinder activityToken, Intent intent,
2887 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2888 final int callingUid = Binder.getCallingUid();
2889 final long callingIdent = Binder.clearCallingIdentity();
2890
2891 try {
2892 synchronized (mGlobalLock) {
2893 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2894 if (r == null) {
2895 throw new IllegalArgumentException("Activity does not exist; token="
2896 + activityToken);
2897 }
2898 ComponentName comp = intent.getComponent();
2899 if (comp == null) {
2900 throw new IllegalArgumentException("Intent " + intent
2901 + " must specify explicit component");
2902 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002903 if (thumbnail.getWidth() != mThumbnailWidth
2904 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002905 throw new IllegalArgumentException("Bad thumbnail size: got "
2906 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002907 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002908 }
2909 if (intent.getSelector() != null) {
2910 intent.setSelector(null);
2911 }
2912 if (intent.getSourceBounds() != null) {
2913 intent.setSourceBounds(null);
2914 }
2915 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2916 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2917 // The caller has added this as an auto-remove task... that makes no
2918 // sense, so turn off auto-remove.
2919 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2920 }
2921 }
2922 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2923 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2924 if (ainfo.applicationInfo.uid != callingUid) {
2925 throw new SecurityException(
2926 "Can't add task for another application: target uid="
2927 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2928 }
2929
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002930 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002932 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002934 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 // The app has too many tasks already and we can't add any more
2936 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2937 return INVALID_TASK_ID;
2938 }
2939 task.lastTaskDescription.copyFrom(description);
2940
2941 // TODO: Send the thumbnail to WM to store it.
2942
2943 return task.taskId;
2944 }
2945 } finally {
2946 Binder.restoreCallingIdentity(callingIdent);
2947 }
2948 }
2949
2950 @Override
2951 public Point getAppTaskThumbnailSize() {
2952 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002953 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 }
2955 }
2956
2957 @Override
2958 public void setTaskResizeable(int taskId, int resizeableMode) {
2959 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002960 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2962 if (task == null) {
2963 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2964 return;
2965 }
2966 task.setResizeMode(resizeableMode);
2967 }
2968 }
2969
2970 @Override
2971 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002972 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 long ident = Binder.clearCallingIdentity();
2974 try {
2975 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002976 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002977 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 if (task == null) {
2979 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2980 return;
2981 }
2982 // Place the task in the right stack if it isn't there already based on
2983 // the requested bounds.
2984 // The stack transition logic is:
2985 // - a null bounds on a freeform task moves that task to fullscreen
2986 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2987 // that task to freeform
2988 // - otherwise the task is not moved
2989 ActivityStack stack = task.getStack();
2990 if (!task.getWindowConfiguration().canResizeTask()) {
2991 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2992 }
2993 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2994 stack = stack.getDisplay().getOrCreateStack(
2995 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2996 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2997 stack = stack.getDisplay().getOrCreateStack(
2998 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2999 }
3000
3001 // Reparent the task to the right stack if necessary
3002 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3003 if (stack != task.getStack()) {
3004 // Defer resume until the task is resized below
3005 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3006 DEFER_RESUME, "resizeTask");
3007 preserveWindow = false;
3008 }
3009
3010 // After reparenting (which only resizes the task to the stack bounds), resize the
3011 // task to the actual bounds provided
3012 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3013 }
3014 } finally {
3015 Binder.restoreCallingIdentity(ident);
3016 }
3017 }
3018
3019 @Override
3020 public boolean releaseActivityInstance(IBinder token) {
3021 synchronized (mGlobalLock) {
3022 final long origId = Binder.clearCallingIdentity();
3023 try {
3024 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3025 if (r == null) {
3026 return false;
3027 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003028 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 } finally {
3030 Binder.restoreCallingIdentity(origId);
3031 }
3032 }
3033 }
3034
3035 @Override
3036 public void releaseSomeActivities(IApplicationThread appInt) {
3037 synchronized (mGlobalLock) {
3038 final long origId = Binder.clearCallingIdentity();
3039 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003040 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003041 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 } finally {
3043 Binder.restoreCallingIdentity(origId);
3044 }
3045 }
3046 }
3047
3048 @Override
3049 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003050 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 != PackageManager.PERMISSION_GRANTED) {
3053 throw new SecurityException("Requires permission "
3054 + android.Manifest.permission.DEVICE_POWER);
3055 }
3056
3057 synchronized (mGlobalLock) {
3058 long ident = Binder.clearCallingIdentity();
3059 if (mKeyguardShown != keyguardShowing) {
3060 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003061 final Message msg = PooledLambda.obtainMessage(
3062 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3063 keyguardShowing);
3064 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 }
3066 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003067 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003068 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 } finally {
3070 Binder.restoreCallingIdentity(ident);
3071 }
3072 }
3073
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 mH.post(() -> {
3075 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3076 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3077 }
3078 });
3079 }
3080
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003081 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003082 mH.post(() -> {
3083 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3084 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3085 }
3086 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087 }
3088
3089 @Override
3090 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003091 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3092 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093
3094 final File passedIconFile = new File(filePath);
3095 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3096 passedIconFile.getName());
3097 if (!legitIconFile.getPath().equals(filePath)
3098 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3099 throw new IllegalArgumentException("Bad file path: " + filePath
3100 + " passed for userId " + userId);
3101 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003102 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 }
3104
3105 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003106 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3108 final ActivityOptions activityOptions = safeOptions != null
3109 ? safeOptions.getOptions(mStackSupervisor)
3110 : null;
3111 if (activityOptions == null
3112 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3113 || activityOptions.getCustomInPlaceResId() == 0) {
3114 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3115 "with valid animation");
3116 }
lumark588a3e82018-07-20 18:53:54 +08003117 // Get top display of front most application.
3118 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3119 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003120 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3121 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3122 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003123 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003124 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003125 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 }
3127
3128 @Override
3129 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003130 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131 synchronized (mGlobalLock) {
3132 final long ident = Binder.clearCallingIdentity();
3133 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003134 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 if (stack == null) {
3136 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3137 return;
3138 }
3139 if (!stack.isActivityTypeStandardOrUndefined()) {
3140 throw new IllegalArgumentException(
3141 "Removing non-standard stack is not allowed.");
3142 }
3143 mStackSupervisor.removeStack(stack);
3144 } finally {
3145 Binder.restoreCallingIdentity(ident);
3146 }
3147 }
3148 }
3149
3150 @Override
3151 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003152 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153
3154 synchronized (mGlobalLock) {
3155 final long ident = Binder.clearCallingIdentity();
3156 try {
3157 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3158 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003159 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 } finally {
3161 Binder.restoreCallingIdentity(ident);
3162 }
3163 }
3164 }
3165
3166 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003167 public void exitFreeformMode(IBinder token) {
3168 synchronized (mGlobalLock) {
3169 long ident = Binder.clearCallingIdentity();
3170 try {
3171 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3172 if (r == null) {
3173 throw new IllegalArgumentException(
3174 "exitFreeformMode: No activity record matching token=" + token);
3175 }
3176
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003177 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 if (stack == null || !stack.inFreeformWindowingMode()) {
3179 throw new IllegalStateException(
3180 "exitFreeformMode: You can only go fullscreen from freeform.");
3181 }
3182
3183 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3184 } finally {
3185 Binder.restoreCallingIdentity(ident);
3186 }
3187 }
3188 }
3189
3190 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3191 @Override
3192 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003193 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003195 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197
3198 /** Unregister a task stack listener so that it stops receiving callbacks. */
3199 @Override
3200 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003201 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003202 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003203 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 }
3205
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 @Override
3207 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3208 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3209 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3210 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3211 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3212 }
3213
3214 @Override
3215 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3216 IBinder activityToken, int flags) {
3217 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3218 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3219 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3220 }
3221
3222 @Override
3223 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3224 Bundle args) {
3225 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3226 true /* focused */, true /* newSessionId */, userHandle, args,
3227 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3228 }
3229
3230 @Override
3231 public Bundle getAssistContextExtras(int requestType) {
3232 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3233 null, null, true /* focused */, true /* newSessionId */,
3234 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3235 if (pae == null) {
3236 return null;
3237 }
3238 synchronized (pae) {
3239 while (!pae.haveResult) {
3240 try {
3241 pae.wait();
3242 } catch (InterruptedException e) {
3243 }
3244 }
3245 }
3246 synchronized (mGlobalLock) {
3247 buildAssistBundleLocked(pae, pae.result);
3248 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003249 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 }
3251 return pae.extras;
3252 }
3253
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003254 /**
3255 * Binder IPC calls go through the public entry point.
3256 * This can be called with or without the global lock held.
3257 */
3258 private static int checkCallingPermission(String permission) {
3259 return checkPermission(
3260 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3261 }
3262
3263 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003264 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003265 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3266 mAmInternal.enforceCallingPermission(permission, func);
3267 }
3268 }
3269
3270 @VisibleForTesting
3271 int checkGetTasksPermission(String permission, int pid, int uid) {
3272 return checkPermission(permission, pid, uid);
3273 }
3274
3275 static int checkPermission(String permission, int pid, int uid) {
3276 if (permission == null) {
3277 return PackageManager.PERMISSION_DENIED;
3278 }
3279 return checkComponentPermission(permission, pid, uid, -1, true);
3280 }
3281
Wale Ogunwale214f3482018-10-04 11:00:47 -07003282 public static int checkComponentPermission(String permission, int pid, int uid,
3283 int owningUid, boolean exported) {
3284 return ActivityManagerService.checkComponentPermission(
3285 permission, pid, uid, owningUid, exported);
3286 }
3287
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003288 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3289 if (getRecentTasks().isCallerRecents(callingUid)) {
3290 // Always allow the recents component to get tasks
3291 return true;
3292 }
3293
3294 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3295 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3296 if (!allowed) {
3297 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3298 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3299 // Temporary compatibility: some existing apps on the system image may
3300 // still be requesting the old permission and not switched to the new
3301 // one; if so, we'll still allow them full access. This means we need
3302 // to see if they are holding the old permission and are a system app.
3303 try {
3304 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3305 allowed = true;
3306 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3307 + " is using old GET_TASKS but privileged; allowing");
3308 }
3309 } catch (RemoteException e) {
3310 }
3311 }
3312 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3313 + " does not hold REAL_GET_TASKS; limiting output");
3314 }
3315 return allowed;
3316 }
3317
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3319 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3320 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3321 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003322 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 "enqueueAssistContext()");
3324
3325 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003326 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 if (activity == null) {
3328 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3329 return null;
3330 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003331 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3333 return null;
3334 }
3335 if (focused) {
3336 if (activityToken != null) {
3337 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3338 if (activity != caller) {
3339 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3340 + " is not current top " + activity);
3341 return null;
3342 }
3343 }
3344 } else {
3345 activity = ActivityRecord.forTokenLocked(activityToken);
3346 if (activity == null) {
3347 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3348 + " couldn't be found");
3349 return null;
3350 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003351 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3353 return null;
3354 }
3355 }
3356
3357 PendingAssistExtras pae;
3358 Bundle extras = new Bundle();
3359 if (args != null) {
3360 extras.putAll(args);
3361 }
3362 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003363 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003364
3365 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3366 userHandle);
3367 pae.isHome = activity.isActivityTypeHome();
3368
3369 // Increment the sessionId if necessary
3370 if (newSessionId) {
3371 mViSessionId++;
3372 }
3373 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003374 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3375 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003376 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003377 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 } catch (RemoteException e) {
3379 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3380 return null;
3381 }
3382 return pae;
3383 }
3384 }
3385
3386 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3387 if (result != null) {
3388 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3389 }
3390 if (pae.hint != null) {
3391 pae.extras.putBoolean(pae.hint, true);
3392 }
3393 }
3394
3395 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3396 IAssistDataReceiver receiver;
3397 synchronized (mGlobalLock) {
3398 mPendingAssistExtras.remove(pae);
3399 receiver = pae.receiver;
3400 }
3401 if (receiver != null) {
3402 // Caller wants result sent back to them.
3403 Bundle sendBundle = new Bundle();
3404 // At least return the receiver extras
3405 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3406 try {
3407 pae.receiver.onHandleAssistData(sendBundle);
3408 } catch (RemoteException e) {
3409 }
3410 }
3411 }
3412
3413 public class PendingAssistExtras extends Binder implements Runnable {
3414 public final ActivityRecord activity;
3415 public boolean isHome;
3416 public final Bundle extras;
3417 public final Intent intent;
3418 public final String hint;
3419 public final IAssistDataReceiver receiver;
3420 public final int userHandle;
3421 public boolean haveResult = false;
3422 public Bundle result = null;
3423 public AssistStructure structure = null;
3424 public AssistContent content = null;
3425 public Bundle receiverExtras;
3426
3427 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3428 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3429 int _userHandle) {
3430 activity = _activity;
3431 extras = _extras;
3432 intent = _intent;
3433 hint = _hint;
3434 receiver = _receiver;
3435 receiverExtras = _receiverExtras;
3436 userHandle = _userHandle;
3437 }
3438
3439 @Override
3440 public void run() {
3441 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3442 synchronized (this) {
3443 haveResult = true;
3444 notifyAll();
3445 }
3446 pendingAssistExtrasTimedOut(this);
3447 }
3448 }
3449
3450 @Override
3451 public boolean isAssistDataAllowedOnCurrentActivity() {
3452 int userId;
3453 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003454 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3456 return false;
3457 }
3458
3459 final ActivityRecord activity = focusedStack.getTopActivity();
3460 if (activity == null) {
3461 return false;
3462 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003463 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 }
3465 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3466 }
3467
3468 @Override
3469 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3470 long ident = Binder.clearCallingIdentity();
3471 try {
3472 synchronized (mGlobalLock) {
3473 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003474 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 if (top != caller) {
3476 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3477 + " is not current top " + top);
3478 return false;
3479 }
3480 if (!top.nowVisible) {
3481 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3482 + " is not visible");
3483 return false;
3484 }
3485 }
3486 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3487 token);
3488 } finally {
3489 Binder.restoreCallingIdentity(ident);
3490 }
3491 }
3492
3493 @Override
3494 public boolean isRootVoiceInteraction(IBinder token) {
3495 synchronized (mGlobalLock) {
3496 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3497 if (r == null) {
3498 return false;
3499 }
3500 return r.rootVoiceInteraction;
3501 }
3502 }
3503
Wale Ogunwalef6733932018-06-27 05:14:34 -07003504 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3505 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3506 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3507 if (activityToCallback == null) return;
3508 activityToCallback.setVoiceSessionLocked(voiceSession);
3509
3510 // Inform the activity
3511 try {
3512 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3513 voiceInteractor);
3514 long token = Binder.clearCallingIdentity();
3515 try {
3516 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3517 } finally {
3518 Binder.restoreCallingIdentity(token);
3519 }
3520 // TODO: VI Should we cache the activity so that it's easier to find later
3521 // rather than scan through all the stacks and activities?
3522 } catch (RemoteException re) {
3523 activityToCallback.clearVoiceSessionLocked();
3524 // TODO: VI Should this terminate the voice session?
3525 }
3526 }
3527
3528 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3529 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3530 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3531 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3532 boolean wasRunningVoice = mRunningVoice != null;
3533 mRunningVoice = session;
3534 if (!wasRunningVoice) {
3535 mVoiceWakeLock.acquire();
3536 updateSleepIfNeededLocked();
3537 }
3538 }
3539 }
3540
3541 void finishRunningVoiceLocked() {
3542 if (mRunningVoice != null) {
3543 mRunningVoice = null;
3544 mVoiceWakeLock.release();
3545 updateSleepIfNeededLocked();
3546 }
3547 }
3548
3549 @Override
3550 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3551 synchronized (mGlobalLock) {
3552 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3553 if (keepAwake) {
3554 mVoiceWakeLock.acquire();
3555 } else {
3556 mVoiceWakeLock.release();
3557 }
3558 }
3559 }
3560 }
3561
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 @Override
3563 public ComponentName getActivityClassForToken(IBinder token) {
3564 synchronized (mGlobalLock) {
3565 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3566 if (r == null) {
3567 return null;
3568 }
3569 return r.intent.getComponent();
3570 }
3571 }
3572
3573 @Override
3574 public String getPackageForToken(IBinder token) {
3575 synchronized (mGlobalLock) {
3576 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3577 if (r == null) {
3578 return null;
3579 }
3580 return r.packageName;
3581 }
3582 }
3583
3584 @Override
3585 public void showLockTaskEscapeMessage(IBinder token) {
3586 synchronized (mGlobalLock) {
3587 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3588 if (r == null) {
3589 return;
3590 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003591 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592 }
3593 }
3594
3595 @Override
3596 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003597 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 final long token = Binder.clearCallingIdentity();
3599 try {
3600 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003601 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003602 }
3603 } finally {
3604 Binder.restoreCallingIdentity(token);
3605 }
3606 }
3607
3608 /**
3609 * Try to place task to provided position. The final position might be different depending on
3610 * current user and stacks state. The task will be moved to target stack if it's currently in
3611 * different stack.
3612 */
3613 @Override
3614 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003615 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003616 synchronized (mGlobalLock) {
3617 long ident = Binder.clearCallingIdentity();
3618 try {
3619 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3620 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003621 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 if (task == null) {
3623 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3624 + taskId);
3625 }
3626
Wale Ogunwaled32da472018-11-16 07:19:28 -08003627 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003628
3629 if (stack == null) {
3630 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3631 + stackId);
3632 }
3633 if (!stack.isActivityTypeStandardOrUndefined()) {
3634 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3635 + " the position of task " + taskId + " in/to non-standard stack");
3636 }
3637
3638 // TODO: Have the callers of this API call a separate reparent method if that is
3639 // what they intended to do vs. having this method also do reparenting.
3640 if (task.getStack() == stack) {
3641 // Change position in current stack.
3642 stack.positionChildAt(task, position);
3643 } else {
3644 // Reparent to new stack.
3645 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3646 !DEFER_RESUME, "positionTaskInStack");
3647 }
3648 } finally {
3649 Binder.restoreCallingIdentity(ident);
3650 }
3651 }
3652 }
3653
3654 @Override
3655 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3656 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3657 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3658 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3659 synchronized (mGlobalLock) {
3660 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3661 if (record == null) {
3662 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3663 + "found for: " + token);
3664 }
3665 record.setSizeConfigurations(horizontalSizeConfiguration,
3666 verticalSizeConfigurations, smallestSizeConfigurations);
3667 }
3668 }
3669
3670 /**
3671 * Dismisses split-screen multi-window mode.
3672 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3673 */
3674 @Override
3675 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003676 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3678 final long ident = Binder.clearCallingIdentity();
3679 try {
3680 synchronized (mGlobalLock) {
3681 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003682 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 if (stack == null) {
3684 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3685 return;
3686 }
3687
3688 if (toTop) {
3689 // Caller wants the current split-screen primary stack to be the top stack after
3690 // it goes fullscreen, so move it to the front.
3691 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003692 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 // In this case the current split-screen primary stack shouldn't be the top
3694 // stack after it goes fullscreen, but it current has focus, so we move the
3695 // focus to the top-most split-screen secondary stack next to it.
3696 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3697 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3698 if (otherStack != null) {
3699 otherStack.moveToFront("dismissSplitScreenMode_other");
3700 }
3701 }
3702
Evan Rosky10475742018-09-05 19:02:48 -07003703 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003704 }
3705 } finally {
3706 Binder.restoreCallingIdentity(ident);
3707 }
3708 }
3709
3710 /**
3711 * Dismisses Pip
3712 * @param animate True if the dismissal should be animated.
3713 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3714 * default animation duration should be used.
3715 */
3716 @Override
3717 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003718 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003719 final long ident = Binder.clearCallingIdentity();
3720 try {
3721 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003722 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003723 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003724 if (stack == null) {
3725 Slog.w(TAG, "dismissPip: pinned stack not found.");
3726 return;
3727 }
3728 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3729 throw new IllegalArgumentException("Stack: " + stack
3730 + " doesn't support animated resize.");
3731 }
3732 if (animate) {
3733 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3734 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3735 } else {
3736 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3737 }
3738 }
3739 } finally {
3740 Binder.restoreCallingIdentity(ident);
3741 }
3742 }
3743
3744 @Override
3745 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003746 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003747 synchronized (mGlobalLock) {
3748 mSuppressResizeConfigChanges = suppress;
3749 }
3750 }
3751
3752 /**
3753 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3754 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3755 * activity and clearing the task at the same time.
3756 */
3757 @Override
3758 // TODO: API should just be about changing windowing modes...
3759 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003761 "moveTasksToFullscreenStack()");
3762 synchronized (mGlobalLock) {
3763 final long origId = Binder.clearCallingIdentity();
3764 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003765 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003766 if (stack != null){
3767 if (!stack.isActivityTypeStandardOrUndefined()) {
3768 throw new IllegalArgumentException(
3769 "You can't move tasks from non-standard stacks.");
3770 }
3771 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3772 }
3773 } finally {
3774 Binder.restoreCallingIdentity(origId);
3775 }
3776 }
3777 }
3778
3779 /**
3780 * Moves the top activity in the input stackId to the pinned stack.
3781 *
3782 * @param stackId Id of stack to move the top activity to pinned stack.
3783 * @param bounds Bounds to use for pinned stack.
3784 *
3785 * @return True if the top activity of the input stack was successfully moved to the pinned
3786 * stack.
3787 */
3788 @Override
3789 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003790 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 "moveTopActivityToPinnedStack()");
3792 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003793 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3795 + "Device doesn't support picture-in-picture mode");
3796 }
3797
3798 long ident = Binder.clearCallingIdentity();
3799 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003800 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801 } finally {
3802 Binder.restoreCallingIdentity(ident);
3803 }
3804 }
3805 }
3806
3807 @Override
3808 public boolean isInMultiWindowMode(IBinder token) {
3809 final long origId = Binder.clearCallingIdentity();
3810 try {
3811 synchronized (mGlobalLock) {
3812 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3813 if (r == null) {
3814 return false;
3815 }
3816 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3817 return r.inMultiWindowMode();
3818 }
3819 } finally {
3820 Binder.restoreCallingIdentity(origId);
3821 }
3822 }
3823
3824 @Override
3825 public boolean isInPictureInPictureMode(IBinder token) {
3826 final long origId = Binder.clearCallingIdentity();
3827 try {
3828 synchronized (mGlobalLock) {
3829 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3830 }
3831 } finally {
3832 Binder.restoreCallingIdentity(origId);
3833 }
3834 }
3835
3836 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003837 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3838 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 return false;
3840 }
3841
3842 // If we are animating to fullscreen then we have already dispatched the PIP mode
3843 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003844 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3845 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003846 }
3847
3848 @Override
3849 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3850 final long origId = Binder.clearCallingIdentity();
3851 try {
3852 synchronized (mGlobalLock) {
3853 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3854 "enterPictureInPictureMode", token, params);
3855
3856 // If the activity is already in picture in picture mode, then just return early
3857 if (isInPictureInPictureMode(r)) {
3858 return true;
3859 }
3860
3861 // Activity supports picture-in-picture, now check that we can enter PiP at this
3862 // point, if it is
3863 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3864 false /* beforeStopping */)) {
3865 return false;
3866 }
3867
3868 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003869 synchronized (mGlobalLock) {
3870 // Only update the saved args from the args that are set
3871 r.pictureInPictureArgs.copyOnlySet(params);
3872 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3873 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3874 // Adjust the source bounds by the insets for the transition down
3875 final Rect sourceBounds = new Rect(
3876 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003877 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003878 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003879 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003880 stack.setPictureInPictureAspectRatio(aspectRatio);
3881 stack.setPictureInPictureActions(actions);
3882 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3883 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3884 logPictureInPictureArgs(params);
3885 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003886 };
3887
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003888 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 // If the keyguard is showing or occluded, then try and dismiss it before
3890 // entering picture-in-picture (this will prompt the user to authenticate if the
3891 // device is currently locked).
3892 dismissKeyguard(token, new KeyguardDismissCallback() {
3893 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003894 public void onDismissSucceeded() {
3895 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 }
3897 }, null /* message */);
3898 } else {
3899 // Enter picture in picture immediately otherwise
3900 enterPipRunnable.run();
3901 }
3902 return true;
3903 }
3904 } finally {
3905 Binder.restoreCallingIdentity(origId);
3906 }
3907 }
3908
3909 @Override
3910 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3911 final long origId = Binder.clearCallingIdentity();
3912 try {
3913 synchronized (mGlobalLock) {
3914 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3915 "setPictureInPictureParams", token, params);
3916
3917 // Only update the saved args from the args that are set
3918 r.pictureInPictureArgs.copyOnlySet(params);
3919 if (r.inPinnedWindowingMode()) {
3920 // If the activity is already in picture-in-picture, update the pinned stack now
3921 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3922 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003923 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 if (!stack.isAnimatingBoundsToFullscreen()) {
3925 stack.setPictureInPictureAspectRatio(
3926 r.pictureInPictureArgs.getAspectRatio());
3927 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3928 }
3929 }
3930 logPictureInPictureArgs(params);
3931 }
3932 } finally {
3933 Binder.restoreCallingIdentity(origId);
3934 }
3935 }
3936
3937 @Override
3938 public int getMaxNumPictureInPictureActions(IBinder token) {
3939 // Currently, this is a static constant, but later, we may change this to be dependent on
3940 // the context of the activity
3941 return 3;
3942 }
3943
3944 private void logPictureInPictureArgs(PictureInPictureParams params) {
3945 if (params.hasSetActions()) {
3946 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3947 params.getActions().size());
3948 }
3949 if (params.hasSetAspectRatio()) {
3950 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3951 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3952 MetricsLogger.action(lm);
3953 }
3954 }
3955
3956 /**
3957 * Checks the state of the system and the activity associated with the given {@param token} to
3958 * verify that picture-in-picture is supported for that activity.
3959 *
3960 * @return the activity record for the given {@param token} if all the checks pass.
3961 */
3962 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3963 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003964 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 throw new IllegalStateException(caller
3966 + ": Device doesn't support picture-in-picture mode.");
3967 }
3968
3969 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3970 if (r == null) {
3971 throw new IllegalStateException(caller
3972 + ": Can't find activity for token=" + token);
3973 }
3974
3975 if (!r.supportsPictureInPicture()) {
3976 throw new IllegalStateException(caller
3977 + ": Current activity does not support picture-in-picture.");
3978 }
3979
3980 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003981 && !mWindowManager.isValidPictureInPictureAspectRatio(
3982 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003983 final float minAspectRatio = mContext.getResources().getFloat(
3984 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3985 final float maxAspectRatio = mContext.getResources().getFloat(
3986 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3987 throw new IllegalArgumentException(String.format(caller
3988 + ": Aspect ratio is too extreme (must be between %f and %f).",
3989 minAspectRatio, maxAspectRatio));
3990 }
3991
3992 // Truncate the number of actions if necessary
3993 params.truncateActions(getMaxNumPictureInPictureActions(token));
3994
3995 return r;
3996 }
3997
3998 @Override
3999 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 synchronized (mGlobalLock) {
4002 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4003 if (r == null) {
4004 throw new IllegalArgumentException("Activity does not exist; token="
4005 + activityToken);
4006 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004007 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 }
4009 }
4010
4011 @Override
4012 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4013 Rect tempDockedTaskInsetBounds,
4014 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004015 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004016 long ident = Binder.clearCallingIdentity();
4017 try {
4018 synchronized (mGlobalLock) {
4019 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4020 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4021 PRESERVE_WINDOWS);
4022 }
4023 } finally {
4024 Binder.restoreCallingIdentity(ident);
4025 }
4026 }
4027
4028 @Override
4029 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 final long ident = Binder.clearCallingIdentity();
4032 try {
4033 synchronized (mGlobalLock) {
4034 mStackSupervisor.setSplitScreenResizing(resizing);
4035 }
4036 } finally {
4037 Binder.restoreCallingIdentity(ident);
4038 }
4039 }
4040
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 /**
4042 * Check that we have the features required for VR-related API calls, and throw an exception if
4043 * not.
4044 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004045 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 if (!mContext.getPackageManager().hasSystemFeature(
4047 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4048 throw new UnsupportedOperationException("VR mode not supported on this device!");
4049 }
4050 }
4051
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 @Override
4053 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004054 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004055
4056 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4057
4058 ActivityRecord r;
4059 synchronized (mGlobalLock) {
4060 r = ActivityRecord.isInStackLocked(token);
4061 }
4062
4063 if (r == null) {
4064 throw new IllegalArgumentException();
4065 }
4066
4067 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004068 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 VrManagerInternal.NO_ERROR) {
4070 return err;
4071 }
4072
4073 // Clear the binder calling uid since this path may call moveToTask().
4074 final long callingId = Binder.clearCallingIdentity();
4075 try {
4076 synchronized (mGlobalLock) {
4077 r.requestedVrComponent = (enabled) ? packageName : null;
4078
4079 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004080 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004081 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 }
4083 return 0;
4084 }
4085 } finally {
4086 Binder.restoreCallingIdentity(callingId);
4087 }
4088 }
4089
4090 @Override
4091 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4092 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4093 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004094 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4096 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4097 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004098 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004099 || activity.voiceSession != null) {
4100 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4101 return;
4102 }
4103 if (activity.pendingVoiceInteractionStart) {
4104 Slog.w(TAG, "Pending start of voice interaction already.");
4105 return;
4106 }
4107 activity.pendingVoiceInteractionStart = true;
4108 }
4109 LocalServices.getService(VoiceInteractionManagerInternal.class)
4110 .startLocalVoiceInteraction(callingActivity, options);
4111 }
4112
4113 @Override
4114 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4115 LocalServices.getService(VoiceInteractionManagerInternal.class)
4116 .stopLocalVoiceInteraction(callingActivity);
4117 }
4118
4119 @Override
4120 public boolean supportsLocalVoiceInteraction() {
4121 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4122 .supportsLocalVoiceInteraction();
4123 }
4124
4125 /** Notifies all listeners when the pinned stack animation starts. */
4126 @Override
4127 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004128 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 }
4130
4131 /** Notifies all listeners when the pinned stack animation ends. */
4132 @Override
4133 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004134 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004135 }
4136
4137 @Override
4138 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004139 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 final long ident = Binder.clearCallingIdentity();
4141 try {
4142 synchronized (mGlobalLock) {
4143 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(ident);
4147 }
4148 }
4149
4150 @Override
4151 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004152 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004153
4154 synchronized (mGlobalLock) {
4155 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004156 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 // Call might come when display is not yet added or has already been removed.
4158 if (DEBUG_CONFIGURATION) {
4159 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4160 + displayId);
4161 }
4162 return false;
4163 }
4164
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004165 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004167 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 }
4169
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004170 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004171 final Message msg = PooledLambda.obtainMessage(
4172 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4173 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175
4176 final long origId = Binder.clearCallingIdentity();
4177 try {
4178 if (values != null) {
4179 Settings.System.clearConfiguration(values);
4180 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004181 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4183 return mTmpUpdateConfigurationResult.changes != 0;
4184 } finally {
4185 Binder.restoreCallingIdentity(origId);
4186 }
4187 }
4188 }
4189
4190 @Override
4191 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193
4194 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004195 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004196 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004197 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198 }
4199
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004200 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004201 final Message msg = PooledLambda.obtainMessage(
4202 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4203 DEFAULT_DISPLAY);
4204 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 }
4206
4207 final long origId = Binder.clearCallingIdentity();
4208 try {
4209 if (values != null) {
4210 Settings.System.clearConfiguration(values);
4211 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004212 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 UserHandle.USER_NULL, false /* deferResume */,
4214 mTmpUpdateConfigurationResult);
4215 return mTmpUpdateConfigurationResult.changes != 0;
4216 } finally {
4217 Binder.restoreCallingIdentity(origId);
4218 }
4219 }
4220 }
4221
4222 @Override
4223 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4224 CharSequence message) {
4225 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004226 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4228 }
4229 final long callingId = Binder.clearCallingIdentity();
4230 try {
4231 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004232 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 }
4234 } finally {
4235 Binder.restoreCallingIdentity(callingId);
4236 }
4237 }
4238
4239 @Override
4240 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004241 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 "cancelTaskWindowTransition()");
4243 final long ident = Binder.clearCallingIdentity();
4244 try {
4245 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004246 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 MATCH_TASK_IN_STACKS_ONLY);
4248 if (task == null) {
4249 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4250 return;
4251 }
4252 task.cancelWindowTransition();
4253 }
4254 } finally {
4255 Binder.restoreCallingIdentity(ident);
4256 }
4257 }
4258
4259 @Override
4260 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 final long ident = Binder.clearCallingIdentity();
4263 try {
4264 final TaskRecord task;
4265 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004266 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004267 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4268 if (task == null) {
4269 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4270 return null;
4271 }
4272 }
4273 // Don't call this while holding the lock as this operation might hit the disk.
4274 return task.getSnapshot(reducedResolution);
4275 } finally {
4276 Binder.restoreCallingIdentity(ident);
4277 }
4278 }
4279
4280 @Override
4281 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4282 synchronized (mGlobalLock) {
4283 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4284 if (r == null) {
4285 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4286 + token);
4287 return;
4288 }
4289 final long origId = Binder.clearCallingIdentity();
4290 try {
4291 r.setDisablePreviewScreenshots(disable);
4292 } finally {
4293 Binder.restoreCallingIdentity(origId);
4294 }
4295 }
4296 }
4297
4298 /** Return the user id of the last resumed activity. */
4299 @Override
4300 public @UserIdInt
4301 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004302 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4304 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004305 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004308 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 }
4310 }
4311
4312 @Override
4313 public void updateLockTaskFeatures(int userId, int flags) {
4314 final int callingUid = Binder.getCallingUid();
4315 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 "updateLockTaskFeatures()");
4318 }
4319 synchronized (mGlobalLock) {
4320 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4321 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004322 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324 }
4325
4326 @Override
4327 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4328 synchronized (mGlobalLock) {
4329 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4330 if (r == null) {
4331 return;
4332 }
4333 final long origId = Binder.clearCallingIdentity();
4334 try {
4335 r.setShowWhenLocked(showWhenLocked);
4336 } finally {
4337 Binder.restoreCallingIdentity(origId);
4338 }
4339 }
4340 }
4341
4342 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004343 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4344 synchronized (mGlobalLock) {
4345 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4346 if (r == null) {
4347 return;
4348 }
4349 final long origId = Binder.clearCallingIdentity();
4350 try {
4351 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4352 } finally {
4353 Binder.restoreCallingIdentity(origId);
4354 }
4355 }
4356 }
4357
4358 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4360 synchronized (mGlobalLock) {
4361 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4362 if (r == null) {
4363 return;
4364 }
4365 final long origId = Binder.clearCallingIdentity();
4366 try {
4367 r.setTurnScreenOn(turnScreenOn);
4368 } finally {
4369 Binder.restoreCallingIdentity(origId);
4370 }
4371 }
4372 }
4373
4374 @Override
4375 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004376 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004377 "registerRemoteAnimations");
4378 definition.setCallingPid(Binder.getCallingPid());
4379 synchronized (mGlobalLock) {
4380 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4381 if (r == null) {
4382 return;
4383 }
4384 final long origId = Binder.clearCallingIdentity();
4385 try {
4386 r.registerRemoteAnimations(definition);
4387 } finally {
4388 Binder.restoreCallingIdentity(origId);
4389 }
4390 }
4391 }
4392
4393 @Override
4394 public void registerRemoteAnimationForNextActivityStart(String packageName,
4395 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004396 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 "registerRemoteAnimationForNextActivityStart");
4398 adapter.setCallingPid(Binder.getCallingPid());
4399 synchronized (mGlobalLock) {
4400 final long origId = Binder.clearCallingIdentity();
4401 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004402 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 packageName, adapter);
4404 } finally {
4405 Binder.restoreCallingIdentity(origId);
4406 }
4407 }
4408 }
4409
Evan Rosky966759f2019-01-15 10:33:58 -08004410 @Override
4411 public void registerRemoteAnimationsForDisplay(int displayId,
4412 RemoteAnimationDefinition definition) {
4413 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4414 "registerRemoteAnimations");
4415 definition.setCallingPid(Binder.getCallingPid());
4416 synchronized (mGlobalLock) {
4417 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4418 if (display == null) {
4419 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4420 return;
4421 }
4422 final long origId = Binder.clearCallingIdentity();
4423 try {
4424 display.mDisplayContent.registerRemoteAnimations(definition);
4425 } finally {
4426 Binder.restoreCallingIdentity(origId);
4427 }
4428 }
4429 }
4430
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4432 @Override
4433 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4434 synchronized (mGlobalLock) {
4435 final long origId = Binder.clearCallingIdentity();
4436 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004437 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 } finally {
4439 Binder.restoreCallingIdentity(origId);
4440 }
4441 }
4442 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004443
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004444 @Override
4445 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004447 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004448 final int pid = Binder.getCallingPid();
4449 final WindowProcessController wpc = mPidMap.get(pid);
4450 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004451 }
4452 }
4453
4454 @Override
4455 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004457 != PERMISSION_GRANTED) {
4458 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4459 + Binder.getCallingPid()
4460 + ", uid=" + Binder.getCallingUid()
4461 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4462 Slog.w(TAG, msg);
4463 throw new SecurityException(msg);
4464 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004466 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004467 final int pid = Binder.getCallingPid();
4468 final WindowProcessController proc = mPidMap.get(pid);
4469 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004470 }
4471 }
4472
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 @Override
4474 public void stopAppSwitches() {
4475 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4476 synchronized (mGlobalLock) {
4477 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4478 mDidAppSwitch = false;
4479 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4480 }
4481 }
4482
4483 @Override
4484 public void resumeAppSwitches() {
4485 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4486 synchronized (mGlobalLock) {
4487 // Note that we don't execute any pending app switches... we will
4488 // let those wait until either the timeout, or the next start
4489 // activity request.
4490 mAppSwitchesAllowedTime = 0;
4491 }
4492 }
4493
4494 void onStartActivitySetDidAppSwitch() {
4495 if (mDidAppSwitch) {
4496 // This is the second allowed switch since we stopped switches, so now just generally
4497 // allow switches. Use case:
4498 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4499 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4500 // anyone to switch again).
4501 mAppSwitchesAllowedTime = 0;
4502 } else {
4503 mDidAppSwitch = true;
4504 }
4505 }
4506
4507 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004508 boolean shouldDisableNonVrUiLocked() {
4509 return mVrController.shouldDisableNonVrUiLocked();
4510 }
4511
Wale Ogunwale53783742018-09-16 10:21:51 -07004512 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004513 // VR apps are expected to run in a main display. If an app is turning on VR for
4514 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4515 // fullscreen stack before enabling VR Mode.
4516 // TODO: The goal of this code is to keep the VR app on the main display. When the
4517 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4518 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4519 // option would be a better choice here.
4520 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4521 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4522 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004523 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004524 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004525 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004526 }
4527 mH.post(() -> {
4528 if (!mVrController.onVrModeChanged(r)) {
4529 return;
4530 }
4531 synchronized (mGlobalLock) {
4532 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4533 mWindowManager.disableNonVrUi(disableNonVrUi);
4534 if (disableNonVrUi) {
4535 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4536 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004537 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004538 }
4539 }
4540 });
4541 }
4542
Wale Ogunwale53783742018-09-16 10:21:51 -07004543 @Override
4544 public int getPackageScreenCompatMode(String packageName) {
4545 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4546 synchronized (mGlobalLock) {
4547 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4548 }
4549 }
4550
4551 @Override
4552 public void setPackageScreenCompatMode(String packageName, int mode) {
4553 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4554 "setPackageScreenCompatMode");
4555 synchronized (mGlobalLock) {
4556 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4557 }
4558 }
4559
4560 @Override
4561 public boolean getPackageAskScreenCompat(String packageName) {
4562 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4563 synchronized (mGlobalLock) {
4564 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4565 }
4566 }
4567
4568 @Override
4569 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4570 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4571 "setPackageAskScreenCompat");
4572 synchronized (mGlobalLock) {
4573 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4574 }
4575 }
4576
Wale Ogunwale64258362018-10-16 15:13:37 -07004577 public static String relaunchReasonToString(int relaunchReason) {
4578 switch (relaunchReason) {
4579 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4580 return "window_resize";
4581 case RELAUNCH_REASON_FREE_RESIZE:
4582 return "free_resize";
4583 default:
4584 return null;
4585 }
4586 }
4587
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004588 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004589 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 }
4591
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004592 /** Pokes the task persister. */
4593 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4594 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4595 }
4596
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004597 boolean isKeyguardLocked() {
4598 return mKeyguardController.isKeyguardLocked();
4599 }
4600
Garfield Tan01548632018-11-27 10:15:48 -08004601 /**
4602 * Clears launch params for the given package.
4603 * @param packageNames the names of the packages of which the launch params are to be cleared
4604 */
4605 @Override
4606 public void clearLaunchParamsForPackages(List<String> packageNames) {
4607 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4608 "clearLaunchParamsForPackages");
4609 synchronized (mGlobalLock) {
4610 for (int i = 0; i < packageNames.size(); ++i) {
4611 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4612 }
4613 }
4614 }
4615
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004616 /**
4617 * Makes the display with the given id a single task instance display. I.e the display can only
4618 * contain one task.
4619 */
4620 @Override
4621 public void setDisplayToSingleTaskInstance(int displayId) {
4622 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4623 "setDisplayToSingleTaskInstance");
4624 final long origId = Binder.clearCallingIdentity();
4625 try {
4626 final ActivityDisplay display =
4627 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4628 if (display != null) {
4629 display.setDisplayToSingleTaskInstance();
4630 }
4631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635
Wale Ogunwale31913b52018-10-13 08:29:31 -07004636 void dumpLastANRLocked(PrintWriter pw) {
4637 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4638 if (mLastANRState == null) {
4639 pw.println(" <no ANR has occurred since boot>");
4640 } else {
4641 pw.println(mLastANRState);
4642 }
4643 }
4644
4645 void dumpLastANRTracesLocked(PrintWriter pw) {
4646 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4647
4648 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4649 if (ArrayUtils.isEmpty(files)) {
4650 pw.println(" <no ANR has occurred since boot>");
4651 return;
4652 }
4653 // Find the latest file.
4654 File latest = null;
4655 for (File f : files) {
4656 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4657 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004658 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004659 }
4660 pw.print("File: ");
4661 pw.print(latest.getName());
4662 pw.println();
4663 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4664 String line;
4665 while ((line = in.readLine()) != null) {
4666 pw.println(line);
4667 }
4668 } catch (IOException e) {
4669 pw.print("Unable to read: ");
4670 pw.print(e);
4671 pw.println();
4672 }
4673 }
4674
4675 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4676 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4677 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4678 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4679 }
4680
4681 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4682 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4683 pw.println(header);
4684
Wale Ogunwaled32da472018-11-16 07:19:28 -08004685 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004686 dumpPackage);
4687 boolean needSep = printedAnything;
4688
4689 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004690 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004691 " ResumedActivity: ");
4692 if (printed) {
4693 printedAnything = true;
4694 needSep = false;
4695 }
4696
4697 if (dumpPackage == null) {
4698 if (needSep) {
4699 pw.println();
4700 }
4701 printedAnything = true;
4702 mStackSupervisor.dump(pw, " ");
4703 }
4704
4705 if (!printedAnything) {
4706 pw.println(" (nothing)");
4707 }
4708 }
4709
4710 void dumpActivityContainersLocked(PrintWriter pw) {
4711 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004712 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004713 pw.println(" ");
4714 }
4715
4716 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4717 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4718 getActivityStartController().dump(pw, "", dumpPackage);
4719 }
4720
4721 /**
4722 * There are three things that cmd can be:
4723 * - a flattened component name that matches an existing activity
4724 * - the cmd arg isn't the flattened component name of an existing activity:
4725 * dump all activity whose component contains the cmd as a substring
4726 * - A hex number of the ActivityRecord object instance.
4727 *
4728 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4729 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4730 */
4731 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4732 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4733 ArrayList<ActivityRecord> activities;
4734
4735 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004736 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004737 dumpFocusedStackOnly);
4738 }
4739
4740 if (activities.size() <= 0) {
4741 return false;
4742 }
4743
4744 String[] newArgs = new String[args.length - opti];
4745 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4746
4747 TaskRecord lastTask = null;
4748 boolean needSep = false;
4749 for (int i = activities.size() - 1; i >= 0; i--) {
4750 ActivityRecord r = activities.get(i);
4751 if (needSep) {
4752 pw.println();
4753 }
4754 needSep = true;
4755 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004756 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004757 if (lastTask != task) {
4758 lastTask = task;
4759 pw.print("TASK "); pw.print(lastTask.affinity);
4760 pw.print(" id="); pw.print(lastTask.taskId);
4761 pw.print(" userId="); pw.println(lastTask.userId);
4762 if (dumpAll) {
4763 lastTask.dump(pw, " ");
4764 }
4765 }
4766 }
4767 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4768 }
4769 return true;
4770 }
4771
4772 /**
4773 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4774 * there is a thread associated with the activity.
4775 */
4776 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4777 final ActivityRecord r, String[] args, boolean dumpAll) {
4778 String innerPrefix = prefix + " ";
4779 synchronized (mGlobalLock) {
4780 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4781 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4782 pw.print(" pid=");
4783 if (r.hasProcess()) pw.println(r.app.getPid());
4784 else pw.println("(not running)");
4785 if (dumpAll) {
4786 r.dump(pw, innerPrefix);
4787 }
4788 }
4789 if (r.attachedToProcess()) {
4790 // flush anything that is already in the PrintWriter since the thread is going
4791 // to write to the file descriptor directly
4792 pw.flush();
4793 try {
4794 TransferPipe tp = new TransferPipe();
4795 try {
4796 r.app.getThread().dumpActivity(tp.getWriteFd(),
4797 r.appToken, innerPrefix, args);
4798 tp.go(fd);
4799 } finally {
4800 tp.kill();
4801 }
4802 } catch (IOException e) {
4803 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4804 } catch (RemoteException e) {
4805 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4806 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004807 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004808 }
4809
sanryhuang498e77e2018-12-06 14:57:01 +08004810 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4811 boolean testPssMode) {
4812 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4813 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4814 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004815 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004816 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4817 st.toString());
4818 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004819 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4820 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4821 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004822 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4823 testPssMode);
4824 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004825 }
4826
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004827 int getCurrentUserId() {
4828 return mAmInternal.getCurrentUserId();
4829 }
4830
4831 private void enforceNotIsolatedCaller(String caller) {
4832 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4833 throw new SecurityException("Isolated process not allowed to call " + caller);
4834 }
4835 }
4836
Wale Ogunwalef6733932018-06-27 05:14:34 -07004837 public Configuration getConfiguration() {
4838 Configuration ci;
4839 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004840 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004841 ci.userSetLocale = false;
4842 }
4843 return ci;
4844 }
4845
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004846 /**
4847 * Current global configuration information. Contains general settings for the entire system,
4848 * also corresponds to the merged configuration of the default display.
4849 */
4850 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004851 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004852 }
4853
4854 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4855 boolean initLocale) {
4856 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4857 }
4858
4859 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4860 boolean initLocale, boolean deferResume) {
4861 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4862 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4863 UserHandle.USER_NULL, deferResume);
4864 }
4865
Wale Ogunwale59507092018-10-29 09:00:30 -07004866 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004867 final long origId = Binder.clearCallingIdentity();
4868 try {
4869 synchronized (mGlobalLock) {
4870 updateConfigurationLocked(values, null, false, true, userId,
4871 false /* deferResume */);
4872 }
4873 } finally {
4874 Binder.restoreCallingIdentity(origId);
4875 }
4876 }
4877
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004878 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4879 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4880 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4881 deferResume, null /* result */);
4882 }
4883
4884 /**
4885 * Do either or both things: (1) change the current configuration, and (2)
4886 * make sure the given activity is running with the (now) current
4887 * configuration. Returns true if the activity has been left running, or
4888 * false if <var>starting</var> is being destroyed to match the new
4889 * configuration.
4890 *
4891 * @param userId is only used when persistent parameter is set to true to persist configuration
4892 * for that particular user
4893 */
4894 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4895 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4896 ActivityTaskManagerService.UpdateConfigurationResult result) {
4897 int changes = 0;
4898 boolean kept = true;
4899
4900 if (mWindowManager != null) {
4901 mWindowManager.deferSurfaceLayout();
4902 }
4903 try {
4904 if (values != null) {
4905 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4906 deferResume);
4907 }
4908
4909 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4910 } finally {
4911 if (mWindowManager != null) {
4912 mWindowManager.continueSurfaceLayout();
4913 }
4914 }
4915
4916 if (result != null) {
4917 result.changes = changes;
4918 result.activityRelaunched = !kept;
4919 }
4920 return kept;
4921 }
4922
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004923 /** Update default (global) configuration and notify listeners about changes. */
4924 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4925 boolean persistent, int userId, boolean deferResume) {
4926 mTempConfig.setTo(getGlobalConfiguration());
4927 final int changes = mTempConfig.updateFrom(values);
4928 if (changes == 0) {
4929 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4930 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4931 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4932 // (even if there are no actual changes) to unfreeze the window.
4933 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4934 return 0;
4935 }
4936
4937 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4938 "Updating global configuration to: " + values);
4939
4940 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4941 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4942 values.colorMode,
4943 values.densityDpi,
4944 values.fontScale,
4945 values.hardKeyboardHidden,
4946 values.keyboard,
4947 values.keyboardHidden,
4948 values.mcc,
4949 values.mnc,
4950 values.navigation,
4951 values.navigationHidden,
4952 values.orientation,
4953 values.screenHeightDp,
4954 values.screenLayout,
4955 values.screenWidthDp,
4956 values.smallestScreenWidthDp,
4957 values.touchscreen,
4958 values.uiMode);
4959
4960
4961 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4962 final LocaleList locales = values.getLocales();
4963 int bestLocaleIndex = 0;
4964 if (locales.size() > 1) {
4965 if (mSupportedSystemLocales == null) {
4966 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4967 }
4968 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4969 }
4970 SystemProperties.set("persist.sys.locale",
4971 locales.get(bestLocaleIndex).toLanguageTag());
4972 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004973
4974 final Message m = PooledLambda.obtainMessage(
4975 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4976 locales.get(bestLocaleIndex));
4977 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004978 }
4979
Yunfan Chen75157d72018-07-27 14:47:21 +09004980 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004981
4982 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004983 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004984
4985 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4986 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004987 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004988
4989 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004990 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004991
4992 AttributeCache ac = AttributeCache.instance();
4993 if (ac != null) {
4994 ac.updateConfiguration(mTempConfig);
4995 }
4996
4997 // Make sure all resources in our process are updated right now, so that anyone who is going
4998 // to retrieve resource values after we return will be sure to get the new ones. This is
4999 // especially important during boot, where the first config change needs to guarantee all
5000 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005001 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005002
5003 // We need another copy of global config because we're scheduling some calls instead of
5004 // running them in place. We need to be sure that object we send will be handled unchanged.
5005 final Configuration configCopy = new Configuration(mTempConfig);
5006 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005007 final Message msg = PooledLambda.obtainMessage(
5008 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5009 this, userId, configCopy);
5010 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005011 }
5012
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005013 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005014 final int pid = mPidMap.keyAt(i);
5015 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005016 if (DEBUG_CONFIGURATION) {
5017 Slog.v(TAG_CONFIGURATION, "Update process config of "
5018 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005019 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005020 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005021 }
5022
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005023 final Message msg = PooledLambda.obtainMessage(
5024 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5025 mAmInternal, changes, initLocale);
5026 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005027
5028 // Override configuration of the default display duplicates global config, so we need to
5029 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005030 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005031 DEFAULT_DISPLAY);
5032
5033 return changes;
5034 }
5035
5036 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5037 boolean deferResume, int displayId) {
5038 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5039 displayId, null /* result */);
5040 }
5041
5042 /**
5043 * Updates override configuration specific for the selected display. If no config is provided,
5044 * new one will be computed in WM based on current display info.
5045 */
5046 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5047 ActivityRecord starting, boolean deferResume, int displayId,
5048 ActivityTaskManagerService.UpdateConfigurationResult result) {
5049 int changes = 0;
5050 boolean kept = true;
5051
5052 if (mWindowManager != null) {
5053 mWindowManager.deferSurfaceLayout();
5054 }
5055 try {
5056 if (values != null) {
5057 if (displayId == DEFAULT_DISPLAY) {
5058 // Override configuration of the default display duplicates global config, so
5059 // we're calling global config update instead for default display. It will also
5060 // apply the correct override config.
5061 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5062 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5063 } else {
5064 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5065 }
5066 }
5067
5068 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5069 } finally {
5070 if (mWindowManager != null) {
5071 mWindowManager.continueSurfaceLayout();
5072 }
5073 }
5074
5075 if (result != null) {
5076 result.changes = changes;
5077 result.activityRelaunched = !kept;
5078 }
5079 return kept;
5080 }
5081
5082 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5083 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005084 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005085 final int changes = mTempConfig.updateFrom(values);
5086 if (changes != 0) {
5087 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5088 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005089 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005090
5091 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5092 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005093 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005094
Wale Ogunwale5c918702018-10-18 11:06:33 -07005095 // Post message to start process to avoid possible deadlock of calling into AMS with
5096 // the ATMS lock held.
5097 final Message msg = PooledLambda.obtainMessage(
5098 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5099 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5100 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005101 }
5102 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005103 return changes;
5104 }
5105
Wale Ogunwalef6733932018-06-27 05:14:34 -07005106 private void updateEventDispatchingLocked(boolean booted) {
5107 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5108 }
5109
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005110 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5111 final ContentResolver resolver = mContext.getContentResolver();
5112 Settings.System.putConfigurationForUser(resolver, config, userId);
5113 }
5114
5115 private void sendLocaleToMountDaemonMsg(Locale l) {
5116 try {
5117 IBinder service = ServiceManager.getService("mount");
5118 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5119 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5120 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5121 } catch (RemoteException e) {
5122 Log.e(TAG, "Error storing locale for decryption UI", e);
5123 }
5124 }
5125
Alison Cichowlas3e340502018-08-07 17:15:01 -04005126 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5127 mStartActivitySources.remove(permissionToken);
5128 mExpiredStartAsCallerTokens.add(permissionToken);
5129 }
5130
5131 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5132 mExpiredStartAsCallerTokens.remove(permissionToken);
5133 }
5134
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005135 boolean isActivityStartsLoggingEnabled() {
5136 return mAmInternal.isActivityStartsLoggingEnabled();
5137 }
5138
Michal Karpinski8596ded2018-11-14 14:43:48 +00005139 boolean isBackgroundActivityStartsEnabled() {
5140 return mAmInternal.isBackgroundActivityStartsEnabled();
5141 }
5142
Wale Ogunwalef6733932018-06-27 05:14:34 -07005143 void enableScreenAfterBoot(boolean booted) {
5144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5145 SystemClock.uptimeMillis());
5146 mWindowManager.enableScreenAfterBoot();
5147
5148 synchronized (mGlobalLock) {
5149 updateEventDispatchingLocked(booted);
5150 }
5151 }
5152
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005153 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5154 if (r == null || !r.hasProcess()) {
5155 return KEY_DISPATCHING_TIMEOUT_MS;
5156 }
5157 return getInputDispatchingTimeoutLocked(r.app);
5158 }
5159
5160 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005161 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005162 }
5163
Wale Ogunwalef6733932018-06-27 05:14:34 -07005164 /**
5165 * Decide based on the configuration whether we should show the ANR,
5166 * crash, etc dialogs. The idea is that if there is no affordance to
5167 * press the on-screen buttons, or the user experience would be more
5168 * greatly impacted than the crash itself, we shouldn't show the dialog.
5169 *
5170 * A thought: SystemUI might also want to get told about this, the Power
5171 * dialog / global actions also might want different behaviors.
5172 */
5173 private void updateShouldShowDialogsLocked(Configuration config) {
5174 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5175 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5176 && config.navigation == Configuration.NAVIGATION_NONAV);
5177 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5178 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5179 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5180 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5181 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5182 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5183 HIDE_ERROR_DIALOGS, 0) != 0;
5184 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5185 }
5186
5187 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5188 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5189 FONT_SCALE, 1.0f, userId);
5190
5191 synchronized (this) {
5192 if (getGlobalConfiguration().fontScale == scaleFactor) {
5193 return;
5194 }
5195
5196 final Configuration configuration
5197 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5198 configuration.fontScale = scaleFactor;
5199 updatePersistentConfiguration(configuration, userId);
5200 }
5201 }
5202
5203 // Actually is sleeping or shutting down or whatever else in the future
5204 // is an inactive state.
5205 boolean isSleepingOrShuttingDownLocked() {
5206 return isSleepingLocked() || mShuttingDown;
5207 }
5208
5209 boolean isSleepingLocked() {
5210 return mSleeping;
5211 }
5212
Riddle Hsu16567132018-08-16 21:37:47 +08005213 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005214 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005215 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005216 if (task.isActivityTypeStandard()) {
5217 if (mCurAppTimeTracker != r.appTimeTracker) {
5218 // We are switching app tracking. Complete the current one.
5219 if (mCurAppTimeTracker != null) {
5220 mCurAppTimeTracker.stop();
5221 mH.obtainMessage(
5222 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005223 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005224 mCurAppTimeTracker = null;
5225 }
5226 if (r.appTimeTracker != null) {
5227 mCurAppTimeTracker = r.appTimeTracker;
5228 startTimeTrackingFocusedActivityLocked();
5229 }
5230 } else {
5231 startTimeTrackingFocusedActivityLocked();
5232 }
5233 } else {
5234 r.appTimeTracker = null;
5235 }
5236 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5237 // TODO: Probably not, because we don't want to resume voice on switching
5238 // back to this activity
5239 if (task.voiceInteractor != null) {
5240 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5241 } else {
5242 finishRunningVoiceLocked();
5243
5244 if (mLastResumedActivity != null) {
5245 final IVoiceInteractionSession session;
5246
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005247 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005248 if (lastResumedActivityTask != null
5249 && lastResumedActivityTask.voiceSession != null) {
5250 session = lastResumedActivityTask.voiceSession;
5251 } else {
5252 session = mLastResumedActivity.voiceSession;
5253 }
5254
5255 if (session != null) {
5256 // We had been in a voice interaction session, but now focused has
5257 // move to something different. Just finish the session, we can't
5258 // return to it and retain the proper state and synchronization with
5259 // the voice interaction service.
5260 finishVoiceTask(session);
5261 }
5262 }
5263 }
5264
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005265 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5266 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005267 }
5268 updateResumedAppTrace(r);
5269 mLastResumedActivity = r;
5270
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005271 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005272
5273 applyUpdateLockStateLocked(r);
5274 applyUpdateVrModeLocked(r);
5275
5276 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005277 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 r == null ? "NULL" : r.shortComponentName,
5279 reason);
5280 }
5281
5282 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5283 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005284 final ActivityTaskManagerInternal.SleepToken token =
5285 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005286 updateSleepIfNeededLocked();
5287 return token;
5288 }
5289 }
5290
5291 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005292 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005293 final boolean wasSleeping = mSleeping;
5294 boolean updateOomAdj = false;
5295
5296 if (!shouldSleep) {
5297 // If wasSleeping is true, we need to wake up activity manager state from when
5298 // we started sleeping. In either case, we need to apply the sleep tokens, which
5299 // will wake up stacks or put them to sleep as appropriate.
5300 if (wasSleeping) {
5301 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005302 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5303 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005304 startTimeTrackingFocusedActivityLocked();
5305 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5306 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5307 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005308 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005309 if (wasSleeping) {
5310 updateOomAdj = true;
5311 }
5312 } else if (!mSleeping && shouldSleep) {
5313 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005314 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5315 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005316 if (mCurAppTimeTracker != null) {
5317 mCurAppTimeTracker.stop();
5318 }
5319 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5320 mStackSupervisor.goingToSleepLocked();
5321 updateResumedAppTrace(null /* resumed */);
5322 updateOomAdj = true;
5323 }
5324 if (updateOomAdj) {
5325 mH.post(mAmInternal::updateOomAdj);
5326 }
5327 }
5328
5329 void updateOomAdj() {
5330 mH.post(mAmInternal::updateOomAdj);
5331 }
5332
Wale Ogunwale53783742018-09-16 10:21:51 -07005333 void updateCpuStats() {
5334 mH.post(mAmInternal::updateCpuStats);
5335 }
5336
Hui Yu03d12402018-12-06 18:00:37 -08005337 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5338 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005339 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5340 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005341 mH.sendMessage(m);
5342 }
5343
Hui Yu03d12402018-12-06 18:00:37 -08005344 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005345 ComponentName taskRoot = null;
5346 final TaskRecord task = activity.getTaskRecord();
5347 if (task != null) {
5348 final ActivityRecord rootActivity = task.getRootActivity();
5349 if (rootActivity != null) {
5350 taskRoot = rootActivity.mActivityComponent;
5351 }
5352 }
5353
Hui Yu03d12402018-12-06 18:00:37 -08005354 final Message m = PooledLambda.obtainMessage(
5355 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005356 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005357 mH.sendMessage(m);
5358 }
5359
Wale Ogunwale53783742018-09-16 10:21:51 -07005360 void setBooting(boolean booting) {
5361 mAmInternal.setBooting(booting);
5362 }
5363
5364 boolean isBooting() {
5365 return mAmInternal.isBooting();
5366 }
5367
5368 void setBooted(boolean booted) {
5369 mAmInternal.setBooted(booted);
5370 }
5371
5372 boolean isBooted() {
5373 return mAmInternal.isBooted();
5374 }
5375
5376 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5377 mH.post(() -> {
5378 if (finishBooting) {
5379 mAmInternal.finishBooting();
5380 }
5381 if (enableScreen) {
5382 mInternal.enableScreenAfterBoot(isBooted());
5383 }
5384 });
5385 }
5386
5387 void setHeavyWeightProcess(ActivityRecord root) {
5388 mHeavyWeightProcess = root.app;
5389 final Message m = PooledLambda.obtainMessage(
5390 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005391 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005392 mH.sendMessage(m);
5393 }
5394
5395 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5396 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5397 return;
5398 }
5399
5400 mHeavyWeightProcess = null;
5401 final Message m = PooledLambda.obtainMessage(
5402 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5403 proc.mUserId);
5404 mH.sendMessage(m);
5405 }
5406
5407 private void cancelHeavyWeightProcessNotification(int userId) {
5408 final INotificationManager inm = NotificationManager.getService();
5409 if (inm == null) {
5410 return;
5411 }
5412 try {
5413 inm.cancelNotificationWithTag("android", null,
5414 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5415 } catch (RuntimeException e) {
5416 Slog.w(TAG, "Error canceling notification for service", e);
5417 } catch (RemoteException e) {
5418 }
5419
5420 }
5421
5422 private void postHeavyWeightProcessNotification(
5423 WindowProcessController proc, Intent intent, int userId) {
5424 if (proc == null) {
5425 return;
5426 }
5427
5428 final INotificationManager inm = NotificationManager.getService();
5429 if (inm == null) {
5430 return;
5431 }
5432
5433 try {
5434 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5435 String text = mContext.getString(R.string.heavy_weight_notification,
5436 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5437 Notification notification =
5438 new Notification.Builder(context,
5439 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5440 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5441 .setWhen(0)
5442 .setOngoing(true)
5443 .setTicker(text)
5444 .setColor(mContext.getColor(
5445 com.android.internal.R.color.system_notification_accent_color))
5446 .setContentTitle(text)
5447 .setContentText(
5448 mContext.getText(R.string.heavy_weight_notification_detail))
5449 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5450 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5451 new UserHandle(userId)))
5452 .build();
5453 try {
5454 inm.enqueueNotificationWithTag("android", "android", null,
5455 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5456 } catch (RuntimeException e) {
5457 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5458 } catch (RemoteException e) {
5459 }
5460 } catch (PackageManager.NameNotFoundException e) {
5461 Slog.w(TAG, "Unable to create context for heavy notification", e);
5462 }
5463
5464 }
5465
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005466 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5467 IBinder token, String resultWho, int requestCode, Intent[] intents,
5468 String[] resolvedTypes, int flags, Bundle bOptions) {
5469
5470 ActivityRecord activity = null;
5471 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5472 activity = ActivityRecord.isInStackLocked(token);
5473 if (activity == null) {
5474 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5475 return null;
5476 }
5477 if (activity.finishing) {
5478 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5479 return null;
5480 }
5481 }
5482
5483 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5484 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5485 bOptions);
5486 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5487 if (noCreate) {
5488 return rec;
5489 }
5490 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5491 if (activity.pendingResults == null) {
5492 activity.pendingResults = new HashSet<>();
5493 }
5494 activity.pendingResults.add(rec.ref);
5495 }
5496 return rec;
5497 }
5498
Andrii Kulian52d255c2018-07-13 11:32:19 -07005499 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005501 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005502 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5503 mCurAppTimeTracker.start(resumedActivity.packageName);
5504 }
5505 }
5506
5507 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5508 if (mTracedResumedActivity != null) {
5509 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5510 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5511 }
5512 if (resumed != null) {
5513 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5514 constructResumedTraceName(resumed.packageName), 0);
5515 }
5516 mTracedResumedActivity = resumed;
5517 }
5518
5519 private String constructResumedTraceName(String packageName) {
5520 return "focused app: " + packageName;
5521 }
5522
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005523 /** Applies latest configuration and/or visibility updates if needed. */
5524 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5525 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005526 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005527 // mainStack is null during startup.
5528 if (mainStack != null) {
5529 if (changes != 0 && starting == null) {
5530 // If the configuration changed, and the caller is not already
5531 // in the process of starting an activity, then find the top
5532 // activity to check if its configuration needs to change.
5533 starting = mainStack.topRunningActivityLocked();
5534 }
5535
5536 if (starting != null) {
5537 kept = starting.ensureActivityConfiguration(changes,
5538 false /* preserveWindow */);
5539 // And we need to make sure at this point that all other activities
5540 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005541 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005542 !PRESERVE_WINDOWS);
5543 }
5544 }
5545
5546 return kept;
5547 }
5548
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005549 void scheduleAppGcsLocked() {
5550 mH.post(() -> mAmInternal.scheduleAppGcs());
5551 }
5552
Wale Ogunwale53783742018-09-16 10:21:51 -07005553 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5554 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5555 }
5556
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005557 /**
5558 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5559 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5560 * on demand.
5561 */
5562 IPackageManager getPackageManager() {
5563 return AppGlobals.getPackageManager();
5564 }
5565
5566 PackageManagerInternal getPackageManagerInternalLocked() {
5567 if (mPmInternal == null) {
5568 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5569 }
5570 return mPmInternal;
5571 }
5572
Wale Ogunwale008163e2018-07-23 23:11:08 -07005573 AppWarnings getAppWarningsLocked() {
5574 return mAppWarnings;
5575 }
5576
Wale Ogunwale214f3482018-10-04 11:00:47 -07005577 Intent getHomeIntent() {
5578 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5579 intent.setComponent(mTopComponent);
5580 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5581 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5582 intent.addCategory(Intent.CATEGORY_HOME);
5583 }
5584 return intent;
5585 }
5586
Chilun2ef71f72018-11-16 17:57:15 +08005587 /**
5588 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5589 * activities.
5590 *
5591 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5592 * component defined in config_secondaryHomeComponent.
5593 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5594 */
5595 Intent getSecondaryHomeIntent(String preferredPackage) {
5596 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5597 if (preferredPackage == null) {
5598 // Using the component stored in config if no package name.
5599 final String secondaryHomeComponent = mContext.getResources().getString(
5600 com.android.internal.R.string.config_secondaryHomeComponent);
5601 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5602 } else {
5603 intent.setPackage(preferredPackage);
5604 }
5605 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5606 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5607 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5608 }
5609 return intent;
5610 }
5611
Wale Ogunwale214f3482018-10-04 11:00:47 -07005612 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5613 if (info == null) return null;
5614 ApplicationInfo newInfo = new ApplicationInfo(info);
5615 newInfo.initForUser(userId);
5616 return newInfo;
5617 }
5618
Wale Ogunwale9c103022018-10-18 07:44:54 -07005619 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005620 if (uid == SYSTEM_UID) {
5621 // The system gets to run in any process. If there are multiple processes with the same
5622 // uid, just pick the first (this should never happen).
5623 final SparseArray<WindowProcessController> procs =
5624 mProcessNames.getMap().get(processName);
5625 if (procs == null) return null;
5626 final int procCount = procs.size();
5627 for (int i = 0; i < procCount; i++) {
5628 final int procUid = procs.keyAt(i);
5629 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5630 // Don't use an app process or different user process for system component.
5631 continue;
5632 }
5633 return procs.valueAt(i);
5634 }
5635 }
5636
5637 return mProcessNames.get(processName, uid);
5638 }
5639
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005640 WindowProcessController getProcessController(IApplicationThread thread) {
5641 if (thread == null) {
5642 return null;
5643 }
5644
5645 final IBinder threadBinder = thread.asBinder();
5646 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5647 for (int i = pmap.size()-1; i >= 0; i--) {
5648 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5649 for (int j = procs.size() - 1; j >= 0; j--) {
5650 final WindowProcessController proc = procs.valueAt(j);
5651 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5652 return proc;
5653 }
5654 }
5655 }
5656
5657 return null;
5658 }
5659
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005660 int getUidStateLocked(int uid) {
5661 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5662 }
5663
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005664 boolean isUidForeground(int uid) {
5665 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5666 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5667 }
5668
Wale Ogunwale9de19442018-10-18 19:05:03 -07005669 /**
5670 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5671 * the whitelist
5672 */
5673 String getPendingTempWhitelistTagForUidLocked(int uid) {
5674 return mPendingTempWhitelist.get(uid);
5675 }
5676
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005677 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5678 if (true || Build.IS_USER) {
5679 return;
5680 }
5681
5682 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5683 StrictMode.allowThreadDiskWrites();
5684 try {
5685 File tracesDir = new File("/data/anr");
5686 File tracesFile = null;
5687 try {
5688 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5689
5690 StringBuilder sb = new StringBuilder();
5691 Time tobj = new Time();
5692 tobj.set(System.currentTimeMillis());
5693 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5694 sb.append(": ");
5695 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5696 sb.append(" since ");
5697 sb.append(msg);
5698 FileOutputStream fos = new FileOutputStream(tracesFile);
5699 fos.write(sb.toString().getBytes());
5700 if (app == null) {
5701 fos.write("\n*** No application process!".getBytes());
5702 }
5703 fos.close();
5704 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5705 } catch (IOException e) {
5706 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5707 return;
5708 }
5709
5710 if (app != null && app.getPid() > 0) {
5711 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5712 firstPids.add(app.getPid());
5713 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5714 }
5715
5716 File lastTracesFile = null;
5717 File curTracesFile = null;
5718 for (int i=9; i>=0; i--) {
5719 String name = String.format(Locale.US, "slow%02d.txt", i);
5720 curTracesFile = new File(tracesDir, name);
5721 if (curTracesFile.exists()) {
5722 if (lastTracesFile != null) {
5723 curTracesFile.renameTo(lastTracesFile);
5724 } else {
5725 curTracesFile.delete();
5726 }
5727 }
5728 lastTracesFile = curTracesFile;
5729 }
5730 tracesFile.renameTo(curTracesFile);
5731 } finally {
5732 StrictMode.setThreadPolicy(oldPolicy);
5733 }
5734 }
5735
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005736 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005737 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005738
5739
Wale Ogunwale98875612018-10-12 07:53:02 -07005740 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5741 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005742
Riddle Hsud93a6c42018-11-29 21:50:06 +08005743 H(Looper looper) {
5744 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005745 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005746
5747 @Override
5748 public void handleMessage(Message msg) {
5749 switch (msg.what) {
5750 case REPORT_TIME_TRACKER_MSG: {
5751 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5752 tracker.deliverResult(mContext);
5753 } break;
5754 }
5755 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005756 }
5757
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005758 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005759 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005760
5761 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005762 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005763 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005764
5765 @Override
5766 public void handleMessage(Message msg) {
5767 switch (msg.what) {
5768 case DISMISS_DIALOG_UI_MSG: {
5769 final Dialog d = (Dialog) msg.obj;
5770 d.dismiss();
5771 break;
5772 }
5773 }
5774 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005775 }
5776
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005777 final class LocalService extends ActivityTaskManagerInternal {
5778 @Override
5779 public SleepToken acquireSleepToken(String tag, int displayId) {
5780 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005781 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
5783
5784 @Override
5785 public ComponentName getHomeActivityForUser(int userId) {
5786 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005787 final ActivityRecord homeActivity =
5788 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005789 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005790 }
5791 }
5792
5793 @Override
5794 public void onLocalVoiceInteractionStarted(IBinder activity,
5795 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5796 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005797 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005798 }
5799 }
5800
5801 @Override
5802 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5803 synchronized (mGlobalLock) {
5804 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5805 reasons, timestamp);
5806 }
5807 }
5808
5809 @Override
5810 public void notifyAppTransitionFinished() {
5811 synchronized (mGlobalLock) {
5812 mStackSupervisor.notifyAppTransitionDone();
5813 }
5814 }
5815
5816 @Override
5817 public void notifyAppTransitionCancelled() {
5818 synchronized (mGlobalLock) {
5819 mStackSupervisor.notifyAppTransitionDone();
5820 }
5821 }
5822
5823 @Override
5824 public List<IBinder> getTopVisibleActivities() {
5825 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005826 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005827 }
5828 }
5829
5830 @Override
5831 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5832 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005833 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005834 }
5835 }
5836
5837 @Override
5838 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5839 Bundle bOptions) {
5840 Preconditions.checkNotNull(intents, "intents");
5841 final String[] resolvedTypes = new String[intents.length];
5842
5843 // UID of the package on user userId.
5844 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5845 // packageUid may not be initialized.
5846 int packageUid = 0;
5847 final long ident = Binder.clearCallingIdentity();
5848
5849 try {
5850 for (int i = 0; i < intents.length; i++) {
5851 resolvedTypes[i] =
5852 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5853 }
5854
5855 packageUid = AppGlobals.getPackageManager().getPackageUid(
5856 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5857 } catch (RemoteException e) {
5858 // Shouldn't happen.
5859 } finally {
5860 Binder.restoreCallingIdentity(ident);
5861 }
5862
5863 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005864 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005865 packageUid, packageName,
5866 intents, resolvedTypes, null /* resultTo */,
5867 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005868 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5869 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005870 }
5871 }
5872
5873 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005874 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5875 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5876 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5877 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005878 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005879 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005880 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5881 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5882 userId, validateIncomingUser, originatingPendingIntent,
5883 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005884 }
5885 }
5886
5887 @Override
5888 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5889 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5890 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5891 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005892 PendingIntentRecord originatingPendingIntent,
5893 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005894 synchronized (mGlobalLock) {
5895 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5896 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5897 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005898 validateIncomingUser, originatingPendingIntent,
5899 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005900 }
5901 }
5902
5903 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005904 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5905 Intent intent, Bundle options, int userId) {
5906 return ActivityTaskManagerService.this.startActivityAsUser(
5907 caller, callerPacakge, intent,
5908 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5909 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5910 false /*validateIncomingUser*/);
5911 }
5912
5913 @Override
lumark588a3e82018-07-20 18:53:54 +08005914 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005915 synchronized (mGlobalLock) {
5916
5917 // We might change the visibilities here, so prepare an empty app transition which
5918 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005919 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005920 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005921 if (activityDisplay == null) {
5922 return;
5923 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005924 final DisplayContent dc = activityDisplay.mDisplayContent;
5925 final boolean wasTransitionSet =
5926 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005927 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005928 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005930 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005931
5932 // If there was a transition set already we don't want to interfere with it as we
5933 // might be starting it too early.
5934 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005935 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005936 }
5937 }
5938 if (callback != null) {
5939 callback.run();
5940 }
5941 }
5942
5943 @Override
5944 public void notifyKeyguardTrustedChanged() {
5945 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005946 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005947 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005948 }
5949 }
5950 }
5951
5952 /**
5953 * Called after virtual display Id is updated by
5954 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5955 * {@param vrVr2dDisplayId}.
5956 */
5957 @Override
5958 public void setVr2dDisplayId(int vr2dDisplayId) {
5959 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5960 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005961 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005962 }
5963 }
5964
5965 @Override
5966 public void setFocusedActivity(IBinder token) {
5967 synchronized (mGlobalLock) {
5968 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5969 if (r == null) {
5970 throw new IllegalArgumentException(
5971 "setFocusedActivity: No activity record matching token=" + token);
5972 }
Louis Chang19443452018-10-09 12:10:21 +08005973 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005974 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005975 }
5976 }
5977 }
5978
5979 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005980 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005981 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005982 }
5983
5984 @Override
5985 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005986 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005987 }
5988
5989 @Override
5990 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005991 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005992 }
5993
5994 @Override
5995 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5996 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5997 }
5998
5999 @Override
6000 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006001 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006002 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006003
6004 @Override
6005 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6006 synchronized (mGlobalLock) {
6007 mActiveVoiceInteractionServiceComponent = component;
6008 }
6009 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006010
6011 @Override
6012 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6013 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6014 return;
6015 }
6016 synchronized (mGlobalLock) {
6017 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6018 if (types == null) {
6019 if (uid < 0) {
6020 return;
6021 }
6022 types = new ArrayMap<>();
6023 mAllowAppSwitchUids.put(userId, types);
6024 }
6025 if (uid < 0) {
6026 types.remove(type);
6027 } else {
6028 types.put(type, uid);
6029 }
6030 }
6031 }
6032
6033 @Override
6034 public void onUserStopped(int userId) {
6035 synchronized (mGlobalLock) {
6036 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6037 mAllowAppSwitchUids.remove(userId);
6038 }
6039 }
6040
6041 @Override
6042 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6043 synchronized (mGlobalLock) {
6044 return ActivityTaskManagerService.this.isGetTasksAllowed(
6045 caller, callingPid, callingUid);
6046 }
6047 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006048
6049 @Override
6050 public void onProcessAdded(WindowProcessController proc) {
6051 synchronized (mGlobalLock) {
6052 mProcessNames.put(proc.mName, proc.mUid, proc);
6053 }
6054 }
6055
6056 @Override
6057 public void onProcessRemoved(String name, int uid) {
6058 synchronized (mGlobalLock) {
6059 mProcessNames.remove(name, uid);
6060 }
6061 }
6062
6063 @Override
6064 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6065 synchronized (mGlobalLock) {
6066 if (proc == mHomeProcess) {
6067 mHomeProcess = null;
6068 }
6069 if (proc == mPreviousProcess) {
6070 mPreviousProcess = null;
6071 }
6072 }
6073 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006074
6075 @Override
6076 public int getTopProcessState() {
6077 synchronized (mGlobalLock) {
6078 return mTopProcessState;
6079 }
6080 }
6081
6082 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006083 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6084 synchronized (mGlobalLock) {
6085 return proc == mHeavyWeightProcess;
6086 }
6087 }
6088
6089 @Override
6090 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6091 synchronized (mGlobalLock) {
6092 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6093 }
6094 }
6095
6096 @Override
6097 public void finishHeavyWeightApp() {
6098 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006099 if (mHeavyWeightProcess != null) {
6100 mHeavyWeightProcess.finishActivities();
6101 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006102 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6103 mHeavyWeightProcess);
6104 }
6105 }
6106
6107 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006108 public boolean isSleeping() {
6109 synchronized (mGlobalLock) {
6110 return isSleepingLocked();
6111 }
6112 }
6113
6114 @Override
6115 public boolean isShuttingDown() {
6116 synchronized (mGlobalLock) {
6117 return mShuttingDown;
6118 }
6119 }
6120
6121 @Override
6122 public boolean shuttingDown(boolean booted, int timeout) {
6123 synchronized (mGlobalLock) {
6124 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006125 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006126 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006127 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006128 return mStackSupervisor.shutdownLocked(timeout);
6129 }
6130 }
6131
6132 @Override
6133 public void enableScreenAfterBoot(boolean booted) {
6134 synchronized (mGlobalLock) {
6135 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6136 SystemClock.uptimeMillis());
6137 mWindowManager.enableScreenAfterBoot();
6138 updateEventDispatchingLocked(booted);
6139 }
6140 }
6141
6142 @Override
6143 public boolean showStrictModeViolationDialog() {
6144 synchronized (mGlobalLock) {
6145 return mShowDialogs && !mSleeping && !mShuttingDown;
6146 }
6147 }
6148
6149 @Override
6150 public void showSystemReadyErrorDialogsIfNeeded() {
6151 synchronized (mGlobalLock) {
6152 try {
6153 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6154 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6155 + " data partition or your device will be unstable.");
6156 mUiHandler.post(() -> {
6157 if (mShowDialogs) {
6158 AlertDialog d = new BaseErrorDialog(mUiContext);
6159 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6160 d.setCancelable(false);
6161 d.setTitle(mUiContext.getText(R.string.android_system_label));
6162 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6163 d.setButton(DialogInterface.BUTTON_POSITIVE,
6164 mUiContext.getText(R.string.ok),
6165 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6166 d.show();
6167 }
6168 });
6169 }
6170 } catch (RemoteException e) {
6171 }
6172
6173 if (!Build.isBuildConsistent()) {
6174 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6175 mUiHandler.post(() -> {
6176 if (mShowDialogs) {
6177 AlertDialog d = new BaseErrorDialog(mUiContext);
6178 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6179 d.setCancelable(false);
6180 d.setTitle(mUiContext.getText(R.string.android_system_label));
6181 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6182 d.setButton(DialogInterface.BUTTON_POSITIVE,
6183 mUiContext.getText(R.string.ok),
6184 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6185 d.show();
6186 }
6187 });
6188 }
6189 }
6190 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006191
6192 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006193 public void onProcessMapped(int pid, WindowProcessController proc) {
6194 synchronized (mGlobalLock) {
6195 mPidMap.put(pid, proc);
6196 }
6197 }
6198
6199 @Override
6200 public void onProcessUnMapped(int pid) {
6201 synchronized (mGlobalLock) {
6202 mPidMap.remove(pid);
6203 }
6204 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006205
6206 @Override
6207 public void onPackageDataCleared(String name) {
6208 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006209 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006210 mAppWarnings.onPackageDataCleared(name);
6211 }
6212 }
6213
6214 @Override
6215 public void onPackageUninstalled(String name) {
6216 synchronized (mGlobalLock) {
6217 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006218 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006219 }
6220 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006221
6222 @Override
6223 public void onPackageAdded(String name, boolean replacing) {
6224 synchronized (mGlobalLock) {
6225 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6226 }
6227 }
6228
6229 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006230 public void onPackageReplaced(ApplicationInfo aInfo) {
6231 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006232 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006233 }
6234 }
6235
6236 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006237 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6238 synchronized (mGlobalLock) {
6239 return compatibilityInfoForPackageLocked(ai);
6240 }
6241 }
6242
Yunfan Chen75157d72018-07-27 14:47:21 +09006243 /**
6244 * Set the corresponding display information for the process global configuration. To be
6245 * called when we need to show IME on a different display.
6246 *
6247 * @param pid The process id associated with the IME window.
6248 * @param displayId The ID of the display showing the IME.
6249 */
6250 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006251 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006252 if (pid == MY_PID || pid < 0) {
6253 if (DEBUG_CONFIGURATION) {
6254 Slog.w(TAG,
6255 "Trying to update display configuration for system/invalid process.");
6256 }
6257 return;
6258 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006259 synchronized (mGlobalLock) {
6260 final ActivityDisplay activityDisplay =
6261 mRootActivityContainer.getActivityDisplay(displayId);
6262 if (activityDisplay == null) {
6263 // Call might come when display is not yet added or has been removed.
6264 if (DEBUG_CONFIGURATION) {
6265 Slog.w(TAG, "Trying to update display configuration for non-existing "
6266 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006267 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006268 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006269 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006270 final WindowProcessController process = mPidMap.get(pid);
6271 if (process == null) {
6272 if (DEBUG_CONFIGURATION) {
6273 Slog.w(TAG, "Trying to update display configuration for invalid "
6274 + "process, pid=" + pid);
6275 }
6276 return;
6277 }
6278 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6279 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006280 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006281
6282 @Override
6283 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6284 int requestCode, int resultCode, Intent data) {
6285 synchronized (mGlobalLock) {
6286 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006287 if (r != null && r.getActivityStack() != null) {
6288 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6289 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006290 }
6291 }
6292 }
6293
6294 @Override
6295 public void clearPendingResultForActivity(IBinder activityToken,
6296 WeakReference<PendingIntentRecord> pir) {
6297 synchronized (mGlobalLock) {
6298 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6299 if (r != null && r.pendingResults != null) {
6300 r.pendingResults.remove(pir);
6301 }
6302 }
6303 }
6304
6305 @Override
6306 public IIntentSender getIntentSender(int type, String packageName,
6307 int callingUid, int userId, IBinder token, String resultWho,
6308 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6309 Bundle bOptions) {
6310 synchronized (mGlobalLock) {
6311 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6312 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6313 }
6314 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006315
6316 @Override
6317 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6318 synchronized (mGlobalLock) {
6319 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6320 if (r == null) {
6321 return null;
6322 }
6323 if (r.mServiceConnectionsHolder == null) {
6324 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6325 ActivityTaskManagerService.this, r);
6326 }
6327
6328 return r.mServiceConnectionsHolder;
6329 }
6330 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006331
6332 @Override
6333 public Intent getHomeIntent() {
6334 synchronized (mGlobalLock) {
6335 return ActivityTaskManagerService.this.getHomeIntent();
6336 }
6337 }
6338
6339 @Override
6340 public boolean startHomeActivity(int userId, String reason) {
6341 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006342 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006343 }
6344 }
6345
6346 @Override
6347 public boolean startHomeOnAllDisplays(int userId, String reason) {
6348 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006349 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006350 }
6351 }
6352
6353 @Override
6354 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6355 synchronized (mGlobalLock) {
6356 if (mFactoryTest == FACTORY_TEST_OFF) {
6357 return false;
6358 }
6359 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6360 && wpc.mName.equals(mTopComponent.getPackageName())) {
6361 return true;
6362 }
6363 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6364 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6365 }
6366 }
6367
6368 @Override
6369 public void updateTopComponentForFactoryTest() {
6370 synchronized (mGlobalLock) {
6371 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6372 return;
6373 }
6374 final ResolveInfo ri = mContext.getPackageManager()
6375 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6376 final CharSequence errorMsg;
6377 if (ri != null) {
6378 final ActivityInfo ai = ri.activityInfo;
6379 final ApplicationInfo app = ai.applicationInfo;
6380 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6381 mTopAction = Intent.ACTION_FACTORY_TEST;
6382 mTopData = null;
6383 mTopComponent = new ComponentName(app.packageName, ai.name);
6384 errorMsg = null;
6385 } else {
6386 errorMsg = mContext.getResources().getText(
6387 com.android.internal.R.string.factorytest_not_system);
6388 }
6389 } else {
6390 errorMsg = mContext.getResources().getText(
6391 com.android.internal.R.string.factorytest_no_action);
6392 }
6393 if (errorMsg == null) {
6394 return;
6395 }
6396
6397 mTopAction = null;
6398 mTopData = null;
6399 mTopComponent = null;
6400 mUiHandler.post(() -> {
6401 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6402 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006403 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006404 });
6405 }
6406 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006407
6408 @Override
6409 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6410 Runnable finishInstrumentationCallback) {
6411 synchronized (mGlobalLock) {
6412 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006413 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006414
6415 wpc.clearRecentTasks();
6416 wpc.clearActivities();
6417
6418 if (wpc.isInstrumenting()) {
6419 finishInstrumentationCallback.run();
6420 }
6421
Jorim Jaggid0752812018-10-16 16:07:20 +02006422 if (!restarting && hasVisibleActivities) {
6423 mWindowManager.deferSurfaceLayout();
6424 try {
6425 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6426 // If there was nothing to resume, and we are not already restarting
6427 // this process, but there is a visible activity that is hosted by the
6428 // process...then make sure all visible activities are running, taking
6429 // care of restarting this process.
6430 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6431 !PRESERVE_WINDOWS);
6432 }
6433 } finally {
6434 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006435 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006436 }
6437 }
6438 }
6439
6440 @Override
6441 public void closeSystemDialogs(String reason) {
6442 enforceNotIsolatedCaller("closeSystemDialogs");
6443
6444 final int pid = Binder.getCallingPid();
6445 final int uid = Binder.getCallingUid();
6446 final long origId = Binder.clearCallingIdentity();
6447 try {
6448 synchronized (mGlobalLock) {
6449 // Only allow this from foreground processes, so that background
6450 // applications can't abuse it to prevent system UI from being shown.
6451 if (uid >= FIRST_APPLICATION_UID) {
6452 final WindowProcessController proc = mPidMap.get(pid);
6453 if (!proc.isPerceptible()) {
6454 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6455 + " from background process " + proc);
6456 return;
6457 }
6458 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006459 mWindowManager.closeSystemDialogs(reason);
6460
Wale Ogunwaled32da472018-11-16 07:19:28 -08006461 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006462 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006463 // Call into AM outside the synchronized block.
6464 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006465 } finally {
6466 Binder.restoreCallingIdentity(origId);
6467 }
6468 }
6469
6470 @Override
6471 public void cleanupDisabledPackageComponents(
6472 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6473 synchronized (mGlobalLock) {
6474 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006475 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006476 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006477 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006478 mStackSupervisor.scheduleIdleLocked();
6479 }
6480
6481 // Clean-up disabled tasks
6482 getRecentTasks().cleanupDisabledPackageTasksLocked(
6483 packageName, disabledClasses, userId);
6484 }
6485 }
6486
6487 @Override
6488 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6489 int userId) {
6490 synchronized (mGlobalLock) {
6491
6492 boolean didSomething =
6493 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006494 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006495 null, doit, evenPersistent, userId);
6496 return didSomething;
6497 }
6498 }
6499
6500 @Override
6501 public void resumeTopActivities(boolean scheduleIdle) {
6502 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006503 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006504 if (scheduleIdle) {
6505 mStackSupervisor.scheduleIdleLocked();
6506 }
6507 }
6508 }
6509
6510 @Override
6511 public void preBindApplication(WindowProcessController wpc) {
6512 synchronized (mGlobalLock) {
6513 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6514 }
6515 }
6516
6517 @Override
6518 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6519 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006520 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006521 }
6522 }
6523
6524 @Override
6525 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6526 try {
6527 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6528 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6529 }
6530 } catch (RemoteException ex) {
6531 throw new SecurityException("Fail to check is caller a privileged app", ex);
6532 }
6533
6534 synchronized (mGlobalLock) {
6535 final long ident = Binder.clearCallingIdentity();
6536 try {
6537 if (mAmInternal.shouldConfirmCredentials(userId)) {
6538 if (mKeyguardController.isKeyguardLocked()) {
6539 // Showing launcher to avoid user entering credential twice.
6540 startHomeActivity(currentUserId, "notifyLockedProfile");
6541 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006542 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006543 }
6544 } finally {
6545 Binder.restoreCallingIdentity(ident);
6546 }
6547 }
6548 }
6549
6550 @Override
6551 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6552 mAmInternal.enforceCallingPermission(
6553 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6554
6555 synchronized (mGlobalLock) {
6556 final long ident = Binder.clearCallingIdentity();
6557 try {
6558 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6559 FLAG_ACTIVITY_TASK_ON_HOME);
6560 ActivityOptions activityOptions = options != null
6561 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006562 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006563 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006564 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006565 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006566 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006567 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6568 UserHandle.CURRENT);
6569 } finally {
6570 Binder.restoreCallingIdentity(ident);
6571 }
6572 }
6573 }
6574
6575 @Override
6576 public void writeActivitiesToProto(ProtoOutputStream proto) {
6577 synchronized (mGlobalLock) {
6578 // The output proto of "activity --proto activities"
6579 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006580 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006581 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6582 }
6583 }
6584
6585 @Override
6586 public void saveANRState(String reason) {
6587 synchronized (mGlobalLock) {
6588 final StringWriter sw = new StringWriter();
6589 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6590 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6591 if (reason != null) {
6592 pw.println(" Reason: " + reason);
6593 }
6594 pw.println();
6595 getActivityStartController().dump(pw, " ", null);
6596 pw.println();
6597 pw.println("-------------------------------------------------------------------------------");
6598 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6599 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6600 "" /* header */);
6601 pw.println();
6602 pw.close();
6603
6604 mLastANRState = sw.toString();
6605 }
6606 }
6607
6608 @Override
6609 public void clearSavedANRState() {
6610 synchronized (mGlobalLock) {
6611 mLastANRState = null;
6612 }
6613 }
6614
6615 @Override
6616 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6617 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6618 synchronized (mGlobalLock) {
6619 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6620 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6621 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6622 dumpLastANRLocked(pw);
6623 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6624 dumpLastANRTracesLocked(pw);
6625 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6626 dumpActivityStarterLocked(pw, dumpPackage);
6627 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6628 dumpActivityContainersLocked(pw);
6629 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6630 if (getRecentTasks() != null) {
6631 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6632 }
6633 }
6634 }
6635 }
6636
6637 @Override
6638 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6639 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6640 int wakefulness) {
6641 synchronized (mGlobalLock) {
6642 if (mHomeProcess != null && (dumpPackage == null
6643 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6644 if (needSep) {
6645 pw.println();
6646 needSep = false;
6647 }
6648 pw.println(" mHomeProcess: " + mHomeProcess);
6649 }
6650 if (mPreviousProcess != null && (dumpPackage == null
6651 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6652 if (needSep) {
6653 pw.println();
6654 needSep = false;
6655 }
6656 pw.println(" mPreviousProcess: " + mPreviousProcess);
6657 }
6658 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6659 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6660 StringBuilder sb = new StringBuilder(128);
6661 sb.append(" mPreviousProcessVisibleTime: ");
6662 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6663 pw.println(sb);
6664 }
6665 if (mHeavyWeightProcess != null && (dumpPackage == null
6666 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6667 if (needSep) {
6668 pw.println();
6669 needSep = false;
6670 }
6671 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6672 }
6673 if (dumpPackage == null) {
6674 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006675 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006676 }
6677 if (dumpAll) {
6678 if (dumpPackage == null) {
6679 pw.println(" mConfigWillChange: "
6680 + getTopDisplayFocusedStack().mConfigWillChange);
6681 }
6682 if (mCompatModePackages.getPackages().size() > 0) {
6683 boolean printed = false;
6684 for (Map.Entry<String, Integer> entry
6685 : mCompatModePackages.getPackages().entrySet()) {
6686 String pkg = entry.getKey();
6687 int mode = entry.getValue();
6688 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6689 continue;
6690 }
6691 if (!printed) {
6692 pw.println(" mScreenCompatPackages:");
6693 printed = true;
6694 }
6695 pw.println(" " + pkg + ": " + mode);
6696 }
6697 }
6698 }
6699
6700 if (dumpPackage == null) {
6701 pw.println(" mWakefulness="
6702 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006703 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006704 if (mRunningVoice != null) {
6705 pw.println(" mRunningVoice=" + mRunningVoice);
6706 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6707 }
6708 pw.println(" mSleeping=" + mSleeping);
6709 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6710 pw.println(" mVrController=" + mVrController);
6711 }
6712 if (mCurAppTimeTracker != null) {
6713 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6714 }
6715 if (mAllowAppSwitchUids.size() > 0) {
6716 boolean printed = false;
6717 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6718 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6719 for (int j = 0; j < types.size(); j++) {
6720 if (dumpPackage == null ||
6721 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6722 if (needSep) {
6723 pw.println();
6724 needSep = false;
6725 }
6726 if (!printed) {
6727 pw.println(" mAllowAppSwitchUids:");
6728 printed = true;
6729 }
6730 pw.print(" User ");
6731 pw.print(mAllowAppSwitchUids.keyAt(i));
6732 pw.print(": Type ");
6733 pw.print(types.keyAt(j));
6734 pw.print(" = ");
6735 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6736 pw.println();
6737 }
6738 }
6739 }
6740 }
6741 if (dumpPackage == null) {
6742 if (mController != null) {
6743 pw.println(" mController=" + mController
6744 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6745 }
6746 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6747 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6748 }
6749
6750 return needSep;
6751 }
6752 }
6753
6754 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006755 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6756 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006757 synchronized (mGlobalLock) {
6758 if (dumpPackage == null) {
6759 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6760 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006761 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6762 if (mRunningVoice != null) {
6763 final long vrToken = proto.start(
6764 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6765 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6766 mRunningVoice.toString());
6767 mVoiceWakeLock.writeToProto(
6768 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6769 proto.end(vrToken);
6770 }
6771 mVrController.writeToProto(proto,
6772 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 if (mController != null) {
6774 final long token = proto.start(CONTROLLER);
6775 proto.write(CONTROLLER, mController.toString());
6776 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6777 proto.end(token);
6778 }
6779 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6780 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6781 }
6782
6783 if (mHomeProcess != null && (dumpPackage == null
6784 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006785 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006786 }
6787
6788 if (mPreviousProcess != null && (dumpPackage == null
6789 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006790 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6792 }
6793
6794 if (mHeavyWeightProcess != null && (dumpPackage == null
6795 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006796 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 }
6798
6799 for (Map.Entry<String, Integer> entry
6800 : mCompatModePackages.getPackages().entrySet()) {
6801 String pkg = entry.getKey();
6802 int mode = entry.getValue();
6803 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6804 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6805 proto.write(PACKAGE, pkg);
6806 proto.write(MODE, mode);
6807 proto.end(compatToken);
6808 }
6809 }
6810
6811 if (mCurAppTimeTracker != null) {
6812 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6813 }
6814
6815 }
6816 }
6817
6818 @Override
6819 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6820 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6821 boolean dumpFocusedStackOnly) {
6822 synchronized (mGlobalLock) {
6823 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6824 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6825 }
6826 }
6827
6828 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006829 public void dumpForOom(PrintWriter pw) {
6830 synchronized (mGlobalLock) {
6831 pw.println(" mHomeProcess: " + mHomeProcess);
6832 pw.println(" mPreviousProcess: " + mPreviousProcess);
6833 if (mHeavyWeightProcess != null) {
6834 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6835 }
6836 }
6837 }
6838
6839 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 public boolean canGcNow() {
6841 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006842 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 }
6844 }
6845
6846 @Override
6847 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006848 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006849 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 return top != null ? top.app : null;
6851 }
6852 }
6853
6854 @Override
6855 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006856 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006857 if (mRootActivityContainer != null) {
6858 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 }
6860 }
6861 }
6862
6863 @Override
6864 public void scheduleDestroyAllActivities(String reason) {
6865 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006866 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868 }
6869
6870 @Override
6871 public void removeUser(int userId) {
6872 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006873 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006874 }
6875 }
6876
6877 @Override
6878 public boolean switchUser(int userId, UserState userState) {
6879 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006880 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006881 }
6882 }
6883
6884 @Override
6885 public void onHandleAppCrash(WindowProcessController wpc) {
6886 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006887 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 }
6889 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006890
6891 @Override
6892 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6893 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006894 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006895 }
6896 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006897
6898 @Override
6899 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006900 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006901 mActiveUids.put(uid, procState);
6902 }
6903 }
6904
6905 @Override
6906 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006907 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006908 mActiveUids.remove(uid);
6909 }
6910 }
6911
6912 @Override
6913 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006914 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006915 mActiveUids.clear();
6916 }
6917 }
6918
6919 @Override
6920 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006921 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006922 if (mActiveUids.get(uid) != null) {
6923 mActiveUids.put(uid, procState);
6924 }
6925 }
6926 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006927
6928 @Override
6929 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006930 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006931 mPendingTempWhitelist.put(uid, tag);
6932 }
6933 }
6934
6935 @Override
6936 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006937 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006938 mPendingTempWhitelist.remove(uid);
6939 }
6940 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006941
6942 @Override
6943 public boolean handleAppCrashInActivityController(String processName, int pid,
6944 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6945 Runnable killCrashingAppCallback) {
6946 synchronized (mGlobalLock) {
6947 if (mController == null) {
6948 return false;
6949 }
6950
6951 try {
6952 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6953 stackTrace)) {
6954 killCrashingAppCallback.run();
6955 return true;
6956 }
6957 } catch (RemoteException e) {
6958 mController = null;
6959 Watchdog.getInstance().setActivityController(null);
6960 }
6961 return false;
6962 }
6963 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006964
6965 @Override
6966 public void removeRecentTasksByPackageName(String packageName, int userId) {
6967 synchronized (mGlobalLock) {
6968 mRecentTasks.removeTasksByPackageName(packageName, userId);
6969 }
6970 }
6971
6972 @Override
6973 public void cleanupRecentTasksForUser(int userId) {
6974 synchronized (mGlobalLock) {
6975 mRecentTasks.cleanupLocked(userId);
6976 }
6977 }
6978
6979 @Override
6980 public void loadRecentTasksForUser(int userId) {
6981 synchronized (mGlobalLock) {
6982 mRecentTasks.loadUserRecentsLocked(userId);
6983 }
6984 }
6985
6986 @Override
6987 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6988 synchronized (mGlobalLock) {
6989 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6990 }
6991 }
6992
6993 @Override
6994 public void flushRecentTasks() {
6995 mRecentTasks.flush();
6996 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006997
6998 @Override
6999 public WindowProcessController getHomeProcess() {
7000 synchronized (mGlobalLock) {
7001 return mHomeProcess;
7002 }
7003 }
7004
7005 @Override
7006 public WindowProcessController getPreviousProcess() {
7007 synchronized (mGlobalLock) {
7008 return mPreviousProcess;
7009 }
7010 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007011
7012 @Override
7013 public void clearLockedTasks(String reason) {
7014 synchronized (mGlobalLock) {
7015 getLockTaskController().clearLockedTasks(reason);
7016 }
7017 }
7018
7019 @Override
7020 public void updateUserConfiguration() {
7021 synchronized (mGlobalLock) {
7022 final Configuration configuration = new Configuration(getGlobalConfiguration());
7023 final int currentUserId = mAmInternal.getCurrentUserId();
7024 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7025 configuration, currentUserId, Settings.System.canWrite(mContext));
7026 updateConfigurationLocked(configuration, null /* starting */,
7027 false /* initLocale */, false /* persistent */, currentUserId,
7028 false /* deferResume */);
7029 }
7030 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007031
7032 @Override
7033 public boolean canShowErrorDialogs() {
7034 synchronized (mGlobalLock) {
7035 return mShowDialogs && !mSleeping && !mShuttingDown
7036 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7037 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7038 mAmInternal.getCurrentUserId())
7039 && !(UserManager.isDeviceInDemoMode(mContext)
7040 && mAmInternal.getCurrentUser().isDemo());
7041 }
7042 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007043
7044 @Override
7045 public void setProfileApp(String profileApp) {
7046 synchronized (mGlobalLock) {
7047 mProfileApp = profileApp;
7048 }
7049 }
7050
7051 @Override
7052 public void setProfileProc(WindowProcessController wpc) {
7053 synchronized (mGlobalLock) {
7054 mProfileProc = wpc;
7055 }
7056 }
7057
7058 @Override
7059 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7060 synchronized (mGlobalLock) {
7061 mProfilerInfo = profilerInfo;
7062 }
7063 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007064
7065 @Override
7066 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7067 synchronized (mGlobalLock) {
7068 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7069 }
7070 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007071
7072 @Override
7073 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7074 synchronized (mGlobalLock) {
7075 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7076 }
7077 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007078
7079 @Override
7080 public boolean isUidForeground(int uid) {
7081 synchronized (mGlobalLock) {
7082 return ActivityTaskManagerService.this.isUidForeground(uid);
7083 }
7084 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007085 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007086}