blob: 2e3fb961b0640b7d9365411b881e0c8df9e53966 [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
Michal Karpinski4026cae2019-02-12 11:51:47 +0000624 private String mDeviceOwnerPackageName;
625
Wale Ogunwalef6733932018-06-27 05:14:34 -0700626 private final class FontScaleSettingObserver extends ContentObserver {
627 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
628 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
629
630 public FontScaleSettingObserver() {
631 super(mH);
632 final ContentResolver resolver = mContext.getContentResolver();
633 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
634 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
635 UserHandle.USER_ALL);
636 }
637
638 @Override
639 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
640 if (mFontScaleUri.equals(uri)) {
641 updateFontScaleIfNeeded(userId);
642 } else if (mHideErrorDialogsUri.equals(uri)) {
643 synchronized (mGlobalLock) {
644 updateShouldShowDialogsLocked(getGlobalConfiguration());
645 }
646 }
647 }
648 }
649
Charles Chen8d98dd22018-12-26 17:36:54 +0800650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
651 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700652 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700653 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700654 mSystemThread = ActivityThread.currentActivityThread();
655 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800657 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700658 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700659 }
660
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 public void onSystemReady() {
662 synchronized (mGlobalLock) {
663 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
664 PackageManager.FEATURE_CANT_SAVE_STATE);
665 mAssistUtils = new AssistUtils(mContext);
666 mVrController.onSystemReady();
667 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700668 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700669 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void onInitPowerManagement() {
673 synchronized (mGlobalLock) {
674 mStackSupervisor.initPowerManagement();
675 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
676 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
677 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
678 mVoiceWakeLock.setReferenceCounted(false);
679 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700680 }
681
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700682 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700683 mFontScaleSettingObserver = new FontScaleSettingObserver();
684 }
685
Wale Ogunwale59507092018-10-29 09:00:30 -0700686 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean freeformWindowManagement =
688 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
689 || Settings.Global.getInt(
690 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
691
692 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
693 final boolean supportsPictureInPicture = supportsMultiWindow &&
694 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
695 final boolean supportsSplitScreenMultiWindow =
696 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
697 final boolean supportsMultiDisplay = mContext.getPackageManager()
698 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700699 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
700 final boolean forceResizable = Settings.Global.getInt(
701 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700702 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700703
704 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900705 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706
707 final Configuration configuration = new Configuration();
708 Settings.System.getConfiguration(resolver, configuration);
709 if (forceRtl) {
710 // This will take care of setting the correct layout direction flags
711 configuration.setLayoutDirection(configuration.locale);
712 }
713
714 synchronized (mGlobalLock) {
715 mForceResizableActivities = forceResizable;
716 final boolean multiWindowFormEnabled = freeformWindowManagement
717 || supportsSplitScreenMultiWindow
718 || supportsPictureInPicture
719 || supportsMultiDisplay;
720 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
721 mSupportsMultiWindow = true;
722 mSupportsFreeformWindowManagement = freeformWindowManagement;
723 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
724 mSupportsPictureInPicture = supportsPictureInPicture;
725 mSupportsMultiDisplay = supportsMultiDisplay;
726 } else {
727 mSupportsMultiWindow = false;
728 mSupportsFreeformWindowManagement = false;
729 mSupportsSplitScreenMultiWindow = false;
730 mSupportsPictureInPicture = false;
731 mSupportsMultiDisplay = false;
732 }
733 mWindowManager.setForceResizableTasks(mForceResizableActivities);
734 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700735 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
736 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737 // This happens before any activities are started, so we can change global configuration
738 // in-place.
739 updateConfigurationLocked(configuration, null, true);
740 final Configuration globalConfig = getGlobalConfiguration();
741 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
742
743 // Load resources only after the current configuration has been set.
744 final Resources res = mContext.getResources();
745 mThumbnailWidth = res.getDimensionPixelSize(
746 com.android.internal.R.dimen.thumbnail_width);
747 mThumbnailHeight = res.getDimensionPixelSize(
748 com.android.internal.R.dimen.thumbnail_height);
749
750 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
751 mFullscreenThumbnailScale = (float) res
752 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
753 (float) globalConfig.screenWidthDp;
754 } else {
755 mFullscreenThumbnailScale = res.getFraction(
756 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
757 }
758 }
759 }
760
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800761 public WindowManagerGlobalLock getGlobalLock() {
762 return mGlobalLock;
763 }
764
Riddle Hsud93a6c42018-11-29 21:50:06 +0800765 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
766 Looper looper) {
767 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700769 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700770 final File systemDir = SystemServiceManager.ensureSystemDir();
771 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
772 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700773 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774
775 mTempConfig.setToDefaults();
776 mTempConfig.setLocales(LocaleList.getDefault());
777 mConfigurationSeq = mTempConfig.seq = 1;
778 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800779 mRootActivityContainer = new RootActivityContainer(this);
780 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700781
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700782 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700784 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700785 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700786 mRecentTasks = createRecentTasks();
787 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700788 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700789 mKeyguardController = mStackSupervisor.getKeyguardController();
790 }
791
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700792 public void onActivityManagerInternalAdded() {
793 synchronized (mGlobalLock) {
794 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
795 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
796 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700797 }
798
Yunfan Chen75157d72018-07-27 14:47:21 +0900799 int increaseConfigurationSeqLocked() {
800 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
801 return mConfigurationSeq;
802 }
803
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804 protected ActivityStackSupervisor createStackSupervisor() {
805 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
806 supervisor.initialize();
807 return supervisor;
808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setWindowManager(WindowManagerService wm) {
811 synchronized (mGlobalLock) {
812 mWindowManager = wm;
813 mLockTaskController.setWindowManager(wm);
814 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700816 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700817 }
818
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700819 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
820 synchronized (mGlobalLock) {
821 mUsageStatsInternal = usageStatsManager;
822 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 }
824
Wale Ogunwalef6733932018-06-27 05:14:34 -0700825 UserManagerService getUserManager() {
826 if (mUserManager == null) {
827 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
828 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
829 }
830 return mUserManager;
831 }
832
833 AppOpsService getAppOpsService() {
834 if (mAppOpsService == null) {
835 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
836 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
837 }
838 return mAppOpsService;
839 }
840
841 boolean hasUserRestriction(String restriction, int userId) {
842 return getUserManager().hasUserRestriction(restriction, userId);
843 }
844
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700845 protected RecentTasks createRecentTasks() {
846 return new RecentTasks(this, mStackSupervisor);
847 }
848
849 RecentTasks getRecentTasks() {
850 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700851 }
852
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700853 ClientLifecycleManager getLifecycleManager() {
854 return mLifecycleManager;
855 }
856
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700857 ActivityStartController getActivityStartController() {
858 return mActivityStartController;
859 }
860
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700861 TaskChangeNotificationController getTaskChangeNotificationController() {
862 return mTaskChangeNotificationController;
863 }
864
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700865 LockTaskController getLockTaskController() {
866 return mLockTaskController;
867 }
868
Yunfan Chen75157d72018-07-27 14:47:21 +0900869 /**
870 * Return the global configuration used by the process corresponding to the input pid. This is
871 * usually the global configuration with some overrides specific to that process.
872 */
873 Configuration getGlobalConfigurationForCallingPid() {
874 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800875 return getGlobalConfigurationForPid(pid);
876 }
877
878 /**
879 * Return the global configuration used by the process corresponding to the given pid.
880 */
881 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900882 if (pid == MY_PID || pid < 0) {
883 return getGlobalConfiguration();
884 }
885 synchronized (mGlobalLock) {
886 final WindowProcessController app = mPidMap.get(pid);
887 return app != null ? app.getConfiguration() : getGlobalConfiguration();
888 }
889 }
890
891 /**
892 * Return the device configuration info used by the process corresponding to the input pid.
893 * The value is consistent with the global configuration for the process.
894 */
895 @Override
896 public ConfigurationInfo getDeviceConfigurationInfo() {
897 ConfigurationInfo config = new ConfigurationInfo();
898 synchronized (mGlobalLock) {
899 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
900 config.reqTouchScreen = globalConfig.touchscreen;
901 config.reqKeyboardType = globalConfig.keyboard;
902 config.reqNavigation = globalConfig.navigation;
903 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
904 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
905 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
906 }
907 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
908 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
909 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
910 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700911 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 }
913 return config;
914 }
915
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700916 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700917 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700918 }
919
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 public static final class Lifecycle extends SystemService {
921 private final ActivityTaskManagerService mService;
922
923 public Lifecycle(Context context) {
924 super(context);
925 mService = new ActivityTaskManagerService(context);
926 }
927
928 @Override
929 public void onStart() {
930 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700931 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700932 }
933
Garfield Tan891146c2018-10-09 12:14:00 -0700934 @Override
935 public void onUnlockUser(int userId) {
936 synchronized (mService.getGlobalLock()) {
937 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
938 }
939 }
940
941 @Override
942 public void onCleanupUser(int userId) {
943 synchronized (mService.getGlobalLock()) {
944 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
945 }
946 }
947
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700948 public ActivityTaskManagerService getService() {
949 return mService;
950 }
951 }
952
953 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700954 public final int startActivity(IApplicationThread caller, String callingPackage,
955 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
956 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
957 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
958 resultWho, requestCode, startFlags, profilerInfo, bOptions,
959 UserHandle.getCallingUserId());
960 }
961
962 @Override
963 public final int startActivities(IApplicationThread caller, String callingPackage,
964 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
965 int userId) {
966 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700967 enforceNotIsolatedCaller(reason);
968 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000970 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
971 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
972 reason, null /* originatingPendingIntent */,
973 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700974 }
975
976 @Override
977 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
978 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
979 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
980 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
981 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
982 true /*validateIncomingUser*/);
983 }
984
985 int startActivityAsUser(IApplicationThread caller, String callingPackage,
986 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
987 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
988 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700989 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700990
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700991 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700992 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
993
994 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700995 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 .setCaller(caller)
997 .setCallingPackage(callingPackage)
998 .setResolvedType(resolvedType)
999 .setResultTo(resultTo)
1000 .setResultWho(resultWho)
1001 .setRequestCode(requestCode)
1002 .setStartFlags(startFlags)
1003 .setProfilerInfo(profilerInfo)
1004 .setActivityOptions(bOptions)
1005 .setMayWait(userId)
1006 .execute();
1007
1008 }
1009
1010 @Override
1011 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1012 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001013 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1014 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 // Refuse possible leaked file descriptors
1016 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1017 throw new IllegalArgumentException("File descriptors passed in Intent");
1018 }
1019
1020 if (!(target instanceof PendingIntentRecord)) {
1021 throw new IllegalArgumentException("Bad PendingIntent object");
1022 }
1023
1024 PendingIntentRecord pir = (PendingIntentRecord)target;
1025
1026 synchronized (mGlobalLock) {
1027 // If this is coming from the currently resumed activity, it is
1028 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001029 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 if (stack.mResumedActivity != null &&
1031 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 }
1034 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 }
1038
1039 @Override
1040 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1041 Bundle bOptions) {
1042 // Refuse possible leaked file descriptors
1043 if (intent != null && intent.hasFileDescriptors()) {
1044 throw new IllegalArgumentException("File descriptors passed in Intent");
1045 }
1046 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1047
1048 synchronized (mGlobalLock) {
1049 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1050 if (r == null) {
1051 SafeActivityOptions.abort(options);
1052 return false;
1053 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001054 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 // The caller is not running... d'oh!
1056 SafeActivityOptions.abort(options);
1057 return false;
1058 }
1059 intent = new Intent(intent);
1060 // The caller is not allowed to change the data.
1061 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1062 // And we are resetting to find the next component...
1063 intent.setComponent(null);
1064
1065 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1066
1067 ActivityInfo aInfo = null;
1068 try {
1069 List<ResolveInfo> resolves =
1070 AppGlobals.getPackageManager().queryIntentActivities(
1071 intent, r.resolvedType,
1072 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1073 UserHandle.getCallingUserId()).getList();
1074
1075 // Look for the original activity in the list...
1076 final int N = resolves != null ? resolves.size() : 0;
1077 for (int i=0; i<N; i++) {
1078 ResolveInfo rInfo = resolves.get(i);
1079 if (rInfo.activityInfo.packageName.equals(r.packageName)
1080 && rInfo.activityInfo.name.equals(r.info.name)) {
1081 // We found the current one... the next matching is
1082 // after it.
1083 i++;
1084 if (i<N) {
1085 aInfo = resolves.get(i).activityInfo;
1086 }
1087 if (debug) {
1088 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1089 + "/" + r.info.name);
1090 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1091 ? "null" : aInfo.packageName + "/" + aInfo.name));
1092 }
1093 break;
1094 }
1095 }
1096 } catch (RemoteException e) {
1097 }
1098
1099 if (aInfo == null) {
1100 // Nobody who is next!
1101 SafeActivityOptions.abort(options);
1102 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1103 return false;
1104 }
1105
1106 intent.setComponent(new ComponentName(
1107 aInfo.applicationInfo.packageName, aInfo.name));
1108 intent.setFlags(intent.getFlags()&~(
1109 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1110 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1111 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1112 FLAG_ACTIVITY_NEW_TASK));
1113
1114 // Okay now we need to start the new activity, replacing the currently running activity.
1115 // This is a little tricky because we want to start the new one as if the current one is
1116 // finished, but not finish the current one first so that there is no flicker.
1117 // And thus...
1118 final boolean wasFinishing = r.finishing;
1119 r.finishing = true;
1120
1121 // Propagate reply information over to the new activity.
1122 final ActivityRecord resultTo = r.resultTo;
1123 final String resultWho = r.resultWho;
1124 final int requestCode = r.requestCode;
1125 r.resultTo = null;
1126 if (resultTo != null) {
1127 resultTo.removeResultsLocked(r, resultWho, requestCode);
1128 }
1129
1130 final long origId = Binder.clearCallingIdentity();
1131 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001132 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001133 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001134 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 .setResolvedType(r.resolvedType)
1136 .setActivityInfo(aInfo)
1137 .setResultTo(resultTo != null ? resultTo.appToken : null)
1138 .setResultWho(resultWho)
1139 .setRequestCode(requestCode)
1140 .setCallingPid(-1)
1141 .setCallingUid(r.launchedFromUid)
1142 .setCallingPackage(r.launchedFromPackage)
1143 .setRealCallingPid(-1)
1144 .setRealCallingUid(r.launchedFromUid)
1145 .setActivityOptions(options)
1146 .execute();
1147 Binder.restoreCallingIdentity(origId);
1148
1149 r.finishing = wasFinishing;
1150 if (res != ActivityManager.START_SUCCESS) {
1151 return false;
1152 }
1153 return true;
1154 }
1155 }
1156
1157 @Override
1158 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1159 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1160 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1161 final WaitResult res = new WaitResult();
1162 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001163 enforceNotIsolatedCaller("startActivityAndWait");
1164 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1165 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001166 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001167 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 .setCaller(caller)
1169 .setCallingPackage(callingPackage)
1170 .setResolvedType(resolvedType)
1171 .setResultTo(resultTo)
1172 .setResultWho(resultWho)
1173 .setRequestCode(requestCode)
1174 .setStartFlags(startFlags)
1175 .setActivityOptions(bOptions)
1176 .setMayWait(userId)
1177 .setProfilerInfo(profilerInfo)
1178 .setWaitResult(res)
1179 .execute();
1180 }
1181 return res;
1182 }
1183
1184 @Override
1185 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1186 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1187 int startFlags, Configuration config, Bundle bOptions, int userId) {
1188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001189 enforceNotIsolatedCaller("startActivityWithConfig");
1190 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1191 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .setCaller(caller)
1195 .setCallingPackage(callingPackage)
1196 .setResolvedType(resolvedType)
1197 .setResultTo(resultTo)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setStartFlags(startFlags)
1201 .setGlobalConfiguration(config)
1202 .setActivityOptions(bOptions)
1203 .setMayWait(userId)
1204 .execute();
1205 }
1206 }
1207
Alison Cichowlas3e340502018-08-07 17:15:01 -04001208
1209 @Override
1210 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1211 int callingUid = Binder.getCallingUid();
1212 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1213 throw new SecurityException("Only the system process can request a permission token, "
1214 + "received request from uid: " + callingUid);
1215 }
1216 IBinder permissionToken = new Binder();
1217 synchronized (mGlobalLock) {
1218 mStartActivitySources.put(permissionToken, delegatorToken);
1219 }
1220
1221 Message expireMsg = PooledLambda.obtainMessage(
1222 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1223 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1224
1225 Message forgetMsg = PooledLambda.obtainMessage(
1226 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1227 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1228
1229 return permissionToken;
1230 }
1231
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001232 @Override
1233 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1236 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001238 // permission grants) as any app that may launch one of your own activities. So we only
1239 // allow this in two cases:
1240 // 1) The caller is an activity that is part of the core framework, and then only when it
1241 // is running as the system.
1242 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1243 // can only be requested by a system activity, which may then delegate this call to
1244 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 final ActivityRecord sourceRecord;
1246 final int targetUid;
1247 final String targetPackage;
1248 final boolean isResolver;
1249 synchronized (mGlobalLock) {
1250 if (resultTo == null) {
1251 throw new SecurityException("Must be called from an activity");
1252 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001253 final IBinder sourceToken;
1254 if (permissionToken != null) {
1255 // To even attempt to use a permissionToken, an app must also have this signature
1256 // permission.
1257 mAmInternal.enforceCallingPermission(
1258 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1259 "startActivityAsCaller");
1260 // If called with a permissionToken, we want the sourceRecord from the delegator
1261 // activity that requested this token.
1262 sourceToken = mStartActivitySources.remove(permissionToken);
1263 if (sourceToken == null) {
1264 // Invalid permissionToken, check if it recently expired.
1265 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1266 throw new SecurityException("Called with expired permission token: "
1267 + permissionToken);
1268 } else {
1269 throw new SecurityException("Called with invalid permission token: "
1270 + permissionToken);
1271 }
1272 }
1273 } else {
1274 // This method was called directly by the source.
1275 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277
Wale Ogunwaled32da472018-11-16 07:19:28 -08001278 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 if (sourceRecord == null) {
1280 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 }
1282 if (sourceRecord.app == null) {
1283 throw new SecurityException("Called without a process attached to activity");
1284 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285
1286 // Whether called directly or from a delegate, the source activity must be from the
1287 // android package.
1288 if (!sourceRecord.info.packageName.equals("android")) {
1289 throw new SecurityException("Must be called from an activity that is "
1290 + "declared in the android package");
1291 }
1292
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001293 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001294 // This is still okay, as long as this activity is running under the
1295 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001296 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001298 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 + " must be system uid or original calling uid "
1300 + sourceRecord.launchedFromUid);
1301 }
1302 }
1303 if (ignoreTargetSecurity) {
1304 if (intent.getComponent() == null) {
1305 throw new SecurityException(
1306 "Component must be specified with ignoreTargetSecurity");
1307 }
1308 if (intent.getSelector() != null) {
1309 throw new SecurityException(
1310 "Selector not allowed with ignoreTargetSecurity");
1311 }
1312 }
1313 targetUid = sourceRecord.launchedFromUid;
1314 targetPackage = sourceRecord.launchedFromPackage;
1315 isResolver = sourceRecord.isResolverOrChildActivity();
1316 }
1317
1318 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001319 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
1321
1322 // TODO: Switch to user app stacks here.
1323 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001324 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 .setCallingUid(targetUid)
1326 .setCallingPackage(targetPackage)
1327 .setResolvedType(resolvedType)
1328 .setResultTo(resultTo)
1329 .setResultWho(resultWho)
1330 .setRequestCode(requestCode)
1331 .setStartFlags(startFlags)
1332 .setActivityOptions(bOptions)
1333 .setMayWait(userId)
1334 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1335 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1336 .execute();
1337 } catch (SecurityException e) {
1338 // XXX need to figure out how to propagate to original app.
1339 // A SecurityException here is generally actually a fault of the original
1340 // calling activity (such as a fairly granting permissions), so propagate it
1341 // back to them.
1342 /*
1343 StringBuilder msg = new StringBuilder();
1344 msg.append("While launching");
1345 msg.append(intent.toString());
1346 msg.append(": ");
1347 msg.append(e.getMessage());
1348 */
1349 throw e;
1350 }
1351 }
1352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1354 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1355 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1356 }
1357
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 @Override
1359 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1360 Intent intent, String resolvedType, IVoiceInteractionSession session,
1361 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1362 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001363 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 if (session == null || interactor == null) {
1365 throw new NullPointerException("null session or interactor");
1366 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001369 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 .setCallingUid(callingUid)
1371 .setCallingPackage(callingPackage)
1372 .setResolvedType(resolvedType)
1373 .setVoiceSession(session)
1374 .setVoiceInteractor(interactor)
1375 .setStartFlags(startFlags)
1376 .setProfilerInfo(profilerInfo)
1377 .setActivityOptions(bOptions)
1378 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001379 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 .execute();
1381 }
1382
1383 @Override
1384 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1385 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001386 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1387 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001389 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 .setCallingUid(callingUid)
1391 .setCallingPackage(callingPackage)
1392 .setResolvedType(resolvedType)
1393 .setActivityOptions(bOptions)
1394 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001395 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .execute();
1397 }
1398
1399 @Override
1400 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1401 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001402 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 final int callingPid = Binder.getCallingPid();
1404 final long origId = Binder.clearCallingIdentity();
1405 try {
1406 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001407 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1408 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409
1410 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1412 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1414 recentsUid, assistDataReceiver);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(origId);
1418 }
1419 }
1420
1421 @Override
1422 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 "startActivityFromRecents()");
1425
1426 final int callingPid = Binder.getCallingPid();
1427 final int callingUid = Binder.getCallingUid();
1428 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1429 final long origId = Binder.clearCallingIdentity();
1430 try {
1431 synchronized (mGlobalLock) {
1432 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1433 safeOptions);
1434 }
1435 } finally {
1436 Binder.restoreCallingIdentity(origId);
1437 }
1438 }
1439
1440 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001441 * Public API to check if the client is allowed to start an activity on specified display.
1442 *
1443 * If the target display is private or virtual, some restrictions will apply.
1444 *
1445 * @param displayId Target display id.
1446 * @param intent Intent used to launch the activity.
1447 * @param resolvedType The MIME type of the intent.
1448 * @param userId The id of the user for whom the call is made.
1449 * @return {@code true} if a call to start an activity on the target display should succeed and
1450 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1451 */
1452 @Override
1453 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1454 String resolvedType, int userId) {
1455 final int callingUid = Binder.getCallingUid();
1456 final int callingPid = Binder.getCallingPid();
1457 final long origId = Binder.clearCallingIdentity();
1458
1459 try {
1460 // Collect information about the target of the Intent.
1461 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1462 0 /* startFlags */, null /* profilerInfo */, userId,
1463 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1464 UserHandle.USER_NULL));
1465 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1466
1467 synchronized (mGlobalLock) {
1468 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1469 aInfo);
1470 }
1471 } finally {
1472 Binder.restoreCallingIdentity(origId);
1473 }
1474 }
1475
1476 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 * This is the internal entry point for handling Activity.finish().
1478 *
1479 * @param token The Binder token referencing the Activity we want to finish.
1480 * @param resultCode Result code, if any, from this Activity.
1481 * @param resultData Result data (Intent), if any, from this Activity.
1482 * @param finishTask Whether to finish the task associated with this Activity.
1483 *
1484 * @return Returns true if the activity successfully finished, or false if it is still running.
1485 */
1486 @Override
1487 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1488 int finishTask) {
1489 // Refuse possible leaked file descriptors
1490 if (resultData != null && resultData.hasFileDescriptors()) {
1491 throw new IllegalArgumentException("File descriptors passed in Intent");
1492 }
1493
1494 synchronized (mGlobalLock) {
1495 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1496 if (r == null) {
1497 return true;
1498 }
1499 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001500 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001501 ActivityRecord rootR = tr.getRootActivity();
1502 if (rootR == null) {
1503 Slog.w(TAG, "Finishing task with all activities already finished");
1504 }
1505 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1506 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001507 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 return false;
1509 }
1510
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001511 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1512 // We should consolidate.
1513 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001514 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001515 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 if (next != null) {
1517 // ask watcher if this is allowed
1518 boolean resumeOK = true;
1519 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001520 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001522 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 Watchdog.getInstance().setActivityController(null);
1524 }
1525
1526 if (!resumeOK) {
1527 Slog.i(TAG, "Not finishing activity because controller resumed");
1528 return false;
1529 }
1530 }
1531 }
1532 final long origId = Binder.clearCallingIdentity();
1533 try {
1534 boolean res;
1535 final boolean finishWithRootActivity =
1536 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1537 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1538 || (finishWithRootActivity && r == rootR)) {
1539 // If requested, remove the task that is associated to this activity only if it
1540 // was the root activity in the task. The result code and data is ignored
1541 // because we don't support returning them across task boundaries. Also, to
1542 // keep backwards compatibility we remove the task from recents when finishing
1543 // task with root activity.
1544 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1545 finishWithRootActivity, "finish-activity");
1546 if (!res) {
1547 Slog.i(TAG, "Removing task failed to finish activity");
1548 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001549 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001550 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 } else {
1552 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1553 resultData, "app-request", true);
1554 if (!res) {
1555 Slog.i(TAG, "Failed to finish by app-request");
1556 }
1557 }
1558 return res;
1559 } finally {
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562 }
1563 }
1564
1565 @Override
1566 public boolean finishActivityAffinity(IBinder token) {
1567 synchronized (mGlobalLock) {
1568 final long origId = Binder.clearCallingIdentity();
1569 try {
1570 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1571 if (r == null) {
1572 return false;
1573 }
1574
1575 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1576 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001577 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001578 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 return false;
1580 }
1581 return task.getStack().finishActivityAffinityLocked(r);
1582 } finally {
1583 Binder.restoreCallingIdentity(origId);
1584 }
1585 }
1586 }
1587
1588 @Override
1589 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1590 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001591 try {
1592 WindowProcessController proc = null;
1593 synchronized (mGlobalLock) {
1594 ActivityStack stack = ActivityRecord.getStackLocked(token);
1595 if (stack == null) {
1596 return;
1597 }
1598 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1599 false /* fromTimeout */, false /* processPausingActivities */, config);
1600 if (r != null) {
1601 proc = r.app;
1602 }
1603 if (stopProfiling && proc != null) {
1604 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 }
1606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001607 } finally {
1608 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 }
1611
1612 @Override
1613 public final void activityResumed(IBinder token) {
1614 final long origId = Binder.clearCallingIdentity();
1615 synchronized (mGlobalLock) {
1616 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001617 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityPaused(IBinder token) {
1624 final long origId = Binder.clearCallingIdentity();
1625 synchronized (mGlobalLock) {
1626 ActivityStack stack = ActivityRecord.getStackLocked(token);
1627 if (stack != null) {
1628 stack.activityPausedLocked(token, false);
1629 }
1630 }
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633
1634 @Override
1635 public final void activityStopped(IBinder token, Bundle icicle,
1636 PersistableBundle persistentState, CharSequence description) {
1637 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1638
1639 // Refuse possible leaked file descriptors
1640 if (icicle != null && icicle.hasFileDescriptors()) {
1641 throw new IllegalArgumentException("File descriptors passed in Bundle");
1642 }
1643
1644 final long origId = Binder.clearCallingIdentity();
1645
1646 synchronized (mGlobalLock) {
1647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1648 if (r != null) {
1649 r.activityStoppedLocked(icicle, persistentState, description);
1650 }
1651 }
1652
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001653 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654
1655 Binder.restoreCallingIdentity(origId);
1656 }
1657
1658 @Override
1659 public final void activityDestroyed(IBinder token) {
1660 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1661 synchronized (mGlobalLock) {
1662 ActivityStack stack = ActivityRecord.getStackLocked(token);
1663 if (stack != null) {
1664 stack.activityDestroyedLocked(token, "activityDestroyed");
1665 }
1666 }
1667 }
1668
1669 @Override
1670 public final void activityRelaunched(IBinder token) {
1671 final long origId = Binder.clearCallingIdentity();
1672 synchronized (mGlobalLock) {
1673 mStackSupervisor.activityRelaunchedLocked(token);
1674 }
1675 Binder.restoreCallingIdentity(origId);
1676 }
1677
1678 public final void activitySlept(IBinder token) {
1679 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1680
1681 final long origId = Binder.clearCallingIdentity();
1682
1683 synchronized (mGlobalLock) {
1684 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r != null) {
1686 mStackSupervisor.activitySleptLocked(r);
1687 }
1688 }
1689
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
1694 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1695 synchronized (mGlobalLock) {
1696 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1697 if (r == null) {
1698 return;
1699 }
1700 final long origId = Binder.clearCallingIdentity();
1701 try {
1702 r.setRequestedOrientation(requestedOrientation);
1703 } finally {
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706 }
1707 }
1708
1709 @Override
1710 public int getRequestedOrientation(IBinder token) {
1711 synchronized (mGlobalLock) {
1712 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1713 if (r == null) {
1714 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1715 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001716 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 }
1718 }
1719
1720 @Override
1721 public void setImmersive(IBinder token, boolean immersive) {
1722 synchronized (mGlobalLock) {
1723 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1724 if (r == null) {
1725 throw new IllegalArgumentException();
1726 }
1727 r.immersive = immersive;
1728
1729 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001730 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001732 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734 }
1735 }
1736
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001737 void applyUpdateLockStateLocked(ActivityRecord r) {
1738 // Modifications to the UpdateLock state are done on our handler, outside
1739 // the activity manager's locks. The new state is determined based on the
1740 // state *now* of the relevant activity record. The object is passed to
1741 // the handler solely for logging detail, not to be consulted/modified.
1742 final boolean nextState = r != null && r.immersive;
1743 mH.post(() -> {
1744 if (mUpdateLock.isHeld() != nextState) {
1745 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1746 "Applying new update lock state '" + nextState + "' for " + r);
1747 if (nextState) {
1748 mUpdateLock.acquire();
1749 } else {
1750 mUpdateLock.release();
1751 }
1752 }
1753 });
1754 }
1755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 @Override
1757 public boolean isImmersive(IBinder token) {
1758 synchronized (mGlobalLock) {
1759 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1760 if (r == null) {
1761 throw new IllegalArgumentException();
1762 }
1763 return r.immersive;
1764 }
1765 }
1766
1767 @Override
1768 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001769 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001771 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 return (r != null) ? r.immersive : false;
1773 }
1774 }
1775
1776 @Override
1777 public void overridePendingTransition(IBinder token, String packageName,
1778 int enterAnim, int exitAnim) {
1779 synchronized (mGlobalLock) {
1780 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1781 if (self == null) {
1782 return;
1783 }
1784
1785 final long origId = Binder.clearCallingIdentity();
1786
1787 if (self.isState(
1788 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001789 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001790 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795 }
1796
1797 @Override
1798 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001801 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 if (r == null) {
1803 return ActivityManager.COMPAT_MODE_UNKNOWN;
1804 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001805 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
1807 }
1808
1809 @Override
1810 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001815 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 if (r == null) {
1817 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1818 return;
1819 }
1820 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001821 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001822 }
1823 }
1824
1825 @Override
1826 public int getLaunchedFromUid(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return -1;
1833 }
1834 return srec.launchedFromUid;
1835 }
1836
1837 @Override
1838 public String getLaunchedFromPackage(IBinder activityToken) {
1839 ActivityRecord srec;
1840 synchronized (mGlobalLock) {
1841 srec = ActivityRecord.forTokenLocked(activityToken);
1842 }
1843 if (srec == null) {
1844 return null;
1845 }
1846 return srec.launchedFromPackage;
1847 }
1848
1849 @Override
1850 public boolean convertFromTranslucent(IBinder token) {
1851 final long origId = Binder.clearCallingIdentity();
1852 try {
1853 synchronized (mGlobalLock) {
1854 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 return false;
1857 }
1858 final boolean translucentChanged = r.changeWindowTranslucency(true);
1859 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001860 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 return translucentChanged;
1864 }
1865 } finally {
1866 Binder.restoreCallingIdentity(origId);
1867 }
1868 }
1869
1870 @Override
1871 public boolean convertToTranslucent(IBinder token, Bundle options) {
1872 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1873 final long origId = Binder.clearCallingIdentity();
1874 try {
1875 synchronized (mGlobalLock) {
1876 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1877 if (r == null) {
1878 return false;
1879 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001880 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 int index = task.mActivities.lastIndexOf(r);
1882 if (index > 0) {
1883 ActivityRecord under = task.mActivities.get(index - 1);
1884 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1885 }
1886 final boolean translucentChanged = r.changeWindowTranslucency(false);
1887 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001888 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001890 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 return translucentChanged;
1893 }
1894 } finally {
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898
1899 @Override
1900 public void notifyActivityDrawn(IBinder token) {
1901 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1902 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001903 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001905 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908 }
1909
1910 @Override
1911 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 return;
1916 }
1917 r.reportFullyDrawnLocked(restoredFromBundle);
1918 }
1919 }
1920
1921 @Override
1922 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1923 synchronized (mGlobalLock) {
1924 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1925 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1926 return stack.mDisplayId;
1927 }
1928 return DEFAULT_DISPLAY;
1929 }
1930 }
1931
1932 @Override
1933 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 long ident = Binder.clearCallingIdentity();
1936 try {
1937 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001938 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001940 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 }
1942 return null;
1943 }
1944 } finally {
1945 Binder.restoreCallingIdentity(ident);
1946 }
1947 }
1948
1949 @Override
1950 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1953 final long callingId = Binder.clearCallingIdentity();
1954 try {
1955 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001956 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 if (stack == null) {
1958 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1959 return;
1960 }
1961 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001962 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966 } finally {
1967 Binder.restoreCallingIdentity(callingId);
1968 }
1969 }
1970
1971 @Override
1972 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001973 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1975 final long callingId = Binder.clearCallingIdentity();
1976 try {
1977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001978 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001979 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 if (task == null) {
1981 return;
1982 }
1983 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001984 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001985 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
1987 }
1988 } finally {
1989 Binder.restoreCallingIdentity(callingId);
1990 }
1991 }
1992
1993 @Override
1994 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 synchronized (mGlobalLock) {
1997 final long ident = Binder.clearCallingIdentity();
1998 try {
1999 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2000 "remove-task");
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 }
2005 }
2006
2007 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002008 public void removeAllVisibleRecentTasks() {
2009 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2010 synchronized (mGlobalLock) {
2011 final long ident = Binder.clearCallingIdentity();
2012 try {
2013 getRecentTasks().removeAllVisibleTasks();
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018 }
2019
2020 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2022 synchronized (mGlobalLock) {
2023 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2024 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 }
2028 return false;
2029 }
2030
2031 @Override
2032 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2033 Intent resultData) {
2034
2035 synchronized (mGlobalLock) {
2036 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2037 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002038 return r.getActivityStack().navigateUpToLocked(
2039 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return false;
2042 }
2043 }
2044
2045 /**
2046 * Attempts to move a task backwards in z-order (the order of activities within the task is
2047 * unchanged).
2048 *
2049 * There are several possible results of this call:
2050 * - if the task is locked, then we will show the lock toast
2051 * - if there is a task behind the provided task, then that task is made visible and resumed as
2052 * this task is moved to the back
2053 * - otherwise, if there are no other tasks in the stack:
2054 * - if this task is in the pinned stack, then we remove the stack completely, which will
2055 * have the effect of moving the task to the top or bottom of the fullscreen stack
2056 * (depending on whether it is visible)
2057 * - otherwise, we simply return home and hide this task
2058 *
2059 * @param token A reference to the activity we wish to move
2060 * @param nonRoot If false then this only works if the activity is the root
2061 * of a task; if true it will work for any activity in a task.
2062 * @return Returns true if the move completed, false if not.
2063 */
2064 @Override
2065 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 synchronized (mGlobalLock) {
2068 final long origId = Binder.clearCallingIdentity();
2069 try {
2070 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 if (task != null) {
2073 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(origId);
2077 }
2078 }
2079 return false;
2080 }
2081
2082 @Override
2083 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 long ident = Binder.clearCallingIdentity();
2086 Rect rect = new Rect();
2087 try {
2088 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002089 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2091 if (task == null) {
2092 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2093 return rect;
2094 }
2095 if (task.getStack() != null) {
2096 // Return the bounds from window manager since it will be adjusted for various
2097 // things like the presense of a docked stack for tasks that aren't resizeable.
2098 task.getWindowContainerBounds(rect);
2099 } else {
2100 // Task isn't in window manager yet since it isn't associated with a stack.
2101 // Return the persist value from activity manager
2102 if (!task.matchParentBounds()) {
2103 rect.set(task.getBounds());
2104 } else if (task.mLastNonFullscreenBounds != null) {
2105 rect.set(task.mLastNonFullscreenBounds);
2106 }
2107 }
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
2112 return rect;
2113 }
2114
2115 @Override
2116 public ActivityManager.TaskDescription getTaskDescription(int id) {
2117 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002120 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2122 if (tr != null) {
2123 return tr.lastTaskDescription;
2124 }
2125 }
2126 return null;
2127 }
2128
2129 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2131 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2132 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2133 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2134 return;
2135 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002136 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002137 synchronized (mGlobalLock) {
2138 final long ident = Binder.clearCallingIdentity();
2139 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002140 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002141 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002142 if (task == null) {
2143 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2144 return;
2145 }
2146
2147 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2148 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2149
2150 if (!task.isActivityTypeStandardOrUndefined()) {
2151 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2152 + " non-standard task " + taskId + " to windowing mode="
2153 + windowingMode);
2154 }
2155
2156 final ActivityStack stack = task.getStack();
2157 if (toTop) {
2158 stack.moveToFront("setTaskWindowingMode", task);
2159 }
2160 stack.setWindowingMode(windowingMode);
2161 } finally {
2162 Binder.restoreCallingIdentity(ident);
2163 }
2164 }
2165 }
2166
2167 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002169 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 ActivityRecord r = getCallingRecordLocked(token);
2171 return r != null ? r.info.packageName : null;
2172 }
2173 }
2174
2175 @Override
2176 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002177 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 ActivityRecord r = getCallingRecordLocked(token);
2179 return r != null ? r.intent.getComponent() : null;
2180 }
2181 }
2182
2183 private ActivityRecord getCallingRecordLocked(IBinder token) {
2184 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2185 if (r == null) {
2186 return null;
2187 }
2188 return r.resultTo;
2189 }
2190
2191 @Override
2192 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194
2195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002198 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 } finally {
2200 Binder.restoreCallingIdentity(origId);
2201 }
2202 }
2203 }
2204
2205 /**
2206 * TODO: Add mController hook
2207 */
2208 @Override
2209 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211
2212 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2213 synchronized (mGlobalLock) {
2214 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2215 false /* fromRecents */);
2216 }
2217 }
2218
2219 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2220 boolean fromRecents) {
2221
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 Binder.getCallingUid(), -1, -1, "Task to front")) {
2224 SafeActivityOptions.abort(options);
2225 return;
2226 }
2227 final long origId = Binder.clearCallingIdentity();
2228 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002229 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 if (task == null) {
2231 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002232 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 return;
2234 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002235 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002237 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 return;
2239 }
2240 ActivityOptions realOptions = options != null
2241 ? options.getOptions(mStackSupervisor)
2242 : null;
2243 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2244 false /* forceNonResizable */);
2245
2246 final ActivityRecord topActivity = task.getTopActivity();
2247 if (topActivity != null) {
2248
2249 // We are reshowing a task, use a starting window to hide the initial draw delay
2250 // so the transition can start earlier.
2251 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2252 true /* taskSwitch */, fromRecents);
2253 }
2254 } finally {
2255 Binder.restoreCallingIdentity(origId);
2256 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 }
2258
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2260 int callingPid, int callingUid, String name) {
2261 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2262 return true;
2263 }
2264
2265 if (getRecentTasks().isCallerRecents(sourceUid)) {
2266 return true;
2267 }
2268
2269 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2270 if (perm == PackageManager.PERMISSION_GRANTED) {
2271 return true;
2272 }
2273 if (checkAllowAppSwitchUid(sourceUid)) {
2274 return true;
2275 }
2276
2277 // If the actual IPC caller is different from the logical source, then
2278 // also see if they are allowed to control app switches.
2279 if (callingUid != -1 && callingUid != sourceUid) {
2280 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2281 if (perm == PackageManager.PERMISSION_GRANTED) {
2282 return true;
2283 }
2284 if (checkAllowAppSwitchUid(callingUid)) {
2285 return true;
2286 }
2287 }
2288
2289 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2290 return false;
2291 }
2292
2293 private boolean checkAllowAppSwitchUid(int uid) {
2294 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2295 if (types != null) {
2296 for (int i = types.size() - 1; i >= 0; i--) {
2297 if (types.valueAt(i).intValue() == uid) {
2298 return true;
2299 }
2300 }
2301 }
2302 return false;
2303 }
2304
2305 @Override
2306 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2307 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2308 "setActivityController()");
2309 synchronized (mGlobalLock) {
2310 mController = controller;
2311 mControllerIsAMonkey = imAMonkey;
2312 Watchdog.getInstance().setActivityController(controller);
2313 }
2314 }
2315
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002316 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002317 synchronized (mGlobalLock) {
2318 return mController != null && mControllerIsAMonkey;
2319 }
2320 }
2321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 @Override
2323 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2324 synchronized (mGlobalLock) {
2325 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2326 }
2327 }
2328
2329 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2331 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2332 }
2333
2334 @Override
2335 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2336 @WindowConfiguration.ActivityType int ignoreActivityType,
2337 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2338 final int callingUid = Binder.getCallingUid();
2339 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2340
2341 synchronized (mGlobalLock) {
2342 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2343
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002345 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002346 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002347 ignoreWindowingMode, callingUid, allowed);
2348 }
2349
2350 return list;
2351 }
2352
2353 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2355 synchronized (mGlobalLock) {
2356 final long origId = Binder.clearCallingIdentity();
2357 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2358 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002359 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 }
2361 Binder.restoreCallingIdentity(origId);
2362 }
2363 }
2364
2365 @Override
2366 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 ActivityStack stack = ActivityRecord.getStackLocked(token);
2369 if (stack != null) {
2370 return stack.willActivityBeVisibleLocked(token);
2371 }
2372 return false;
2373 }
2374 }
2375
2376 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002377 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002378 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 synchronized (mGlobalLock) {
2380 final long ident = Binder.clearCallingIdentity();
2381 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002382 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 if (task == null) {
2384 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2385 return;
2386 }
2387
2388 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2389 + " to stackId=" + stackId + " toTop=" + toTop);
2390
Wale Ogunwaled32da472018-11-16 07:19:28 -08002391 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002392 if (stack == null) {
2393 throw new IllegalStateException(
2394 "moveTaskToStack: No stack for stackId=" + stackId);
2395 }
2396 if (!stack.isActivityTypeStandardOrUndefined()) {
2397 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2398 + taskId + " to stack " + stackId);
2399 }
2400 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2403 }
2404 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2405 "moveTaskToStack");
2406 } finally {
2407 Binder.restoreCallingIdentity(ident);
2408 }
2409 }
2410 }
2411
2412 @Override
2413 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2414 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416
2417 final long ident = Binder.clearCallingIdentity();
2418 try {
2419 synchronized (mGlobalLock) {
2420 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002421 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 if (stack == null) {
2423 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2424 return;
2425 }
2426 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2427 throw new IllegalArgumentException("Stack: " + stackId
2428 + " doesn't support animated resize.");
2429 }
2430 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2431 animationDuration, false /* fromFullscreen */);
2432 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002433 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002434 if (stack == null) {
2435 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2436 return;
2437 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002438 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2440 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2441 }
2442 }
2443 } finally {
2444 Binder.restoreCallingIdentity(ident);
2445 }
2446 }
2447
wilsonshih5c4cf522019-01-25 09:03:47 +08002448 @Override
2449 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2450 int animationDuration) {
2451 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2452
2453 final long ident = Binder.clearCallingIdentity();
2454 try {
2455 synchronized (mGlobalLock) {
2456 if (xOffset == 0 && yOffset == 0) {
2457 return;
2458 }
2459 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2460 if (stack == null) {
2461 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2462 return;
2463 }
2464 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2465 throw new IllegalArgumentException("Stack: " + stackId
2466 + " doesn't support animated resize.");
2467 }
2468 final Rect destBounds = new Rect();
2469 stack.getAnimationOrCurrentBounds(destBounds);
2470 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2471 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2472 return;
2473 }
2474 destBounds.offset(xOffset, yOffset);
2475 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2476 animationDuration, false /* fromFullscreen */);
2477 }
2478 } finally {
2479 Binder.restoreCallingIdentity(ident);
2480 }
2481 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002482 /**
2483 * Moves the specified task to the primary-split-screen stack.
2484 *
2485 * @param taskId Id of task to move.
2486 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2487 * exist already. See
2488 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2489 * and
2490 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2491 * @param toTop If the task and stack should be moved to the top.
2492 * @param animate Whether we should play an animation for the moving the task.
2493 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2494 * stack. Pass {@code null} to use default bounds.
2495 * @param showRecents If the recents activity should be shown on the other side of the task
2496 * going into split-screen mode.
2497 */
2498 @Override
2499 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2500 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002501 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 "setTaskWindowingModeSplitScreenPrimary()");
2503 synchronized (mGlobalLock) {
2504 final long ident = Binder.clearCallingIdentity();
2505 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002506 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002507 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 if (task == null) {
2509 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2510 return false;
2511 }
2512 if (DEBUG_STACK) Slog.d(TAG_STACK,
2513 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2514 + " to createMode=" + createMode + " toTop=" + toTop);
2515 if (!task.isActivityTypeStandardOrUndefined()) {
2516 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2517 + " non-standard task " + taskId + " to split-screen windowing mode");
2518 }
2519
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002520 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 final int windowingMode = task.getWindowingMode();
2522 final ActivityStack stack = task.getStack();
2523 if (toTop) {
2524 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2525 }
2526 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002527 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2528 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002529 return windowingMode != task.getWindowingMode();
2530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
2533 }
2534 }
2535
2536 /**
2537 * Removes stacks in the input windowing modes from the system if they are of activity type
2538 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2539 */
2540 @Override
2541 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002542 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 "removeStacksInWindowingModes()");
2544
2545 synchronized (mGlobalLock) {
2546 final long ident = Binder.clearCallingIdentity();
2547 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
2552 }
2553 }
2554
2555 @Override
2556 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 "removeStacksWithActivityTypes()");
2559
2560 synchronized (mGlobalLock) {
2561 final long ident = Binder.clearCallingIdentity();
2562 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002569
2570 @Override
2571 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2572 int userId) {
2573 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2575 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002577 final boolean detailed = checkGetTasksPermission(
2578 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2579 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002580 == PackageManager.PERMISSION_GRANTED;
2581
2582 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002583 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002584 callingUid);
2585 }
2586 }
2587
2588 @Override
2589 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002590 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002595 }
2596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
2599 }
2600
2601 @Override
2602 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 long ident = Binder.clearCallingIdentity();
2605 try {
2606 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002607 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608 }
2609 } finally {
2610 Binder.restoreCallingIdentity(ident);
2611 }
2612 }
2613
2614 @Override
2615 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002616 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002617 final long callingUid = Binder.getCallingUid();
2618 final long origId = Binder.clearCallingIdentity();
2619 try {
2620 synchronized (mGlobalLock) {
2621 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002622 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002623 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2624 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(origId);
2628 }
2629 }
2630
2631 @Override
2632 public void startLockTaskModeByToken(IBinder token) {
2633 synchronized (mGlobalLock) {
2634 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2635 if (r == null) {
2636 return;
2637 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002638 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639 }
2640 }
2641
2642 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002643 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002644 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002645 // This makes inner call to look as if it was initiated by system.
2646 long ident = Binder.clearCallingIdentity();
2647 try {
2648 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002649 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002650 MATCH_TASK_IN_STACKS_ONLY);
2651 if (task == null) {
2652 return;
2653 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654
2655 // When starting lock task mode the stack must be in front and focused
2656 task.getStack().moveToFront("startSystemLockTaskMode");
2657 startLockTaskModeLocked(task, true /* isSystemCaller */);
2658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(ident);
2661 }
2662 }
2663
2664 @Override
2665 public void stopLockTaskModeByToken(IBinder token) {
2666 synchronized (mGlobalLock) {
2667 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2668 if (r == null) {
2669 return;
2670 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002671 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002672 }
2673 }
2674
2675 /**
2676 * This API should be called by SystemUI only when user perform certain action to dismiss
2677 * lock task mode. We should only dismiss pinned lock task mode in this case.
2678 */
2679 @Override
2680 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002681 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2683 }
2684
2685 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2686 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2687 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2688 return;
2689 }
2690
Wale Ogunwaled32da472018-11-16 07:19:28 -08002691 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002692 if (stack == null || task != stack.topTask()) {
2693 throw new IllegalArgumentException("Invalid task, not in foreground");
2694 }
2695
2696 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2697 // system or a specific app.
2698 // * System-initiated requests will only start the pinned mode (screen pinning)
2699 // * App-initiated requests
2700 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2701 // - will start the pinned mode, otherwise
2702 final int callingUid = Binder.getCallingUid();
2703 long ident = Binder.clearCallingIdentity();
2704 try {
2705 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002706 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002707
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002708 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713
2714 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2715 final int callingUid = Binder.getCallingUid();
2716 long ident = Binder.clearCallingIdentity();
2717 try {
2718 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002719 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 }
2721 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2722 // task and jumping straight into a call in the case of emergency call back.
2723 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2724 if (tm != null) {
2725 tm.showInCallScreen(false);
2726 }
2727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731
2732 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002733 public void updateLockTaskPackages(int userId, String[] packages) {
2734 final int callingUid = Binder.getCallingUid();
2735 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2736 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2737 "updateLockTaskPackages()");
2738 }
2739 synchronized (this) {
2740 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2741 + Arrays.toString(packages));
2742 getLockTaskController().updateLockTaskPackages(userId, packages);
2743 }
2744 }
2745
2746 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 public boolean isInLockTaskMode() {
2748 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2749 }
2750
2751 @Override
2752 public int getLockTaskModeState() {
2753 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002754 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 }
2756 }
2757
2758 @Override
2759 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2760 synchronized (mGlobalLock) {
2761 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2762 if (r != null) {
2763 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002764 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002766 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 }
2769 }
2770
2771 @Override
2772 public Bundle getActivityOptions(IBinder token) {
2773 final long origId = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mGlobalLock) {
2776 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2777 if (r != null) {
2778 final ActivityOptions activityOptions = r.takeOptionsLocked();
2779 return activityOptions == null ? null : activityOptions.toBundle();
2780 }
2781 return null;
2782 }
2783 } finally {
2784 Binder.restoreCallingIdentity(origId);
2785 }
2786 }
2787
2788 @Override
2789 public List<IBinder> getAppTasks(String callingPackage) {
2790 int callingUid = Binder.getCallingUid();
2791 long ident = Binder.clearCallingIdentity();
2792 try {
2793 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002794 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
2799 }
2800
2801 @Override
2802 public void finishVoiceTask(IVoiceInteractionSession session) {
2803 synchronized (mGlobalLock) {
2804 final long origId = Binder.clearCallingIdentity();
2805 try {
2806 // TODO: VI Consider treating local voice interactions and voice tasks
2807 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002808 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 } finally {
2810 Binder.restoreCallingIdentity(origId);
2811 }
2812 }
2813
2814 }
2815
2816 @Override
2817 public boolean isTopOfTask(IBinder token) {
2818 synchronized (mGlobalLock) {
2819 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002820 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 }
2823
2824 @Override
2825 public void notifyLaunchTaskBehindComplete(IBinder token) {
2826 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2827 }
2828
2829 @Override
2830 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002831 mH.post(() -> {
2832 synchronized (mGlobalLock) {
2833 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002834 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002835 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002836 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002837 } catch (RemoteException e) {
2838 }
2839 }
2840 }
2841
2842 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 }
2844
2845 /** Called from an app when assist data is ready. */
2846 @Override
2847 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2848 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002849 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 synchronized (pae) {
2851 pae.result = extras;
2852 pae.structure = structure;
2853 pae.content = content;
2854 if (referrer != null) {
2855 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2856 }
2857 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002858 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002859 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2860 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002861 structure.setHomeActivity(pae.isHome);
2862 }
2863 pae.haveResult = true;
2864 pae.notifyAll();
2865 if (pae.intent == null && pae.receiver == null) {
2866 // Caller is just waiting for the result.
2867 return;
2868 }
2869 }
2870 // We are now ready to launch the assist activity.
2871 IAssistDataReceiver sendReceiver = null;
2872 Bundle sendBundle = null;
2873 synchronized (mGlobalLock) {
2874 buildAssistBundleLocked(pae, extras);
2875 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002876 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 if (!exists) {
2878 // Timed out.
2879 return;
2880 }
2881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002882 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 // Caller wants result sent back to them.
2884 sendBundle = new Bundle();
2885 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2886 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2887 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2888 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2889 }
2890 }
2891 if (sendReceiver != null) {
2892 try {
2893 sendReceiver.onHandleAssistData(sendBundle);
2894 } catch (RemoteException e) {
2895 }
2896 return;
2897 }
2898
2899 final long ident = Binder.clearCallingIdentity();
2900 try {
2901 if (TextUtils.equals(pae.intent.getAction(),
2902 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2903 pae.intent.putExtras(pae.extras);
2904 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2905 } else {
2906 pae.intent.replaceExtras(pae.extras);
2907 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2908 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2909 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002910 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911
2912 try {
2913 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2914 } catch (ActivityNotFoundException e) {
2915 Slog.w(TAG, "No activity to handle assist action.", e);
2916 }
2917 }
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
2923 @Override
2924 public int addAppTask(IBinder activityToken, Intent intent,
2925 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2926 final int callingUid = Binder.getCallingUid();
2927 final long callingIdent = Binder.clearCallingIdentity();
2928
2929 try {
2930 synchronized (mGlobalLock) {
2931 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2932 if (r == null) {
2933 throw new IllegalArgumentException("Activity does not exist; token="
2934 + activityToken);
2935 }
2936 ComponentName comp = intent.getComponent();
2937 if (comp == null) {
2938 throw new IllegalArgumentException("Intent " + intent
2939 + " must specify explicit component");
2940 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002941 if (thumbnail.getWidth() != mThumbnailWidth
2942 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 throw new IllegalArgumentException("Bad thumbnail size: got "
2944 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002945 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 if (intent.getSelector() != null) {
2948 intent.setSelector(null);
2949 }
2950 if (intent.getSourceBounds() != null) {
2951 intent.setSourceBounds(null);
2952 }
2953 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2954 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2955 // The caller has added this as an auto-remove task... that makes no
2956 // sense, so turn off auto-remove.
2957 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2958 }
2959 }
2960 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2961 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2962 if (ainfo.applicationInfo.uid != callingUid) {
2963 throw new SecurityException(
2964 "Can't add task for another application: target uid="
2965 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2966 }
2967
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002968 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002970 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002972 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 // The app has too many tasks already and we can't add any more
2974 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2975 return INVALID_TASK_ID;
2976 }
2977 task.lastTaskDescription.copyFrom(description);
2978
2979 // TODO: Send the thumbnail to WM to store it.
2980
2981 return task.taskId;
2982 }
2983 } finally {
2984 Binder.restoreCallingIdentity(callingIdent);
2985 }
2986 }
2987
2988 @Override
2989 public Point getAppTaskThumbnailSize() {
2990 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002991 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void setTaskResizeable(int taskId, int resizeableMode) {
2997 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002998 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3000 if (task == null) {
3001 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3002 return;
3003 }
3004 task.setResizeMode(resizeableMode);
3005 }
3006 }
3007
3008 @Override
3009 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 long ident = Binder.clearCallingIdentity();
3012 try {
3013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003014 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003015 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 if (task == null) {
3017 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3018 return;
3019 }
3020 // Place the task in the right stack if it isn't there already based on
3021 // the requested bounds.
3022 // The stack transition logic is:
3023 // - a null bounds on a freeform task moves that task to fullscreen
3024 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3025 // that task to freeform
3026 // - otherwise the task is not moved
3027 ActivityStack stack = task.getStack();
3028 if (!task.getWindowConfiguration().canResizeTask()) {
3029 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3030 }
3031 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3032 stack = stack.getDisplay().getOrCreateStack(
3033 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3034 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3035 stack = stack.getDisplay().getOrCreateStack(
3036 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3037 }
3038
3039 // Reparent the task to the right stack if necessary
3040 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3041 if (stack != task.getStack()) {
3042 // Defer resume until the task is resized below
3043 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3044 DEFER_RESUME, "resizeTask");
3045 preserveWindow = false;
3046 }
3047
3048 // After reparenting (which only resizes the task to the stack bounds), resize the
3049 // task to the actual bounds provided
3050 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3051 }
3052 } finally {
3053 Binder.restoreCallingIdentity(ident);
3054 }
3055 }
3056
3057 @Override
3058 public boolean releaseActivityInstance(IBinder token) {
3059 synchronized (mGlobalLock) {
3060 final long origId = Binder.clearCallingIdentity();
3061 try {
3062 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3063 if (r == null) {
3064 return false;
3065 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003066 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 } finally {
3068 Binder.restoreCallingIdentity(origId);
3069 }
3070 }
3071 }
3072
3073 @Override
3074 public void releaseSomeActivities(IApplicationThread appInt) {
3075 synchronized (mGlobalLock) {
3076 final long origId = Binder.clearCallingIdentity();
3077 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003078 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003079 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 } finally {
3081 Binder.restoreCallingIdentity(origId);
3082 }
3083 }
3084 }
3085
3086 @Override
3087 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003088 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003089 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 != PackageManager.PERMISSION_GRANTED) {
3091 throw new SecurityException("Requires permission "
3092 + android.Manifest.permission.DEVICE_POWER);
3093 }
3094
3095 synchronized (mGlobalLock) {
3096 long ident = Binder.clearCallingIdentity();
3097 if (mKeyguardShown != keyguardShowing) {
3098 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003099 final Message msg = PooledLambda.obtainMessage(
3100 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3101 keyguardShowing);
3102 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 }
3104 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003105 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003106 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 } finally {
3108 Binder.restoreCallingIdentity(ident);
3109 }
3110 }
3111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003112 mH.post(() -> {
3113 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3114 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3115 }
3116 });
3117 }
3118
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003119 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 mH.post(() -> {
3121 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3122 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3123 }
3124 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 }
3126
3127 @Override
3128 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003129 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3130 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131
3132 final File passedIconFile = new File(filePath);
3133 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3134 passedIconFile.getName());
3135 if (!legitIconFile.getPath().equals(filePath)
3136 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3137 throw new IllegalArgumentException("Bad file path: " + filePath
3138 + " passed for userId " + userId);
3139 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003140 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141 }
3142
3143 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003144 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3146 final ActivityOptions activityOptions = safeOptions != null
3147 ? safeOptions.getOptions(mStackSupervisor)
3148 : null;
3149 if (activityOptions == null
3150 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3151 || activityOptions.getCustomInPlaceResId() == 0) {
3152 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3153 "with valid animation");
3154 }
lumark588a3e82018-07-20 18:53:54 +08003155 // Get top display of front most application.
3156 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3157 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003158 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3159 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3160 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003161 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003162 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003163 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 }
3165
3166 @Override
3167 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003168 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 synchronized (mGlobalLock) {
3170 final long ident = Binder.clearCallingIdentity();
3171 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003172 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 if (stack == null) {
3174 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3175 return;
3176 }
3177 if (!stack.isActivityTypeStandardOrUndefined()) {
3178 throw new IllegalArgumentException(
3179 "Removing non-standard stack is not allowed.");
3180 }
3181 mStackSupervisor.removeStack(stack);
3182 } finally {
3183 Binder.restoreCallingIdentity(ident);
3184 }
3185 }
3186 }
3187
3188 @Override
3189 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003190 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191
3192 synchronized (mGlobalLock) {
3193 final long ident = Binder.clearCallingIdentity();
3194 try {
3195 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3196 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003197 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 } finally {
3199 Binder.restoreCallingIdentity(ident);
3200 }
3201 }
3202 }
3203
3204 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 public void exitFreeformMode(IBinder token) {
3206 synchronized (mGlobalLock) {
3207 long ident = Binder.clearCallingIdentity();
3208 try {
3209 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3210 if (r == null) {
3211 throw new IllegalArgumentException(
3212 "exitFreeformMode: No activity record matching token=" + token);
3213 }
3214
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003215 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 if (stack == null || !stack.inFreeformWindowingMode()) {
3217 throw new IllegalStateException(
3218 "exitFreeformMode: You can only go fullscreen from freeform.");
3219 }
3220
3221 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3222 } finally {
3223 Binder.restoreCallingIdentity(ident);
3224 }
3225 }
3226 }
3227
3228 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3229 @Override
3230 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003231 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003232 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003233 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 }
3235
3236 /** Unregister a task stack listener so that it stops receiving callbacks. */
3237 @Override
3238 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003239 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003241 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 }
3243
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 @Override
3245 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3246 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3247 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3248 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3249 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3250 }
3251
3252 @Override
3253 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3254 IBinder activityToken, int flags) {
3255 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3256 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3257 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3258 }
3259
3260 @Override
3261 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3262 Bundle args) {
3263 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3264 true /* focused */, true /* newSessionId */, userHandle, args,
3265 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3266 }
3267
3268 @Override
3269 public Bundle getAssistContextExtras(int requestType) {
3270 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3271 null, null, true /* focused */, true /* newSessionId */,
3272 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3273 if (pae == null) {
3274 return null;
3275 }
3276 synchronized (pae) {
3277 while (!pae.haveResult) {
3278 try {
3279 pae.wait();
3280 } catch (InterruptedException e) {
3281 }
3282 }
3283 }
3284 synchronized (mGlobalLock) {
3285 buildAssistBundleLocked(pae, pae.result);
3286 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003287 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288 }
3289 return pae.extras;
3290 }
3291
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 /**
3293 * Binder IPC calls go through the public entry point.
3294 * This can be called with or without the global lock held.
3295 */
3296 private static int checkCallingPermission(String permission) {
3297 return checkPermission(
3298 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3299 }
3300
3301 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003302 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003303 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3304 mAmInternal.enforceCallingPermission(permission, func);
3305 }
3306 }
3307
3308 @VisibleForTesting
3309 int checkGetTasksPermission(String permission, int pid, int uid) {
3310 return checkPermission(permission, pid, uid);
3311 }
3312
3313 static int checkPermission(String permission, int pid, int uid) {
3314 if (permission == null) {
3315 return PackageManager.PERMISSION_DENIED;
3316 }
3317 return checkComponentPermission(permission, pid, uid, -1, true);
3318 }
3319
Wale Ogunwale214f3482018-10-04 11:00:47 -07003320 public static int checkComponentPermission(String permission, int pid, int uid,
3321 int owningUid, boolean exported) {
3322 return ActivityManagerService.checkComponentPermission(
3323 permission, pid, uid, owningUid, exported);
3324 }
3325
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3327 if (getRecentTasks().isCallerRecents(callingUid)) {
3328 // Always allow the recents component to get tasks
3329 return true;
3330 }
3331
3332 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3333 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3334 if (!allowed) {
3335 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3336 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3337 // Temporary compatibility: some existing apps on the system image may
3338 // still be requesting the old permission and not switched to the new
3339 // one; if so, we'll still allow them full access. This means we need
3340 // to see if they are holding the old permission and are a system app.
3341 try {
3342 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3343 allowed = true;
3344 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3345 + " is using old GET_TASKS but privileged; allowing");
3346 }
3347 } catch (RemoteException e) {
3348 }
3349 }
3350 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3351 + " does not hold REAL_GET_TASKS; limiting output");
3352 }
3353 return allowed;
3354 }
3355
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3357 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3358 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3359 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003360 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 "enqueueAssistContext()");
3362
3363 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003364 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 if (activity == null) {
3366 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3367 return null;
3368 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003369 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3371 return null;
3372 }
3373 if (focused) {
3374 if (activityToken != null) {
3375 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3376 if (activity != caller) {
3377 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3378 + " is not current top " + activity);
3379 return null;
3380 }
3381 }
3382 } else {
3383 activity = ActivityRecord.forTokenLocked(activityToken);
3384 if (activity == null) {
3385 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3386 + " couldn't be found");
3387 return null;
3388 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003389 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3391 return null;
3392 }
3393 }
3394
3395 PendingAssistExtras pae;
3396 Bundle extras = new Bundle();
3397 if (args != null) {
3398 extras.putAll(args);
3399 }
3400 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003401 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402
3403 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3404 userHandle);
3405 pae.isHome = activity.isActivityTypeHome();
3406
3407 // Increment the sessionId if necessary
3408 if (newSessionId) {
3409 mViSessionId++;
3410 }
3411 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003412 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3413 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003415 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 } catch (RemoteException e) {
3417 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3418 return null;
3419 }
3420 return pae;
3421 }
3422 }
3423
3424 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3425 if (result != null) {
3426 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3427 }
3428 if (pae.hint != null) {
3429 pae.extras.putBoolean(pae.hint, true);
3430 }
3431 }
3432
3433 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3434 IAssistDataReceiver receiver;
3435 synchronized (mGlobalLock) {
3436 mPendingAssistExtras.remove(pae);
3437 receiver = pae.receiver;
3438 }
3439 if (receiver != null) {
3440 // Caller wants result sent back to them.
3441 Bundle sendBundle = new Bundle();
3442 // At least return the receiver extras
3443 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3444 try {
3445 pae.receiver.onHandleAssistData(sendBundle);
3446 } catch (RemoteException e) {
3447 }
3448 }
3449 }
3450
3451 public class PendingAssistExtras extends Binder implements Runnable {
3452 public final ActivityRecord activity;
3453 public boolean isHome;
3454 public final Bundle extras;
3455 public final Intent intent;
3456 public final String hint;
3457 public final IAssistDataReceiver receiver;
3458 public final int userHandle;
3459 public boolean haveResult = false;
3460 public Bundle result = null;
3461 public AssistStructure structure = null;
3462 public AssistContent content = null;
3463 public Bundle receiverExtras;
3464
3465 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3466 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3467 int _userHandle) {
3468 activity = _activity;
3469 extras = _extras;
3470 intent = _intent;
3471 hint = _hint;
3472 receiver = _receiver;
3473 receiverExtras = _receiverExtras;
3474 userHandle = _userHandle;
3475 }
3476
3477 @Override
3478 public void run() {
3479 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3480 synchronized (this) {
3481 haveResult = true;
3482 notifyAll();
3483 }
3484 pendingAssistExtrasTimedOut(this);
3485 }
3486 }
3487
3488 @Override
3489 public boolean isAssistDataAllowedOnCurrentActivity() {
3490 int userId;
3491 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003492 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003493 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3494 return false;
3495 }
3496
3497 final ActivityRecord activity = focusedStack.getTopActivity();
3498 if (activity == null) {
3499 return false;
3500 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003501 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 }
3503 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3504 }
3505
3506 @Override
3507 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3508 long ident = Binder.clearCallingIdentity();
3509 try {
3510 synchronized (mGlobalLock) {
3511 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003512 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003513 if (top != caller) {
3514 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3515 + " is not current top " + top);
3516 return false;
3517 }
3518 if (!top.nowVisible) {
3519 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3520 + " is not visible");
3521 return false;
3522 }
3523 }
3524 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3525 token);
3526 } finally {
3527 Binder.restoreCallingIdentity(ident);
3528 }
3529 }
3530
3531 @Override
3532 public boolean isRootVoiceInteraction(IBinder token) {
3533 synchronized (mGlobalLock) {
3534 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3535 if (r == null) {
3536 return false;
3537 }
3538 return r.rootVoiceInteraction;
3539 }
3540 }
3541
Wale Ogunwalef6733932018-06-27 05:14:34 -07003542 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3543 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3544 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3545 if (activityToCallback == null) return;
3546 activityToCallback.setVoiceSessionLocked(voiceSession);
3547
3548 // Inform the activity
3549 try {
3550 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3551 voiceInteractor);
3552 long token = Binder.clearCallingIdentity();
3553 try {
3554 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3555 } finally {
3556 Binder.restoreCallingIdentity(token);
3557 }
3558 // TODO: VI Should we cache the activity so that it's easier to find later
3559 // rather than scan through all the stacks and activities?
3560 } catch (RemoteException re) {
3561 activityToCallback.clearVoiceSessionLocked();
3562 // TODO: VI Should this terminate the voice session?
3563 }
3564 }
3565
3566 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3567 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3568 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3569 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3570 boolean wasRunningVoice = mRunningVoice != null;
3571 mRunningVoice = session;
3572 if (!wasRunningVoice) {
3573 mVoiceWakeLock.acquire();
3574 updateSleepIfNeededLocked();
3575 }
3576 }
3577 }
3578
3579 void finishRunningVoiceLocked() {
3580 if (mRunningVoice != null) {
3581 mRunningVoice = null;
3582 mVoiceWakeLock.release();
3583 updateSleepIfNeededLocked();
3584 }
3585 }
3586
3587 @Override
3588 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3589 synchronized (mGlobalLock) {
3590 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3591 if (keepAwake) {
3592 mVoiceWakeLock.acquire();
3593 } else {
3594 mVoiceWakeLock.release();
3595 }
3596 }
3597 }
3598 }
3599
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600 @Override
3601 public ComponentName getActivityClassForToken(IBinder token) {
3602 synchronized (mGlobalLock) {
3603 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3604 if (r == null) {
3605 return null;
3606 }
3607 return r.intent.getComponent();
3608 }
3609 }
3610
3611 @Override
3612 public String getPackageForToken(IBinder token) {
3613 synchronized (mGlobalLock) {
3614 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3615 if (r == null) {
3616 return null;
3617 }
3618 return r.packageName;
3619 }
3620 }
3621
3622 @Override
3623 public void showLockTaskEscapeMessage(IBinder token) {
3624 synchronized (mGlobalLock) {
3625 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3626 if (r == null) {
3627 return;
3628 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003629 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003630 }
3631 }
3632
3633 @Override
3634 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003635 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 final long token = Binder.clearCallingIdentity();
3637 try {
3638 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003639 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640 }
3641 } finally {
3642 Binder.restoreCallingIdentity(token);
3643 }
3644 }
3645
3646 /**
3647 * Try to place task to provided position. The final position might be different depending on
3648 * current user and stacks state. The task will be moved to target stack if it's currently in
3649 * different stack.
3650 */
3651 @Override
3652 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003653 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 synchronized (mGlobalLock) {
3655 long ident = Binder.clearCallingIdentity();
3656 try {
3657 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3658 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003659 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003660 if (task == null) {
3661 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3662 + taskId);
3663 }
3664
Wale Ogunwaled32da472018-11-16 07:19:28 -08003665 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003666
3667 if (stack == null) {
3668 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3669 + stackId);
3670 }
3671 if (!stack.isActivityTypeStandardOrUndefined()) {
3672 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3673 + " the position of task " + taskId + " in/to non-standard stack");
3674 }
3675
3676 // TODO: Have the callers of this API call a separate reparent method if that is
3677 // what they intended to do vs. having this method also do reparenting.
3678 if (task.getStack() == stack) {
3679 // Change position in current stack.
3680 stack.positionChildAt(task, position);
3681 } else {
3682 // Reparent to new stack.
3683 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3684 !DEFER_RESUME, "positionTaskInStack");
3685 }
3686 } finally {
3687 Binder.restoreCallingIdentity(ident);
3688 }
3689 }
3690 }
3691
3692 @Override
3693 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3694 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3695 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3696 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3697 synchronized (mGlobalLock) {
3698 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3699 if (record == null) {
3700 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3701 + "found for: " + token);
3702 }
3703 record.setSizeConfigurations(horizontalSizeConfiguration,
3704 verticalSizeConfigurations, smallestSizeConfigurations);
3705 }
3706 }
3707
3708 /**
3709 * Dismisses split-screen multi-window mode.
3710 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3711 */
3712 @Override
3713 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003714 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3716 final long ident = Binder.clearCallingIdentity();
3717 try {
3718 synchronized (mGlobalLock) {
3719 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003720 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 if (stack == null) {
3722 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3723 return;
3724 }
3725
3726 if (toTop) {
3727 // Caller wants the current split-screen primary stack to be the top stack after
3728 // it goes fullscreen, so move it to the front.
3729 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003730 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 // In this case the current split-screen primary stack shouldn't be the top
3732 // stack after it goes fullscreen, but it current has focus, so we move the
3733 // focus to the top-most split-screen secondary stack next to it.
3734 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3735 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3736 if (otherStack != null) {
3737 otherStack.moveToFront("dismissSplitScreenMode_other");
3738 }
3739 }
3740
Evan Rosky10475742018-09-05 19:02:48 -07003741 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 }
3743 } finally {
3744 Binder.restoreCallingIdentity(ident);
3745 }
3746 }
3747
3748 /**
3749 * Dismisses Pip
3750 * @param animate True if the dismissal should be animated.
3751 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3752 * default animation duration should be used.
3753 */
3754 @Override
3755 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003756 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003757 final long ident = Binder.clearCallingIdentity();
3758 try {
3759 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003760 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003761 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003762 if (stack == null) {
3763 Slog.w(TAG, "dismissPip: pinned stack not found.");
3764 return;
3765 }
3766 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3767 throw new IllegalArgumentException("Stack: " + stack
3768 + " doesn't support animated resize.");
3769 }
3770 if (animate) {
3771 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3772 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3773 } else {
3774 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3775 }
3776 }
3777 } finally {
3778 Binder.restoreCallingIdentity(ident);
3779 }
3780 }
3781
3782 @Override
3783 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003784 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 synchronized (mGlobalLock) {
3786 mSuppressResizeConfigChanges = suppress;
3787 }
3788 }
3789
3790 /**
3791 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3792 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3793 * activity and clearing the task at the same time.
3794 */
3795 @Override
3796 // TODO: API should just be about changing windowing modes...
3797 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003798 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003799 "moveTasksToFullscreenStack()");
3800 synchronized (mGlobalLock) {
3801 final long origId = Binder.clearCallingIdentity();
3802 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003803 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 if (stack != null){
3805 if (!stack.isActivityTypeStandardOrUndefined()) {
3806 throw new IllegalArgumentException(
3807 "You can't move tasks from non-standard stacks.");
3808 }
3809 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3810 }
3811 } finally {
3812 Binder.restoreCallingIdentity(origId);
3813 }
3814 }
3815 }
3816
3817 /**
3818 * Moves the top activity in the input stackId to the pinned stack.
3819 *
3820 * @param stackId Id of stack to move the top activity to pinned stack.
3821 * @param bounds Bounds to use for pinned stack.
3822 *
3823 * @return True if the top activity of the input stack was successfully moved to the pinned
3824 * stack.
3825 */
3826 @Override
3827 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003828 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 "moveTopActivityToPinnedStack()");
3830 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003831 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003832 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3833 + "Device doesn't support picture-in-picture mode");
3834 }
3835
3836 long ident = Binder.clearCallingIdentity();
3837 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003838 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 } finally {
3840 Binder.restoreCallingIdentity(ident);
3841 }
3842 }
3843 }
3844
3845 @Override
3846 public boolean isInMultiWindowMode(IBinder token) {
3847 final long origId = Binder.clearCallingIdentity();
3848 try {
3849 synchronized (mGlobalLock) {
3850 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3851 if (r == null) {
3852 return false;
3853 }
3854 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3855 return r.inMultiWindowMode();
3856 }
3857 } finally {
3858 Binder.restoreCallingIdentity(origId);
3859 }
3860 }
3861
3862 @Override
3863 public boolean isInPictureInPictureMode(IBinder token) {
3864 final long origId = Binder.clearCallingIdentity();
3865 try {
3866 synchronized (mGlobalLock) {
3867 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3868 }
3869 } finally {
3870 Binder.restoreCallingIdentity(origId);
3871 }
3872 }
3873
3874 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003875 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3876 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003877 return false;
3878 }
3879
3880 // If we are animating to fullscreen then we have already dispatched the PIP mode
3881 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003882 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3883 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884 }
3885
3886 @Override
3887 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3888 final long origId = Binder.clearCallingIdentity();
3889 try {
3890 synchronized (mGlobalLock) {
3891 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3892 "enterPictureInPictureMode", token, params);
3893
3894 // If the activity is already in picture in picture mode, then just return early
3895 if (isInPictureInPictureMode(r)) {
3896 return true;
3897 }
3898
3899 // Activity supports picture-in-picture, now check that we can enter PiP at this
3900 // point, if it is
3901 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3902 false /* beforeStopping */)) {
3903 return false;
3904 }
3905
3906 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003907 synchronized (mGlobalLock) {
3908 // Only update the saved args from the args that are set
3909 r.pictureInPictureArgs.copyOnlySet(params);
3910 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3911 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3912 // Adjust the source bounds by the insets for the transition down
3913 final Rect sourceBounds = new Rect(
3914 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003915 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003916 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003917 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003918 stack.setPictureInPictureAspectRatio(aspectRatio);
3919 stack.setPictureInPictureActions(actions);
3920 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3921 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3922 logPictureInPictureArgs(params);
3923 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 };
3925
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003926 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 // If the keyguard is showing or occluded, then try and dismiss it before
3928 // entering picture-in-picture (this will prompt the user to authenticate if the
3929 // device is currently locked).
3930 dismissKeyguard(token, new KeyguardDismissCallback() {
3931 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003932 public void onDismissSucceeded() {
3933 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 }
3935 }, null /* message */);
3936 } else {
3937 // Enter picture in picture immediately otherwise
3938 enterPipRunnable.run();
3939 }
3940 return true;
3941 }
3942 } finally {
3943 Binder.restoreCallingIdentity(origId);
3944 }
3945 }
3946
3947 @Override
3948 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3949 final long origId = Binder.clearCallingIdentity();
3950 try {
3951 synchronized (mGlobalLock) {
3952 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3953 "setPictureInPictureParams", token, params);
3954
3955 // Only update the saved args from the args that are set
3956 r.pictureInPictureArgs.copyOnlySet(params);
3957 if (r.inPinnedWindowingMode()) {
3958 // If the activity is already in picture-in-picture, update the pinned stack now
3959 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3960 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003961 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 if (!stack.isAnimatingBoundsToFullscreen()) {
3963 stack.setPictureInPictureAspectRatio(
3964 r.pictureInPictureArgs.getAspectRatio());
3965 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3966 }
3967 }
3968 logPictureInPictureArgs(params);
3969 }
3970 } finally {
3971 Binder.restoreCallingIdentity(origId);
3972 }
3973 }
3974
3975 @Override
3976 public int getMaxNumPictureInPictureActions(IBinder token) {
3977 // Currently, this is a static constant, but later, we may change this to be dependent on
3978 // the context of the activity
3979 return 3;
3980 }
3981
3982 private void logPictureInPictureArgs(PictureInPictureParams params) {
3983 if (params.hasSetActions()) {
3984 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3985 params.getActions().size());
3986 }
3987 if (params.hasSetAspectRatio()) {
3988 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3989 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3990 MetricsLogger.action(lm);
3991 }
3992 }
3993
3994 /**
3995 * Checks the state of the system and the activity associated with the given {@param token} to
3996 * verify that picture-in-picture is supported for that activity.
3997 *
3998 * @return the activity record for the given {@param token} if all the checks pass.
3999 */
4000 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4001 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004002 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 throw new IllegalStateException(caller
4004 + ": Device doesn't support picture-in-picture mode.");
4005 }
4006
4007 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4008 if (r == null) {
4009 throw new IllegalStateException(caller
4010 + ": Can't find activity for token=" + token);
4011 }
4012
4013 if (!r.supportsPictureInPicture()) {
4014 throw new IllegalStateException(caller
4015 + ": Current activity does not support picture-in-picture.");
4016 }
4017
4018 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004019 && !mWindowManager.isValidPictureInPictureAspectRatio(
4020 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 final float minAspectRatio = mContext.getResources().getFloat(
4022 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4023 final float maxAspectRatio = mContext.getResources().getFloat(
4024 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4025 throw new IllegalArgumentException(String.format(caller
4026 + ": Aspect ratio is too extreme (must be between %f and %f).",
4027 minAspectRatio, maxAspectRatio));
4028 }
4029
4030 // Truncate the number of actions if necessary
4031 params.truncateActions(getMaxNumPictureInPictureActions(token));
4032
4033 return r;
4034 }
4035
4036 @Override
4037 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004038 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004039 synchronized (mGlobalLock) {
4040 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4041 if (r == null) {
4042 throw new IllegalArgumentException("Activity does not exist; token="
4043 + activityToken);
4044 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004045 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 }
4047 }
4048
4049 @Override
4050 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4051 Rect tempDockedTaskInsetBounds,
4052 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004053 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004054 long ident = Binder.clearCallingIdentity();
4055 try {
4056 synchronized (mGlobalLock) {
4057 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4058 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4059 PRESERVE_WINDOWS);
4060 }
4061 } finally {
4062 Binder.restoreCallingIdentity(ident);
4063 }
4064 }
4065
4066 @Override
4067 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004068 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 final long ident = Binder.clearCallingIdentity();
4070 try {
4071 synchronized (mGlobalLock) {
4072 mStackSupervisor.setSplitScreenResizing(resizing);
4073 }
4074 } finally {
4075 Binder.restoreCallingIdentity(ident);
4076 }
4077 }
4078
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004079 /**
4080 * Check that we have the features required for VR-related API calls, and throw an exception if
4081 * not.
4082 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004083 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004084 if (!mContext.getPackageManager().hasSystemFeature(
4085 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4086 throw new UnsupportedOperationException("VR mode not supported on this device!");
4087 }
4088 }
4089
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 @Override
4091 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004092 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093
4094 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4095
4096 ActivityRecord r;
4097 synchronized (mGlobalLock) {
4098 r = ActivityRecord.isInStackLocked(token);
4099 }
4100
4101 if (r == null) {
4102 throw new IllegalArgumentException();
4103 }
4104
4105 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004106 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 VrManagerInternal.NO_ERROR) {
4108 return err;
4109 }
4110
4111 // Clear the binder calling uid since this path may call moveToTask().
4112 final long callingId = Binder.clearCallingIdentity();
4113 try {
4114 synchronized (mGlobalLock) {
4115 r.requestedVrComponent = (enabled) ? packageName : null;
4116
4117 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004118 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004119 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 }
4121 return 0;
4122 }
4123 } finally {
4124 Binder.restoreCallingIdentity(callingId);
4125 }
4126 }
4127
4128 @Override
4129 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4130 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4131 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004132 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4134 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4135 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004136 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004137 || activity.voiceSession != null) {
4138 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4139 return;
4140 }
4141 if (activity.pendingVoiceInteractionStart) {
4142 Slog.w(TAG, "Pending start of voice interaction already.");
4143 return;
4144 }
4145 activity.pendingVoiceInteractionStart = true;
4146 }
4147 LocalServices.getService(VoiceInteractionManagerInternal.class)
4148 .startLocalVoiceInteraction(callingActivity, options);
4149 }
4150
4151 @Override
4152 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4153 LocalServices.getService(VoiceInteractionManagerInternal.class)
4154 .stopLocalVoiceInteraction(callingActivity);
4155 }
4156
4157 @Override
4158 public boolean supportsLocalVoiceInteraction() {
4159 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4160 .supportsLocalVoiceInteraction();
4161 }
4162
4163 /** Notifies all listeners when the pinned stack animation starts. */
4164 @Override
4165 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004166 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 }
4168
4169 /** Notifies all listeners when the pinned stack animation ends. */
4170 @Override
4171 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004172 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 }
4174
4175 @Override
4176 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004177 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 final long ident = Binder.clearCallingIdentity();
4179 try {
4180 synchronized (mGlobalLock) {
4181 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4182 }
4183 } finally {
4184 Binder.restoreCallingIdentity(ident);
4185 }
4186 }
4187
4188 @Override
4189 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004190 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004191
4192 synchronized (mGlobalLock) {
4193 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004194 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 // Call might come when display is not yet added or has already been removed.
4196 if (DEBUG_CONFIGURATION) {
4197 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4198 + displayId);
4199 }
4200 return false;
4201 }
4202
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004203 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 }
4207
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004209 final Message msg = PooledLambda.obtainMessage(
4210 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4211 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 }
4213
4214 final long origId = Binder.clearCallingIdentity();
4215 try {
4216 if (values != null) {
4217 Settings.System.clearConfiguration(values);
4218 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004219 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4221 return mTmpUpdateConfigurationResult.changes != 0;
4222 } finally {
4223 Binder.restoreCallingIdentity(origId);
4224 }
4225 }
4226 }
4227
4228 @Override
4229 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004230 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004231
4232 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 }
4237
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004238 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004239 final Message msg = PooledLambda.obtainMessage(
4240 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4241 DEFAULT_DISPLAY);
4242 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 }
4244
4245 final long origId = Binder.clearCallingIdentity();
4246 try {
4247 if (values != null) {
4248 Settings.System.clearConfiguration(values);
4249 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 UserHandle.USER_NULL, false /* deferResume */,
4252 mTmpUpdateConfigurationResult);
4253 return mTmpUpdateConfigurationResult.changes != 0;
4254 } finally {
4255 Binder.restoreCallingIdentity(origId);
4256 }
4257 }
4258 }
4259
4260 @Override
4261 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4262 CharSequence message) {
4263 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004264 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4266 }
4267 final long callingId = Binder.clearCallingIdentity();
4268 try {
4269 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004270 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004271 }
4272 } finally {
4273 Binder.restoreCallingIdentity(callingId);
4274 }
4275 }
4276
4277 @Override
4278 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004279 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 "cancelTaskWindowTransition()");
4281 final long ident = Binder.clearCallingIdentity();
4282 try {
4283 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004284 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 MATCH_TASK_IN_STACKS_ONLY);
4286 if (task == null) {
4287 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4288 return;
4289 }
4290 task.cancelWindowTransition();
4291 }
4292 } finally {
4293 Binder.restoreCallingIdentity(ident);
4294 }
4295 }
4296
4297 @Override
4298 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 final long ident = Binder.clearCallingIdentity();
4301 try {
4302 final TaskRecord task;
4303 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004304 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004305 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4306 if (task == null) {
4307 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4308 return null;
4309 }
4310 }
4311 // Don't call this while holding the lock as this operation might hit the disk.
4312 return task.getSnapshot(reducedResolution);
4313 } finally {
4314 Binder.restoreCallingIdentity(ident);
4315 }
4316 }
4317
4318 @Override
4319 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4320 synchronized (mGlobalLock) {
4321 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4322 if (r == null) {
4323 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4324 + token);
4325 return;
4326 }
4327 final long origId = Binder.clearCallingIdentity();
4328 try {
4329 r.setDisablePreviewScreenshots(disable);
4330 } finally {
4331 Binder.restoreCallingIdentity(origId);
4332 }
4333 }
4334 }
4335
4336 /** Return the user id of the last resumed activity. */
4337 @Override
4338 public @UserIdInt
4339 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004340 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4342 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004343 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004344 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004346 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 }
4348 }
4349
4350 @Override
4351 public void updateLockTaskFeatures(int userId, int flags) {
4352 final int callingUid = Binder.getCallingUid();
4353 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004354 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 "updateLockTaskFeatures()");
4356 }
4357 synchronized (mGlobalLock) {
4358 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4359 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004360 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 }
4362 }
4363
4364 @Override
4365 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4366 synchronized (mGlobalLock) {
4367 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4368 if (r == null) {
4369 return;
4370 }
4371 final long origId = Binder.clearCallingIdentity();
4372 try {
4373 r.setShowWhenLocked(showWhenLocked);
4374 } finally {
4375 Binder.restoreCallingIdentity(origId);
4376 }
4377 }
4378 }
4379
4380 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004381 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4382 synchronized (mGlobalLock) {
4383 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4384 if (r == null) {
4385 return;
4386 }
4387 final long origId = Binder.clearCallingIdentity();
4388 try {
4389 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4390 } finally {
4391 Binder.restoreCallingIdentity(origId);
4392 }
4393 }
4394 }
4395
4396 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4398 synchronized (mGlobalLock) {
4399 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4400 if (r == null) {
4401 return;
4402 }
4403 final long origId = Binder.clearCallingIdentity();
4404 try {
4405 r.setTurnScreenOn(turnScreenOn);
4406 } finally {
4407 Binder.restoreCallingIdentity(origId);
4408 }
4409 }
4410 }
4411
4412 @Override
4413 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 "registerRemoteAnimations");
4416 definition.setCallingPid(Binder.getCallingPid());
4417 synchronized (mGlobalLock) {
4418 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4419 if (r == null) {
4420 return;
4421 }
4422 final long origId = Binder.clearCallingIdentity();
4423 try {
4424 r.registerRemoteAnimations(definition);
4425 } finally {
4426 Binder.restoreCallingIdentity(origId);
4427 }
4428 }
4429 }
4430
4431 @Override
4432 public void registerRemoteAnimationForNextActivityStart(String packageName,
4433 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 "registerRemoteAnimationForNextActivityStart");
4436 adapter.setCallingPid(Binder.getCallingPid());
4437 synchronized (mGlobalLock) {
4438 final long origId = Binder.clearCallingIdentity();
4439 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004440 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 packageName, adapter);
4442 } finally {
4443 Binder.restoreCallingIdentity(origId);
4444 }
4445 }
4446 }
4447
Evan Rosky966759f2019-01-15 10:33:58 -08004448 @Override
4449 public void registerRemoteAnimationsForDisplay(int displayId,
4450 RemoteAnimationDefinition definition) {
4451 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4452 "registerRemoteAnimations");
4453 definition.setCallingPid(Binder.getCallingPid());
4454 synchronized (mGlobalLock) {
4455 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4456 if (display == null) {
4457 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4458 return;
4459 }
4460 final long origId = Binder.clearCallingIdentity();
4461 try {
4462 display.mDisplayContent.registerRemoteAnimations(definition);
4463 } finally {
4464 Binder.restoreCallingIdentity(origId);
4465 }
4466 }
4467 }
4468
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4470 @Override
4471 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4472 synchronized (mGlobalLock) {
4473 final long origId = Binder.clearCallingIdentity();
4474 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004475 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 } finally {
4477 Binder.restoreCallingIdentity(origId);
4478 }
4479 }
4480 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004481
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004482 @Override
4483 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004484 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004485 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004486 final int pid = Binder.getCallingPid();
4487 final WindowProcessController wpc = mPidMap.get(pid);
4488 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004489 }
4490 }
4491
4492 @Override
4493 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004495 != PERMISSION_GRANTED) {
4496 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4497 + Binder.getCallingPid()
4498 + ", uid=" + Binder.getCallingUid()
4499 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4500 Slog.w(TAG, msg);
4501 throw new SecurityException(msg);
4502 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004504 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004505 final int pid = Binder.getCallingPid();
4506 final WindowProcessController proc = mPidMap.get(pid);
4507 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004508 }
4509 }
4510
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004511 @Override
4512 public void stopAppSwitches() {
4513 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4514 synchronized (mGlobalLock) {
4515 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4516 mDidAppSwitch = false;
4517 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4518 }
4519 }
4520
4521 @Override
4522 public void resumeAppSwitches() {
4523 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4524 synchronized (mGlobalLock) {
4525 // Note that we don't execute any pending app switches... we will
4526 // let those wait until either the timeout, or the next start
4527 // activity request.
4528 mAppSwitchesAllowedTime = 0;
4529 }
4530 }
4531
4532 void onStartActivitySetDidAppSwitch() {
4533 if (mDidAppSwitch) {
4534 // This is the second allowed switch since we stopped switches, so now just generally
4535 // allow switches. Use case:
4536 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4537 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4538 // anyone to switch again).
4539 mAppSwitchesAllowedTime = 0;
4540 } else {
4541 mDidAppSwitch = true;
4542 }
4543 }
4544
4545 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004546 boolean shouldDisableNonVrUiLocked() {
4547 return mVrController.shouldDisableNonVrUiLocked();
4548 }
4549
Wale Ogunwale53783742018-09-16 10:21:51 -07004550 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004551 // VR apps are expected to run in a main display. If an app is turning on VR for
4552 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4553 // fullscreen stack before enabling VR Mode.
4554 // TODO: The goal of this code is to keep the VR app on the main display. When the
4555 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4556 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4557 // option would be a better choice here.
4558 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4559 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4560 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004561 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004562 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004563 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004564 }
4565 mH.post(() -> {
4566 if (!mVrController.onVrModeChanged(r)) {
4567 return;
4568 }
4569 synchronized (mGlobalLock) {
4570 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4571 mWindowManager.disableNonVrUi(disableNonVrUi);
4572 if (disableNonVrUi) {
4573 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4574 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004575 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004576 }
4577 }
4578 });
4579 }
4580
Wale Ogunwale53783742018-09-16 10:21:51 -07004581 @Override
4582 public int getPackageScreenCompatMode(String packageName) {
4583 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4584 synchronized (mGlobalLock) {
4585 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4586 }
4587 }
4588
4589 @Override
4590 public void setPackageScreenCompatMode(String packageName, int mode) {
4591 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4592 "setPackageScreenCompatMode");
4593 synchronized (mGlobalLock) {
4594 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4595 }
4596 }
4597
4598 @Override
4599 public boolean getPackageAskScreenCompat(String packageName) {
4600 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4601 synchronized (mGlobalLock) {
4602 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4603 }
4604 }
4605
4606 @Override
4607 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4608 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4609 "setPackageAskScreenCompat");
4610 synchronized (mGlobalLock) {
4611 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4612 }
4613 }
4614
Wale Ogunwale64258362018-10-16 15:13:37 -07004615 public static String relaunchReasonToString(int relaunchReason) {
4616 switch (relaunchReason) {
4617 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4618 return "window_resize";
4619 case RELAUNCH_REASON_FREE_RESIZE:
4620 return "free_resize";
4621 default:
4622 return null;
4623 }
4624 }
4625
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004626 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004627 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004628 }
4629
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004630 /** Pokes the task persister. */
4631 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4632 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4633 }
4634
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004635 boolean isKeyguardLocked() {
4636 return mKeyguardController.isKeyguardLocked();
4637 }
4638
Garfield Tan01548632018-11-27 10:15:48 -08004639 /**
4640 * Clears launch params for the given package.
4641 * @param packageNames the names of the packages of which the launch params are to be cleared
4642 */
4643 @Override
4644 public void clearLaunchParamsForPackages(List<String> packageNames) {
4645 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4646 "clearLaunchParamsForPackages");
4647 synchronized (mGlobalLock) {
4648 for (int i = 0; i < packageNames.size(); ++i) {
4649 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4650 }
4651 }
4652 }
4653
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004654 /**
4655 * Makes the display with the given id a single task instance display. I.e the display can only
4656 * contain one task.
4657 */
4658 @Override
4659 public void setDisplayToSingleTaskInstance(int displayId) {
4660 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4661 "setDisplayToSingleTaskInstance");
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
4664 final ActivityDisplay display =
4665 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4666 if (display != null) {
4667 display.setDisplayToSingleTaskInstance();
4668 }
4669 } finally {
4670 Binder.restoreCallingIdentity(origId);
4671 }
4672 }
4673
Wale Ogunwale31913b52018-10-13 08:29:31 -07004674 void dumpLastANRLocked(PrintWriter pw) {
4675 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4676 if (mLastANRState == null) {
4677 pw.println(" <no ANR has occurred since boot>");
4678 } else {
4679 pw.println(mLastANRState);
4680 }
4681 }
4682
4683 void dumpLastANRTracesLocked(PrintWriter pw) {
4684 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4685
4686 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4687 if (ArrayUtils.isEmpty(files)) {
4688 pw.println(" <no ANR has occurred since boot>");
4689 return;
4690 }
4691 // Find the latest file.
4692 File latest = null;
4693 for (File f : files) {
4694 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4695 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004696 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004697 }
4698 pw.print("File: ");
4699 pw.print(latest.getName());
4700 pw.println();
4701 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4702 String line;
4703 while ((line = in.readLine()) != null) {
4704 pw.println(line);
4705 }
4706 } catch (IOException e) {
4707 pw.print("Unable to read: ");
4708 pw.print(e);
4709 pw.println();
4710 }
4711 }
4712
4713 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4714 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4715 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4716 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4717 }
4718
4719 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4720 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4721 pw.println(header);
4722
Wale Ogunwaled32da472018-11-16 07:19:28 -08004723 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004724 dumpPackage);
4725 boolean needSep = printedAnything;
4726
4727 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004728 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004729 " ResumedActivity: ");
4730 if (printed) {
4731 printedAnything = true;
4732 needSep = false;
4733 }
4734
4735 if (dumpPackage == null) {
4736 if (needSep) {
4737 pw.println();
4738 }
4739 printedAnything = true;
4740 mStackSupervisor.dump(pw, " ");
4741 }
4742
4743 if (!printedAnything) {
4744 pw.println(" (nothing)");
4745 }
4746 }
4747
4748 void dumpActivityContainersLocked(PrintWriter pw) {
4749 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004750 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004751 pw.println(" ");
4752 }
4753
4754 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4755 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4756 getActivityStartController().dump(pw, "", dumpPackage);
4757 }
4758
4759 /**
4760 * There are three things that cmd can be:
4761 * - a flattened component name that matches an existing activity
4762 * - the cmd arg isn't the flattened component name of an existing activity:
4763 * dump all activity whose component contains the cmd as a substring
4764 * - A hex number of the ActivityRecord object instance.
4765 *
4766 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4767 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4768 */
4769 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4770 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4771 ArrayList<ActivityRecord> activities;
4772
4773 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004774 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004775 dumpFocusedStackOnly);
4776 }
4777
4778 if (activities.size() <= 0) {
4779 return false;
4780 }
4781
4782 String[] newArgs = new String[args.length - opti];
4783 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4784
4785 TaskRecord lastTask = null;
4786 boolean needSep = false;
4787 for (int i = activities.size() - 1; i >= 0; i--) {
4788 ActivityRecord r = activities.get(i);
4789 if (needSep) {
4790 pw.println();
4791 }
4792 needSep = true;
4793 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004794 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004795 if (lastTask != task) {
4796 lastTask = task;
4797 pw.print("TASK "); pw.print(lastTask.affinity);
4798 pw.print(" id="); pw.print(lastTask.taskId);
4799 pw.print(" userId="); pw.println(lastTask.userId);
4800 if (dumpAll) {
4801 lastTask.dump(pw, " ");
4802 }
4803 }
4804 }
4805 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4806 }
4807 return true;
4808 }
4809
4810 /**
4811 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4812 * there is a thread associated with the activity.
4813 */
4814 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4815 final ActivityRecord r, String[] args, boolean dumpAll) {
4816 String innerPrefix = prefix + " ";
4817 synchronized (mGlobalLock) {
4818 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4819 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4820 pw.print(" pid=");
4821 if (r.hasProcess()) pw.println(r.app.getPid());
4822 else pw.println("(not running)");
4823 if (dumpAll) {
4824 r.dump(pw, innerPrefix);
4825 }
4826 }
4827 if (r.attachedToProcess()) {
4828 // flush anything that is already in the PrintWriter since the thread is going
4829 // to write to the file descriptor directly
4830 pw.flush();
4831 try {
4832 TransferPipe tp = new TransferPipe();
4833 try {
4834 r.app.getThread().dumpActivity(tp.getWriteFd(),
4835 r.appToken, innerPrefix, args);
4836 tp.go(fd);
4837 } finally {
4838 tp.kill();
4839 }
4840 } catch (IOException e) {
4841 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4842 } catch (RemoteException e) {
4843 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4844 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004845 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004846 }
4847
sanryhuang498e77e2018-12-06 14:57:01 +08004848 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4849 boolean testPssMode) {
4850 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4851 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4852 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004853 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004854 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4855 st.toString());
4856 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004857 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4858 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4859 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004860 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4861 testPssMode);
4862 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004863 }
4864
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004865 int getCurrentUserId() {
4866 return mAmInternal.getCurrentUserId();
4867 }
4868
4869 private void enforceNotIsolatedCaller(String caller) {
4870 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4871 throw new SecurityException("Isolated process not allowed to call " + caller);
4872 }
4873 }
4874
Wale Ogunwalef6733932018-06-27 05:14:34 -07004875 public Configuration getConfiguration() {
4876 Configuration ci;
4877 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004878 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004879 ci.userSetLocale = false;
4880 }
4881 return ci;
4882 }
4883
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004884 /**
4885 * Current global configuration information. Contains general settings for the entire system,
4886 * also corresponds to the merged configuration of the default display.
4887 */
4888 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004889 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890 }
4891
4892 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4893 boolean initLocale) {
4894 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4895 }
4896
4897 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4898 boolean initLocale, boolean deferResume) {
4899 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4900 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4901 UserHandle.USER_NULL, deferResume);
4902 }
4903
Wale Ogunwale59507092018-10-29 09:00:30 -07004904 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004905 final long origId = Binder.clearCallingIdentity();
4906 try {
4907 synchronized (mGlobalLock) {
4908 updateConfigurationLocked(values, null, false, true, userId,
4909 false /* deferResume */);
4910 }
4911 } finally {
4912 Binder.restoreCallingIdentity(origId);
4913 }
4914 }
4915
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004916 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4917 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4918 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4919 deferResume, null /* result */);
4920 }
4921
4922 /**
4923 * Do either or both things: (1) change the current configuration, and (2)
4924 * make sure the given activity is running with the (now) current
4925 * configuration. Returns true if the activity has been left running, or
4926 * false if <var>starting</var> is being destroyed to match the new
4927 * configuration.
4928 *
4929 * @param userId is only used when persistent parameter is set to true to persist configuration
4930 * for that particular user
4931 */
4932 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4933 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4934 ActivityTaskManagerService.UpdateConfigurationResult result) {
4935 int changes = 0;
4936 boolean kept = true;
4937
4938 if (mWindowManager != null) {
4939 mWindowManager.deferSurfaceLayout();
4940 }
4941 try {
4942 if (values != null) {
4943 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4944 deferResume);
4945 }
4946
4947 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4948 } finally {
4949 if (mWindowManager != null) {
4950 mWindowManager.continueSurfaceLayout();
4951 }
4952 }
4953
4954 if (result != null) {
4955 result.changes = changes;
4956 result.activityRelaunched = !kept;
4957 }
4958 return kept;
4959 }
4960
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004961 /** Update default (global) configuration and notify listeners about changes. */
4962 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4963 boolean persistent, int userId, boolean deferResume) {
4964 mTempConfig.setTo(getGlobalConfiguration());
4965 final int changes = mTempConfig.updateFrom(values);
4966 if (changes == 0) {
4967 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4968 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4969 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4970 // (even if there are no actual changes) to unfreeze the window.
4971 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4972 return 0;
4973 }
4974
4975 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4976 "Updating global configuration to: " + values);
4977
4978 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4979 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4980 values.colorMode,
4981 values.densityDpi,
4982 values.fontScale,
4983 values.hardKeyboardHidden,
4984 values.keyboard,
4985 values.keyboardHidden,
4986 values.mcc,
4987 values.mnc,
4988 values.navigation,
4989 values.navigationHidden,
4990 values.orientation,
4991 values.screenHeightDp,
4992 values.screenLayout,
4993 values.screenWidthDp,
4994 values.smallestScreenWidthDp,
4995 values.touchscreen,
4996 values.uiMode);
4997
4998
4999 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5000 final LocaleList locales = values.getLocales();
5001 int bestLocaleIndex = 0;
5002 if (locales.size() > 1) {
5003 if (mSupportedSystemLocales == null) {
5004 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5005 }
5006 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5007 }
5008 SystemProperties.set("persist.sys.locale",
5009 locales.get(bestLocaleIndex).toLanguageTag());
5010 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005011
5012 final Message m = PooledLambda.obtainMessage(
5013 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5014 locales.get(bestLocaleIndex));
5015 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005016 }
5017
Yunfan Chen75157d72018-07-27 14:47:21 +09005018 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005019
5020 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005021 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005022
5023 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5024 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005025 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005026
5027 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005028 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005029
5030 AttributeCache ac = AttributeCache.instance();
5031 if (ac != null) {
5032 ac.updateConfiguration(mTempConfig);
5033 }
5034
5035 // Make sure all resources in our process are updated right now, so that anyone who is going
5036 // to retrieve resource values after we return will be sure to get the new ones. This is
5037 // especially important during boot, where the first config change needs to guarantee all
5038 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005039 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040
5041 // We need another copy of global config because we're scheduling some calls instead of
5042 // running them in place. We need to be sure that object we send will be handled unchanged.
5043 final Configuration configCopy = new Configuration(mTempConfig);
5044 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005045 final Message msg = PooledLambda.obtainMessage(
5046 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5047 this, userId, configCopy);
5048 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005049 }
5050
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005051 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005052 final int pid = mPidMap.keyAt(i);
5053 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005054 if (DEBUG_CONFIGURATION) {
5055 Slog.v(TAG_CONFIGURATION, "Update process config of "
5056 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005057 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005058 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059 }
5060
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005061 final Message msg = PooledLambda.obtainMessage(
5062 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5063 mAmInternal, changes, initLocale);
5064 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005065
5066 // Override configuration of the default display duplicates global config, so we need to
5067 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005068 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005069 DEFAULT_DISPLAY);
5070
5071 return changes;
5072 }
5073
5074 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5075 boolean deferResume, int displayId) {
5076 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5077 displayId, null /* result */);
5078 }
5079
5080 /**
5081 * Updates override configuration specific for the selected display. If no config is provided,
5082 * new one will be computed in WM based on current display info.
5083 */
5084 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5085 ActivityRecord starting, boolean deferResume, int displayId,
5086 ActivityTaskManagerService.UpdateConfigurationResult result) {
5087 int changes = 0;
5088 boolean kept = true;
5089
5090 if (mWindowManager != null) {
5091 mWindowManager.deferSurfaceLayout();
5092 }
5093 try {
5094 if (values != null) {
5095 if (displayId == DEFAULT_DISPLAY) {
5096 // Override configuration of the default display duplicates global config, so
5097 // we're calling global config update instead for default display. It will also
5098 // apply the correct override config.
5099 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5100 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5101 } else {
5102 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5103 }
5104 }
5105
5106 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5107 } finally {
5108 if (mWindowManager != null) {
5109 mWindowManager.continueSurfaceLayout();
5110 }
5111 }
5112
5113 if (result != null) {
5114 result.changes = changes;
5115 result.activityRelaunched = !kept;
5116 }
5117 return kept;
5118 }
5119
5120 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5121 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005122 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005123 final int changes = mTempConfig.updateFrom(values);
5124 if (changes != 0) {
5125 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5126 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005127 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128
5129 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5130 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005131 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132
Wale Ogunwale5c918702018-10-18 11:06:33 -07005133 // Post message to start process to avoid possible deadlock of calling into AMS with
5134 // the ATMS lock held.
5135 final Message msg = PooledLambda.obtainMessage(
5136 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5137 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5138 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 }
5140 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005141 return changes;
5142 }
5143
Wale Ogunwalef6733932018-06-27 05:14:34 -07005144 private void updateEventDispatchingLocked(boolean booted) {
5145 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5146 }
5147
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005148 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5149 final ContentResolver resolver = mContext.getContentResolver();
5150 Settings.System.putConfigurationForUser(resolver, config, userId);
5151 }
5152
5153 private void sendLocaleToMountDaemonMsg(Locale l) {
5154 try {
5155 IBinder service = ServiceManager.getService("mount");
5156 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5157 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5158 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5159 } catch (RemoteException e) {
5160 Log.e(TAG, "Error storing locale for decryption UI", e);
5161 }
5162 }
5163
Alison Cichowlas3e340502018-08-07 17:15:01 -04005164 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5165 mStartActivitySources.remove(permissionToken);
5166 mExpiredStartAsCallerTokens.add(permissionToken);
5167 }
5168
5169 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5170 mExpiredStartAsCallerTokens.remove(permissionToken);
5171 }
5172
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005173 boolean isActivityStartsLoggingEnabled() {
5174 return mAmInternal.isActivityStartsLoggingEnabled();
5175 }
5176
Michal Karpinski8596ded2018-11-14 14:43:48 +00005177 boolean isBackgroundActivityStartsEnabled() {
5178 return mAmInternal.isBackgroundActivityStartsEnabled();
5179 }
5180
Wale Ogunwalef6733932018-06-27 05:14:34 -07005181 void enableScreenAfterBoot(boolean booted) {
5182 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5183 SystemClock.uptimeMillis());
5184 mWindowManager.enableScreenAfterBoot();
5185
5186 synchronized (mGlobalLock) {
5187 updateEventDispatchingLocked(booted);
5188 }
5189 }
5190
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005191 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5192 if (r == null || !r.hasProcess()) {
5193 return KEY_DISPATCHING_TIMEOUT_MS;
5194 }
5195 return getInputDispatchingTimeoutLocked(r.app);
5196 }
5197
5198 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005199 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005200 }
5201
Wale Ogunwalef6733932018-06-27 05:14:34 -07005202 /**
5203 * Decide based on the configuration whether we should show the ANR,
5204 * crash, etc dialogs. The idea is that if there is no affordance to
5205 * press the on-screen buttons, or the user experience would be more
5206 * greatly impacted than the crash itself, we shouldn't show the dialog.
5207 *
5208 * A thought: SystemUI might also want to get told about this, the Power
5209 * dialog / global actions also might want different behaviors.
5210 */
5211 private void updateShouldShowDialogsLocked(Configuration config) {
5212 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5213 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5214 && config.navigation == Configuration.NAVIGATION_NONAV);
5215 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5216 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5217 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5218 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5219 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5220 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5221 HIDE_ERROR_DIALOGS, 0) != 0;
5222 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5223 }
5224
5225 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5226 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5227 FONT_SCALE, 1.0f, userId);
5228
5229 synchronized (this) {
5230 if (getGlobalConfiguration().fontScale == scaleFactor) {
5231 return;
5232 }
5233
5234 final Configuration configuration
5235 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5236 configuration.fontScale = scaleFactor;
5237 updatePersistentConfiguration(configuration, userId);
5238 }
5239 }
5240
5241 // Actually is sleeping or shutting down or whatever else in the future
5242 // is an inactive state.
5243 boolean isSleepingOrShuttingDownLocked() {
5244 return isSleepingLocked() || mShuttingDown;
5245 }
5246
5247 boolean isSleepingLocked() {
5248 return mSleeping;
5249 }
5250
Riddle Hsu16567132018-08-16 21:37:47 +08005251 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005252 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005253 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005254 if (task.isActivityTypeStandard()) {
5255 if (mCurAppTimeTracker != r.appTimeTracker) {
5256 // We are switching app tracking. Complete the current one.
5257 if (mCurAppTimeTracker != null) {
5258 mCurAppTimeTracker.stop();
5259 mH.obtainMessage(
5260 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005261 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005262 mCurAppTimeTracker = null;
5263 }
5264 if (r.appTimeTracker != null) {
5265 mCurAppTimeTracker = r.appTimeTracker;
5266 startTimeTrackingFocusedActivityLocked();
5267 }
5268 } else {
5269 startTimeTrackingFocusedActivityLocked();
5270 }
5271 } else {
5272 r.appTimeTracker = null;
5273 }
5274 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5275 // TODO: Probably not, because we don't want to resume voice on switching
5276 // back to this activity
5277 if (task.voiceInteractor != null) {
5278 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5279 } else {
5280 finishRunningVoiceLocked();
5281
5282 if (mLastResumedActivity != null) {
5283 final IVoiceInteractionSession session;
5284
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005285 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005286 if (lastResumedActivityTask != null
5287 && lastResumedActivityTask.voiceSession != null) {
5288 session = lastResumedActivityTask.voiceSession;
5289 } else {
5290 session = mLastResumedActivity.voiceSession;
5291 }
5292
5293 if (session != null) {
5294 // We had been in a voice interaction session, but now focused has
5295 // move to something different. Just finish the session, we can't
5296 // return to it and retain the proper state and synchronization with
5297 // the voice interaction service.
5298 finishVoiceTask(session);
5299 }
5300 }
5301 }
5302
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005303 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5304 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005305 }
5306 updateResumedAppTrace(r);
5307 mLastResumedActivity = r;
5308
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005309 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005310
5311 applyUpdateLockStateLocked(r);
5312 applyUpdateVrModeLocked(r);
5313
5314 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005315 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005316 r == null ? "NULL" : r.shortComponentName,
5317 reason);
5318 }
5319
5320 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5321 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005322 final ActivityTaskManagerInternal.SleepToken token =
5323 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005324 updateSleepIfNeededLocked();
5325 return token;
5326 }
5327 }
5328
5329 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005330 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005331 final boolean wasSleeping = mSleeping;
5332 boolean updateOomAdj = false;
5333
5334 if (!shouldSleep) {
5335 // If wasSleeping is true, we need to wake up activity manager state from when
5336 // we started sleeping. In either case, we need to apply the sleep tokens, which
5337 // will wake up stacks or put them to sleep as appropriate.
5338 if (wasSleeping) {
5339 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005340 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5341 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005342 startTimeTrackingFocusedActivityLocked();
5343 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5344 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5345 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005346 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005347 if (wasSleeping) {
5348 updateOomAdj = true;
5349 }
5350 } else if (!mSleeping && shouldSleep) {
5351 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005352 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5353 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 if (mCurAppTimeTracker != null) {
5355 mCurAppTimeTracker.stop();
5356 }
5357 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5358 mStackSupervisor.goingToSleepLocked();
5359 updateResumedAppTrace(null /* resumed */);
5360 updateOomAdj = true;
5361 }
5362 if (updateOomAdj) {
5363 mH.post(mAmInternal::updateOomAdj);
5364 }
5365 }
5366
5367 void updateOomAdj() {
5368 mH.post(mAmInternal::updateOomAdj);
5369 }
5370
Wale Ogunwale53783742018-09-16 10:21:51 -07005371 void updateCpuStats() {
5372 mH.post(mAmInternal::updateCpuStats);
5373 }
5374
Hui Yu03d12402018-12-06 18:00:37 -08005375 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5376 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005377 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5378 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005379 mH.sendMessage(m);
5380 }
5381
Hui Yu03d12402018-12-06 18:00:37 -08005382 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005383 ComponentName taskRoot = null;
5384 final TaskRecord task = activity.getTaskRecord();
5385 if (task != null) {
5386 final ActivityRecord rootActivity = task.getRootActivity();
5387 if (rootActivity != null) {
5388 taskRoot = rootActivity.mActivityComponent;
5389 }
5390 }
5391
Hui Yu03d12402018-12-06 18:00:37 -08005392 final Message m = PooledLambda.obtainMessage(
5393 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005394 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005395 mH.sendMessage(m);
5396 }
5397
Wale Ogunwale53783742018-09-16 10:21:51 -07005398 void setBooting(boolean booting) {
5399 mAmInternal.setBooting(booting);
5400 }
5401
5402 boolean isBooting() {
5403 return mAmInternal.isBooting();
5404 }
5405
5406 void setBooted(boolean booted) {
5407 mAmInternal.setBooted(booted);
5408 }
5409
5410 boolean isBooted() {
5411 return mAmInternal.isBooted();
5412 }
5413
5414 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5415 mH.post(() -> {
5416 if (finishBooting) {
5417 mAmInternal.finishBooting();
5418 }
5419 if (enableScreen) {
5420 mInternal.enableScreenAfterBoot(isBooted());
5421 }
5422 });
5423 }
5424
5425 void setHeavyWeightProcess(ActivityRecord root) {
5426 mHeavyWeightProcess = root.app;
5427 final Message m = PooledLambda.obtainMessage(
5428 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005429 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005430 mH.sendMessage(m);
5431 }
5432
5433 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5434 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5435 return;
5436 }
5437
5438 mHeavyWeightProcess = null;
5439 final Message m = PooledLambda.obtainMessage(
5440 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5441 proc.mUserId);
5442 mH.sendMessage(m);
5443 }
5444
5445 private void cancelHeavyWeightProcessNotification(int userId) {
5446 final INotificationManager inm = NotificationManager.getService();
5447 if (inm == null) {
5448 return;
5449 }
5450 try {
5451 inm.cancelNotificationWithTag("android", null,
5452 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5453 } catch (RuntimeException e) {
5454 Slog.w(TAG, "Error canceling notification for service", e);
5455 } catch (RemoteException e) {
5456 }
5457
5458 }
5459
5460 private void postHeavyWeightProcessNotification(
5461 WindowProcessController proc, Intent intent, int userId) {
5462 if (proc == null) {
5463 return;
5464 }
5465
5466 final INotificationManager inm = NotificationManager.getService();
5467 if (inm == null) {
5468 return;
5469 }
5470
5471 try {
5472 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5473 String text = mContext.getString(R.string.heavy_weight_notification,
5474 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5475 Notification notification =
5476 new Notification.Builder(context,
5477 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5478 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5479 .setWhen(0)
5480 .setOngoing(true)
5481 .setTicker(text)
5482 .setColor(mContext.getColor(
5483 com.android.internal.R.color.system_notification_accent_color))
5484 .setContentTitle(text)
5485 .setContentText(
5486 mContext.getText(R.string.heavy_weight_notification_detail))
5487 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5488 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5489 new UserHandle(userId)))
5490 .build();
5491 try {
5492 inm.enqueueNotificationWithTag("android", "android", null,
5493 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5494 } catch (RuntimeException e) {
5495 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5496 } catch (RemoteException e) {
5497 }
5498 } catch (PackageManager.NameNotFoundException e) {
5499 Slog.w(TAG, "Unable to create context for heavy notification", e);
5500 }
5501
5502 }
5503
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005504 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5505 IBinder token, String resultWho, int requestCode, Intent[] intents,
5506 String[] resolvedTypes, int flags, Bundle bOptions) {
5507
5508 ActivityRecord activity = null;
5509 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5510 activity = ActivityRecord.isInStackLocked(token);
5511 if (activity == null) {
5512 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5513 return null;
5514 }
5515 if (activity.finishing) {
5516 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5517 return null;
5518 }
5519 }
5520
5521 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5522 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5523 bOptions);
5524 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5525 if (noCreate) {
5526 return rec;
5527 }
5528 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5529 if (activity.pendingResults == null) {
5530 activity.pendingResults = new HashSet<>();
5531 }
5532 activity.pendingResults.add(rec.ref);
5533 }
5534 return rec;
5535 }
5536
Andrii Kulian52d255c2018-07-13 11:32:19 -07005537 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005539 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005540 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5541 mCurAppTimeTracker.start(resumedActivity.packageName);
5542 }
5543 }
5544
5545 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5546 if (mTracedResumedActivity != null) {
5547 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5548 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5549 }
5550 if (resumed != null) {
5551 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5552 constructResumedTraceName(resumed.packageName), 0);
5553 }
5554 mTracedResumedActivity = resumed;
5555 }
5556
5557 private String constructResumedTraceName(String packageName) {
5558 return "focused app: " + packageName;
5559 }
5560
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005561 /** Applies latest configuration and/or visibility updates if needed. */
5562 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5563 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005564 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005565 // mainStack is null during startup.
5566 if (mainStack != null) {
5567 if (changes != 0 && starting == null) {
5568 // If the configuration changed, and the caller is not already
5569 // in the process of starting an activity, then find the top
5570 // activity to check if its configuration needs to change.
5571 starting = mainStack.topRunningActivityLocked();
5572 }
5573
5574 if (starting != null) {
5575 kept = starting.ensureActivityConfiguration(changes,
5576 false /* preserveWindow */);
5577 // And we need to make sure at this point that all other activities
5578 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005579 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005580 !PRESERVE_WINDOWS);
5581 }
5582 }
5583
5584 return kept;
5585 }
5586
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005587 void scheduleAppGcsLocked() {
5588 mH.post(() -> mAmInternal.scheduleAppGcs());
5589 }
5590
Wale Ogunwale53783742018-09-16 10:21:51 -07005591 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5592 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5593 }
5594
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005595 /**
5596 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5597 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5598 * on demand.
5599 */
5600 IPackageManager getPackageManager() {
5601 return AppGlobals.getPackageManager();
5602 }
5603
5604 PackageManagerInternal getPackageManagerInternalLocked() {
5605 if (mPmInternal == null) {
5606 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5607 }
5608 return mPmInternal;
5609 }
5610
Wale Ogunwale008163e2018-07-23 23:11:08 -07005611 AppWarnings getAppWarningsLocked() {
5612 return mAppWarnings;
5613 }
5614
Wale Ogunwale214f3482018-10-04 11:00:47 -07005615 Intent getHomeIntent() {
5616 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5617 intent.setComponent(mTopComponent);
5618 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5619 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5620 intent.addCategory(Intent.CATEGORY_HOME);
5621 }
5622 return intent;
5623 }
5624
Chilun2ef71f72018-11-16 17:57:15 +08005625 /**
5626 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5627 * activities.
5628 *
5629 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5630 * component defined in config_secondaryHomeComponent.
5631 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5632 */
5633 Intent getSecondaryHomeIntent(String preferredPackage) {
5634 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5635 if (preferredPackage == null) {
5636 // Using the component stored in config if no package name.
5637 final String secondaryHomeComponent = mContext.getResources().getString(
5638 com.android.internal.R.string.config_secondaryHomeComponent);
5639 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5640 } else {
5641 intent.setPackage(preferredPackage);
5642 }
5643 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5644 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5645 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5646 }
5647 return intent;
5648 }
5649
Wale Ogunwale214f3482018-10-04 11:00:47 -07005650 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5651 if (info == null) return null;
5652 ApplicationInfo newInfo = new ApplicationInfo(info);
5653 newInfo.initForUser(userId);
5654 return newInfo;
5655 }
5656
Wale Ogunwale9c103022018-10-18 07:44:54 -07005657 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005658 if (uid == SYSTEM_UID) {
5659 // The system gets to run in any process. If there are multiple processes with the same
5660 // uid, just pick the first (this should never happen).
5661 final SparseArray<WindowProcessController> procs =
5662 mProcessNames.getMap().get(processName);
5663 if (procs == null) return null;
5664 final int procCount = procs.size();
5665 for (int i = 0; i < procCount; i++) {
5666 final int procUid = procs.keyAt(i);
5667 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5668 // Don't use an app process or different user process for system component.
5669 continue;
5670 }
5671 return procs.valueAt(i);
5672 }
5673 }
5674
5675 return mProcessNames.get(processName, uid);
5676 }
5677
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005678 WindowProcessController getProcessController(IApplicationThread thread) {
5679 if (thread == null) {
5680 return null;
5681 }
5682
5683 final IBinder threadBinder = thread.asBinder();
5684 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5685 for (int i = pmap.size()-1; i >= 0; i--) {
5686 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5687 for (int j = procs.size() - 1; j >= 0; j--) {
5688 final WindowProcessController proc = procs.valueAt(j);
5689 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5690 return proc;
5691 }
5692 }
5693 }
5694
5695 return null;
5696 }
5697
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005698 WindowProcessController getProcessController(int pid, int uid) {
5699 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5700 for (int i = pmap.size()-1; i >= 0; i--) {
5701 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5702 for (int j = procs.size() - 1; j >= 0; j--) {
5703 final WindowProcessController proc = procs.valueAt(j);
5704 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5705 return proc;
5706 }
5707 }
5708 }
5709 return null;
5710 }
5711
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005712 int getUidStateLocked(int uid) {
5713 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5714 }
5715
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005716 boolean isUidForeground(int uid) {
5717 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5718 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5719 }
5720
Michal Karpinski4026cae2019-02-12 11:51:47 +00005721 boolean isDeviceOwner(String packageName) {
5722 if (packageName == null) {
5723 return false;
5724 }
5725 return packageName.equals(mDeviceOwnerPackageName);
5726 }
5727
5728 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5729 mDeviceOwnerPackageName = deviceOwnerPkg;
5730 }
5731
Wale Ogunwale9de19442018-10-18 19:05:03 -07005732 /**
5733 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5734 * the whitelist
5735 */
5736 String getPendingTempWhitelistTagForUidLocked(int uid) {
5737 return mPendingTempWhitelist.get(uid);
5738 }
5739
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005740 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5741 if (true || Build.IS_USER) {
5742 return;
5743 }
5744
5745 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5746 StrictMode.allowThreadDiskWrites();
5747 try {
5748 File tracesDir = new File("/data/anr");
5749 File tracesFile = null;
5750 try {
5751 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5752
5753 StringBuilder sb = new StringBuilder();
5754 Time tobj = new Time();
5755 tobj.set(System.currentTimeMillis());
5756 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5757 sb.append(": ");
5758 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5759 sb.append(" since ");
5760 sb.append(msg);
5761 FileOutputStream fos = new FileOutputStream(tracesFile);
5762 fos.write(sb.toString().getBytes());
5763 if (app == null) {
5764 fos.write("\n*** No application process!".getBytes());
5765 }
5766 fos.close();
5767 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5768 } catch (IOException e) {
5769 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5770 return;
5771 }
5772
5773 if (app != null && app.getPid() > 0) {
5774 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5775 firstPids.add(app.getPid());
5776 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5777 }
5778
5779 File lastTracesFile = null;
5780 File curTracesFile = null;
5781 for (int i=9; i>=0; i--) {
5782 String name = String.format(Locale.US, "slow%02d.txt", i);
5783 curTracesFile = new File(tracesDir, name);
5784 if (curTracesFile.exists()) {
5785 if (lastTracesFile != null) {
5786 curTracesFile.renameTo(lastTracesFile);
5787 } else {
5788 curTracesFile.delete();
5789 }
5790 }
5791 lastTracesFile = curTracesFile;
5792 }
5793 tracesFile.renameTo(curTracesFile);
5794 } finally {
5795 StrictMode.setThreadPolicy(oldPolicy);
5796 }
5797 }
5798
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005799 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005800 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005801
5802
Wale Ogunwale98875612018-10-12 07:53:02 -07005803 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5804 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005805
Riddle Hsud93a6c42018-11-29 21:50:06 +08005806 H(Looper looper) {
5807 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005808 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005809
5810 @Override
5811 public void handleMessage(Message msg) {
5812 switch (msg.what) {
5813 case REPORT_TIME_TRACKER_MSG: {
5814 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5815 tracker.deliverResult(mContext);
5816 } break;
5817 }
5818 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005819 }
5820
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005821 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005822 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005823
5824 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005825 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005826 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005827
5828 @Override
5829 public void handleMessage(Message msg) {
5830 switch (msg.what) {
5831 case DISMISS_DIALOG_UI_MSG: {
5832 final Dialog d = (Dialog) msg.obj;
5833 d.dismiss();
5834 break;
5835 }
5836 }
5837 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005838 }
5839
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005840 final class LocalService extends ActivityTaskManagerInternal {
5841 @Override
5842 public SleepToken acquireSleepToken(String tag, int displayId) {
5843 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005844 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005845 }
5846
5847 @Override
5848 public ComponentName getHomeActivityForUser(int userId) {
5849 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005850 final ActivityRecord homeActivity =
5851 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005852 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005853 }
5854 }
5855
5856 @Override
5857 public void onLocalVoiceInteractionStarted(IBinder activity,
5858 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5859 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005860 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005861 }
5862 }
5863
5864 @Override
5865 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5866 synchronized (mGlobalLock) {
5867 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5868 reasons, timestamp);
5869 }
5870 }
5871
5872 @Override
5873 public void notifyAppTransitionFinished() {
5874 synchronized (mGlobalLock) {
5875 mStackSupervisor.notifyAppTransitionDone();
5876 }
5877 }
5878
5879 @Override
5880 public void notifyAppTransitionCancelled() {
5881 synchronized (mGlobalLock) {
5882 mStackSupervisor.notifyAppTransitionDone();
5883 }
5884 }
5885
5886 @Override
5887 public List<IBinder> getTopVisibleActivities() {
5888 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005889 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005890 }
5891 }
5892
5893 @Override
5894 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5895 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005896 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005897 }
5898 }
5899
5900 @Override
5901 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5902 Bundle bOptions) {
5903 Preconditions.checkNotNull(intents, "intents");
5904 final String[] resolvedTypes = new String[intents.length];
5905
5906 // UID of the package on user userId.
5907 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5908 // packageUid may not be initialized.
5909 int packageUid = 0;
5910 final long ident = Binder.clearCallingIdentity();
5911
5912 try {
5913 for (int i = 0; i < intents.length; i++) {
5914 resolvedTypes[i] =
5915 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5916 }
5917
5918 packageUid = AppGlobals.getPackageManager().getPackageUid(
5919 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5920 } catch (RemoteException e) {
5921 // Shouldn't happen.
5922 } finally {
5923 Binder.restoreCallingIdentity(ident);
5924 }
5925
5926 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005927 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005928 packageUid, packageName,
5929 intents, resolvedTypes, null /* resultTo */,
5930 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005931 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5932 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005933 }
5934 }
5935
5936 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005937 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5938 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5939 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5940 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005941 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005942 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005943 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5944 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5945 userId, validateIncomingUser, originatingPendingIntent,
5946 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005947 }
5948 }
5949
5950 @Override
5951 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5952 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5953 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5954 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005955 PendingIntentRecord originatingPendingIntent,
5956 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005957 synchronized (mGlobalLock) {
5958 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5959 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5960 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005961 validateIncomingUser, originatingPendingIntent,
5962 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005963 }
5964 }
5965
5966 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005967 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5968 Intent intent, Bundle options, int userId) {
5969 return ActivityTaskManagerService.this.startActivityAsUser(
5970 caller, callerPacakge, intent,
5971 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5972 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5973 false /*validateIncomingUser*/);
5974 }
5975
5976 @Override
lumark588a3e82018-07-20 18:53:54 +08005977 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005978 synchronized (mGlobalLock) {
5979
5980 // We might change the visibilities here, so prepare an empty app transition which
5981 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005982 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005983 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005984 if (activityDisplay == null) {
5985 return;
5986 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005987 final DisplayContent dc = activityDisplay.mDisplayContent;
5988 final boolean wasTransitionSet =
5989 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005990 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005991 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005992 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005993 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005994
5995 // If there was a transition set already we don't want to interfere with it as we
5996 // might be starting it too early.
5997 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005998 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005999 }
6000 }
6001 if (callback != null) {
6002 callback.run();
6003 }
6004 }
6005
6006 @Override
6007 public void notifyKeyguardTrustedChanged() {
6008 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006009 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006010 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006011 }
6012 }
6013 }
6014
6015 /**
6016 * Called after virtual display Id is updated by
6017 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6018 * {@param vrVr2dDisplayId}.
6019 */
6020 @Override
6021 public void setVr2dDisplayId(int vr2dDisplayId) {
6022 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6023 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006024 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006025 }
6026 }
6027
6028 @Override
6029 public void setFocusedActivity(IBinder token) {
6030 synchronized (mGlobalLock) {
6031 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6032 if (r == null) {
6033 throw new IllegalArgumentException(
6034 "setFocusedActivity: No activity record matching token=" + token);
6035 }
Louis Chang19443452018-10-09 12:10:21 +08006036 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006037 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006038 }
6039 }
6040 }
6041
6042 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006043 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006044 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046
6047 @Override
6048 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006049 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006050 }
6051
6052 @Override
6053 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006054 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006055 }
6056
6057 @Override
6058 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6059 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6060 }
6061
6062 @Override
6063 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006064 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006065 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006066
6067 @Override
6068 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6069 synchronized (mGlobalLock) {
6070 mActiveVoiceInteractionServiceComponent = component;
6071 }
6072 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006073
6074 @Override
6075 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6076 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6077 return;
6078 }
6079 synchronized (mGlobalLock) {
6080 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6081 if (types == null) {
6082 if (uid < 0) {
6083 return;
6084 }
6085 types = new ArrayMap<>();
6086 mAllowAppSwitchUids.put(userId, types);
6087 }
6088 if (uid < 0) {
6089 types.remove(type);
6090 } else {
6091 types.put(type, uid);
6092 }
6093 }
6094 }
6095
6096 @Override
6097 public void onUserStopped(int userId) {
6098 synchronized (mGlobalLock) {
6099 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6100 mAllowAppSwitchUids.remove(userId);
6101 }
6102 }
6103
6104 @Override
6105 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6106 synchronized (mGlobalLock) {
6107 return ActivityTaskManagerService.this.isGetTasksAllowed(
6108 caller, callingPid, callingUid);
6109 }
6110 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006111
6112 @Override
6113 public void onProcessAdded(WindowProcessController proc) {
6114 synchronized (mGlobalLock) {
6115 mProcessNames.put(proc.mName, proc.mUid, proc);
6116 }
6117 }
6118
6119 @Override
6120 public void onProcessRemoved(String name, int uid) {
6121 synchronized (mGlobalLock) {
6122 mProcessNames.remove(name, uid);
6123 }
6124 }
6125
6126 @Override
6127 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6128 synchronized (mGlobalLock) {
6129 if (proc == mHomeProcess) {
6130 mHomeProcess = null;
6131 }
6132 if (proc == mPreviousProcess) {
6133 mPreviousProcess = null;
6134 }
6135 }
6136 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006137
6138 @Override
6139 public int getTopProcessState() {
6140 synchronized (mGlobalLock) {
6141 return mTopProcessState;
6142 }
6143 }
6144
6145 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006146 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6147 synchronized (mGlobalLock) {
6148 return proc == mHeavyWeightProcess;
6149 }
6150 }
6151
6152 @Override
6153 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6154 synchronized (mGlobalLock) {
6155 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6156 }
6157 }
6158
6159 @Override
6160 public void finishHeavyWeightApp() {
6161 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006162 if (mHeavyWeightProcess != null) {
6163 mHeavyWeightProcess.finishActivities();
6164 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006165 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6166 mHeavyWeightProcess);
6167 }
6168 }
6169
6170 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006171 public boolean isSleeping() {
6172 synchronized (mGlobalLock) {
6173 return isSleepingLocked();
6174 }
6175 }
6176
6177 @Override
6178 public boolean isShuttingDown() {
6179 synchronized (mGlobalLock) {
6180 return mShuttingDown;
6181 }
6182 }
6183
6184 @Override
6185 public boolean shuttingDown(boolean booted, int timeout) {
6186 synchronized (mGlobalLock) {
6187 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006188 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006189 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006190 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006191 return mStackSupervisor.shutdownLocked(timeout);
6192 }
6193 }
6194
6195 @Override
6196 public void enableScreenAfterBoot(boolean booted) {
6197 synchronized (mGlobalLock) {
6198 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6199 SystemClock.uptimeMillis());
6200 mWindowManager.enableScreenAfterBoot();
6201 updateEventDispatchingLocked(booted);
6202 }
6203 }
6204
6205 @Override
6206 public boolean showStrictModeViolationDialog() {
6207 synchronized (mGlobalLock) {
6208 return mShowDialogs && !mSleeping && !mShuttingDown;
6209 }
6210 }
6211
6212 @Override
6213 public void showSystemReadyErrorDialogsIfNeeded() {
6214 synchronized (mGlobalLock) {
6215 try {
6216 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6217 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6218 + " data partition or your device will be unstable.");
6219 mUiHandler.post(() -> {
6220 if (mShowDialogs) {
6221 AlertDialog d = new BaseErrorDialog(mUiContext);
6222 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6223 d.setCancelable(false);
6224 d.setTitle(mUiContext.getText(R.string.android_system_label));
6225 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6226 d.setButton(DialogInterface.BUTTON_POSITIVE,
6227 mUiContext.getText(R.string.ok),
6228 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6229 d.show();
6230 }
6231 });
6232 }
6233 } catch (RemoteException e) {
6234 }
6235
6236 if (!Build.isBuildConsistent()) {
6237 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6238 mUiHandler.post(() -> {
6239 if (mShowDialogs) {
6240 AlertDialog d = new BaseErrorDialog(mUiContext);
6241 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6242 d.setCancelable(false);
6243 d.setTitle(mUiContext.getText(R.string.android_system_label));
6244 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6245 d.setButton(DialogInterface.BUTTON_POSITIVE,
6246 mUiContext.getText(R.string.ok),
6247 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6248 d.show();
6249 }
6250 });
6251 }
6252 }
6253 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006254
6255 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006256 public void onProcessMapped(int pid, WindowProcessController proc) {
6257 synchronized (mGlobalLock) {
6258 mPidMap.put(pid, proc);
6259 }
6260 }
6261
6262 @Override
6263 public void onProcessUnMapped(int pid) {
6264 synchronized (mGlobalLock) {
6265 mPidMap.remove(pid);
6266 }
6267 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006268
6269 @Override
6270 public void onPackageDataCleared(String name) {
6271 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006272 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006273 mAppWarnings.onPackageDataCleared(name);
6274 }
6275 }
6276
6277 @Override
6278 public void onPackageUninstalled(String name) {
6279 synchronized (mGlobalLock) {
6280 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006281 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006282 }
6283 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006284
6285 @Override
6286 public void onPackageAdded(String name, boolean replacing) {
6287 synchronized (mGlobalLock) {
6288 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6289 }
6290 }
6291
6292 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006293 public void onPackageReplaced(ApplicationInfo aInfo) {
6294 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006295 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006296 }
6297 }
6298
6299 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006300 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6301 synchronized (mGlobalLock) {
6302 return compatibilityInfoForPackageLocked(ai);
6303 }
6304 }
6305
Yunfan Chen75157d72018-07-27 14:47:21 +09006306 /**
6307 * Set the corresponding display information for the process global configuration. To be
6308 * called when we need to show IME on a different display.
6309 *
6310 * @param pid The process id associated with the IME window.
6311 * @param displayId The ID of the display showing the IME.
6312 */
6313 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006314 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006315 if (pid == MY_PID || pid < 0) {
6316 if (DEBUG_CONFIGURATION) {
6317 Slog.w(TAG,
6318 "Trying to update display configuration for system/invalid process.");
6319 }
6320 return;
6321 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006322 synchronized (mGlobalLock) {
6323 final ActivityDisplay activityDisplay =
6324 mRootActivityContainer.getActivityDisplay(displayId);
6325 if (activityDisplay == null) {
6326 // Call might come when display is not yet added or has been removed.
6327 if (DEBUG_CONFIGURATION) {
6328 Slog.w(TAG, "Trying to update display configuration for non-existing "
6329 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006330 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006331 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006332 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006333 final WindowProcessController process = mPidMap.get(pid);
6334 if (process == null) {
6335 if (DEBUG_CONFIGURATION) {
6336 Slog.w(TAG, "Trying to update display configuration for invalid "
6337 + "process, pid=" + pid);
6338 }
6339 return;
6340 }
6341 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6342 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006343 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006344
6345 @Override
6346 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6347 int requestCode, int resultCode, Intent data) {
6348 synchronized (mGlobalLock) {
6349 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006350 if (r != null && r.getActivityStack() != null) {
6351 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6352 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006353 }
6354 }
6355 }
6356
6357 @Override
6358 public void clearPendingResultForActivity(IBinder activityToken,
6359 WeakReference<PendingIntentRecord> pir) {
6360 synchronized (mGlobalLock) {
6361 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6362 if (r != null && r.pendingResults != null) {
6363 r.pendingResults.remove(pir);
6364 }
6365 }
6366 }
6367
6368 @Override
6369 public IIntentSender getIntentSender(int type, String packageName,
6370 int callingUid, int userId, IBinder token, String resultWho,
6371 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6372 Bundle bOptions) {
6373 synchronized (mGlobalLock) {
6374 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6375 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6376 }
6377 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006378
6379 @Override
6380 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6381 synchronized (mGlobalLock) {
6382 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6383 if (r == null) {
6384 return null;
6385 }
6386 if (r.mServiceConnectionsHolder == null) {
6387 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6388 ActivityTaskManagerService.this, r);
6389 }
6390
6391 return r.mServiceConnectionsHolder;
6392 }
6393 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006394
6395 @Override
6396 public Intent getHomeIntent() {
6397 synchronized (mGlobalLock) {
6398 return ActivityTaskManagerService.this.getHomeIntent();
6399 }
6400 }
6401
6402 @Override
6403 public boolean startHomeActivity(int userId, String reason) {
6404 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006405 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006406 }
6407 }
6408
6409 @Override
6410 public boolean startHomeOnAllDisplays(int userId, String reason) {
6411 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006412 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006413 }
6414 }
6415
6416 @Override
6417 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6418 synchronized (mGlobalLock) {
6419 if (mFactoryTest == FACTORY_TEST_OFF) {
6420 return false;
6421 }
6422 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6423 && wpc.mName.equals(mTopComponent.getPackageName())) {
6424 return true;
6425 }
6426 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6427 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6428 }
6429 }
6430
6431 @Override
6432 public void updateTopComponentForFactoryTest() {
6433 synchronized (mGlobalLock) {
6434 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6435 return;
6436 }
6437 final ResolveInfo ri = mContext.getPackageManager()
6438 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6439 final CharSequence errorMsg;
6440 if (ri != null) {
6441 final ActivityInfo ai = ri.activityInfo;
6442 final ApplicationInfo app = ai.applicationInfo;
6443 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6444 mTopAction = Intent.ACTION_FACTORY_TEST;
6445 mTopData = null;
6446 mTopComponent = new ComponentName(app.packageName, ai.name);
6447 errorMsg = null;
6448 } else {
6449 errorMsg = mContext.getResources().getText(
6450 com.android.internal.R.string.factorytest_not_system);
6451 }
6452 } else {
6453 errorMsg = mContext.getResources().getText(
6454 com.android.internal.R.string.factorytest_no_action);
6455 }
6456 if (errorMsg == null) {
6457 return;
6458 }
6459
6460 mTopAction = null;
6461 mTopData = null;
6462 mTopComponent = null;
6463 mUiHandler.post(() -> {
6464 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6465 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006466 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006467 });
6468 }
6469 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006470
6471 @Override
6472 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6473 Runnable finishInstrumentationCallback) {
6474 synchronized (mGlobalLock) {
6475 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006476 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006477
6478 wpc.clearRecentTasks();
6479 wpc.clearActivities();
6480
6481 if (wpc.isInstrumenting()) {
6482 finishInstrumentationCallback.run();
6483 }
6484
Jorim Jaggid0752812018-10-16 16:07:20 +02006485 if (!restarting && hasVisibleActivities) {
6486 mWindowManager.deferSurfaceLayout();
6487 try {
6488 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6489 // If there was nothing to resume, and we are not already restarting
6490 // this process, but there is a visible activity that is hosted by the
6491 // process...then make sure all visible activities are running, taking
6492 // care of restarting this process.
6493 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6494 !PRESERVE_WINDOWS);
6495 }
6496 } finally {
6497 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006498 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006499 }
6500 }
6501 }
6502
6503 @Override
6504 public void closeSystemDialogs(String reason) {
6505 enforceNotIsolatedCaller("closeSystemDialogs");
6506
6507 final int pid = Binder.getCallingPid();
6508 final int uid = Binder.getCallingUid();
6509 final long origId = Binder.clearCallingIdentity();
6510 try {
6511 synchronized (mGlobalLock) {
6512 // Only allow this from foreground processes, so that background
6513 // applications can't abuse it to prevent system UI from being shown.
6514 if (uid >= FIRST_APPLICATION_UID) {
6515 final WindowProcessController proc = mPidMap.get(pid);
6516 if (!proc.isPerceptible()) {
6517 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6518 + " from background process " + proc);
6519 return;
6520 }
6521 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006522 mWindowManager.closeSystemDialogs(reason);
6523
Wale Ogunwaled32da472018-11-16 07:19:28 -08006524 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006525 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006526 // Call into AM outside the synchronized block.
6527 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006528 } finally {
6529 Binder.restoreCallingIdentity(origId);
6530 }
6531 }
6532
6533 @Override
6534 public void cleanupDisabledPackageComponents(
6535 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6536 synchronized (mGlobalLock) {
6537 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006538 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006539 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006540 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006541 mStackSupervisor.scheduleIdleLocked();
6542 }
6543
6544 // Clean-up disabled tasks
6545 getRecentTasks().cleanupDisabledPackageTasksLocked(
6546 packageName, disabledClasses, userId);
6547 }
6548 }
6549
6550 @Override
6551 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6552 int userId) {
6553 synchronized (mGlobalLock) {
6554
6555 boolean didSomething =
6556 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006557 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006558 null, doit, evenPersistent, userId);
6559 return didSomething;
6560 }
6561 }
6562
6563 @Override
6564 public void resumeTopActivities(boolean scheduleIdle) {
6565 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006566 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006567 if (scheduleIdle) {
6568 mStackSupervisor.scheduleIdleLocked();
6569 }
6570 }
6571 }
6572
6573 @Override
6574 public void preBindApplication(WindowProcessController wpc) {
6575 synchronized (mGlobalLock) {
6576 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6577 }
6578 }
6579
6580 @Override
6581 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6582 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006583 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006584 }
6585 }
6586
6587 @Override
6588 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6589 try {
6590 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6591 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6592 }
6593 } catch (RemoteException ex) {
6594 throw new SecurityException("Fail to check is caller a privileged app", ex);
6595 }
6596
6597 synchronized (mGlobalLock) {
6598 final long ident = Binder.clearCallingIdentity();
6599 try {
6600 if (mAmInternal.shouldConfirmCredentials(userId)) {
6601 if (mKeyguardController.isKeyguardLocked()) {
6602 // Showing launcher to avoid user entering credential twice.
6603 startHomeActivity(currentUserId, "notifyLockedProfile");
6604 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006605 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006606 }
6607 } finally {
6608 Binder.restoreCallingIdentity(ident);
6609 }
6610 }
6611 }
6612
6613 @Override
6614 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6615 mAmInternal.enforceCallingPermission(
6616 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6617
6618 synchronized (mGlobalLock) {
6619 final long ident = Binder.clearCallingIdentity();
6620 try {
6621 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6622 FLAG_ACTIVITY_TASK_ON_HOME);
6623 ActivityOptions activityOptions = options != null
6624 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006625 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006626 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006627 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006628 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006629 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006630 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6631 UserHandle.CURRENT);
6632 } finally {
6633 Binder.restoreCallingIdentity(ident);
6634 }
6635 }
6636 }
6637
6638 @Override
6639 public void writeActivitiesToProto(ProtoOutputStream proto) {
6640 synchronized (mGlobalLock) {
6641 // The output proto of "activity --proto activities"
6642 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006643 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006644 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6645 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006646 }
6647 }
6648
6649 @Override
6650 public void saveANRState(String reason) {
6651 synchronized (mGlobalLock) {
6652 final StringWriter sw = new StringWriter();
6653 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6654 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6655 if (reason != null) {
6656 pw.println(" Reason: " + reason);
6657 }
6658 pw.println();
6659 getActivityStartController().dump(pw, " ", null);
6660 pw.println();
6661 pw.println("-------------------------------------------------------------------------------");
6662 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6663 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6664 "" /* header */);
6665 pw.println();
6666 pw.close();
6667
6668 mLastANRState = sw.toString();
6669 }
6670 }
6671
6672 @Override
6673 public void clearSavedANRState() {
6674 synchronized (mGlobalLock) {
6675 mLastANRState = null;
6676 }
6677 }
6678
6679 @Override
6680 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6681 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6682 synchronized (mGlobalLock) {
6683 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6684 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6685 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6686 dumpLastANRLocked(pw);
6687 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6688 dumpLastANRTracesLocked(pw);
6689 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6690 dumpActivityStarterLocked(pw, dumpPackage);
6691 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6692 dumpActivityContainersLocked(pw);
6693 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6694 if (getRecentTasks() != null) {
6695 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6696 }
6697 }
6698 }
6699 }
6700
6701 @Override
6702 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6703 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6704 int wakefulness) {
6705 synchronized (mGlobalLock) {
6706 if (mHomeProcess != null && (dumpPackage == null
6707 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6708 if (needSep) {
6709 pw.println();
6710 needSep = false;
6711 }
6712 pw.println(" mHomeProcess: " + mHomeProcess);
6713 }
6714 if (mPreviousProcess != null && (dumpPackage == null
6715 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6716 if (needSep) {
6717 pw.println();
6718 needSep = false;
6719 }
6720 pw.println(" mPreviousProcess: " + mPreviousProcess);
6721 }
6722 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6723 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6724 StringBuilder sb = new StringBuilder(128);
6725 sb.append(" mPreviousProcessVisibleTime: ");
6726 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6727 pw.println(sb);
6728 }
6729 if (mHeavyWeightProcess != null && (dumpPackage == null
6730 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6731 if (needSep) {
6732 pw.println();
6733 needSep = false;
6734 }
6735 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6736 }
6737 if (dumpPackage == null) {
6738 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006739 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 }
6741 if (dumpAll) {
6742 if (dumpPackage == null) {
6743 pw.println(" mConfigWillChange: "
6744 + getTopDisplayFocusedStack().mConfigWillChange);
6745 }
6746 if (mCompatModePackages.getPackages().size() > 0) {
6747 boolean printed = false;
6748 for (Map.Entry<String, Integer> entry
6749 : mCompatModePackages.getPackages().entrySet()) {
6750 String pkg = entry.getKey();
6751 int mode = entry.getValue();
6752 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6753 continue;
6754 }
6755 if (!printed) {
6756 pw.println(" mScreenCompatPackages:");
6757 printed = true;
6758 }
6759 pw.println(" " + pkg + ": " + mode);
6760 }
6761 }
6762 }
6763
6764 if (dumpPackage == null) {
6765 pw.println(" mWakefulness="
6766 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006767 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 if (mRunningVoice != null) {
6769 pw.println(" mRunningVoice=" + mRunningVoice);
6770 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6771 }
6772 pw.println(" mSleeping=" + mSleeping);
6773 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6774 pw.println(" mVrController=" + mVrController);
6775 }
6776 if (mCurAppTimeTracker != null) {
6777 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6778 }
6779 if (mAllowAppSwitchUids.size() > 0) {
6780 boolean printed = false;
6781 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6782 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6783 for (int j = 0; j < types.size(); j++) {
6784 if (dumpPackage == null ||
6785 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6786 if (needSep) {
6787 pw.println();
6788 needSep = false;
6789 }
6790 if (!printed) {
6791 pw.println(" mAllowAppSwitchUids:");
6792 printed = true;
6793 }
6794 pw.print(" User ");
6795 pw.print(mAllowAppSwitchUids.keyAt(i));
6796 pw.print(": Type ");
6797 pw.print(types.keyAt(j));
6798 pw.print(" = ");
6799 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6800 pw.println();
6801 }
6802 }
6803 }
6804 }
6805 if (dumpPackage == null) {
6806 if (mController != null) {
6807 pw.println(" mController=" + mController
6808 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6809 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006810 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6811 pw.println(" mLaunchingActivityWakeLock="
6812 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 }
6814
6815 return needSep;
6816 }
6817 }
6818
6819 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006820 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6821 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 synchronized (mGlobalLock) {
6823 if (dumpPackage == null) {
6824 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6825 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006826 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6827 if (mRunningVoice != null) {
6828 final long vrToken = proto.start(
6829 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6830 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6831 mRunningVoice.toString());
6832 mVoiceWakeLock.writeToProto(
6833 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6834 proto.end(vrToken);
6835 }
6836 mVrController.writeToProto(proto,
6837 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 if (mController != null) {
6839 final long token = proto.start(CONTROLLER);
6840 proto.write(CONTROLLER, mController.toString());
6841 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6842 proto.end(token);
6843 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006844 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6845 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6846 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 }
6848
6849 if (mHomeProcess != null && (dumpPackage == null
6850 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006851 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006852 }
6853
6854 if (mPreviousProcess != null && (dumpPackage == null
6855 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006856 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6858 }
6859
6860 if (mHeavyWeightProcess != null && (dumpPackage == null
6861 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006862 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863 }
6864
6865 for (Map.Entry<String, Integer> entry
6866 : mCompatModePackages.getPackages().entrySet()) {
6867 String pkg = entry.getKey();
6868 int mode = entry.getValue();
6869 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6870 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6871 proto.write(PACKAGE, pkg);
6872 proto.write(MODE, mode);
6873 proto.end(compatToken);
6874 }
6875 }
6876
6877 if (mCurAppTimeTracker != null) {
6878 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6879 }
6880
6881 }
6882 }
6883
6884 @Override
6885 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6886 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6887 boolean dumpFocusedStackOnly) {
6888 synchronized (mGlobalLock) {
6889 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6890 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6891 }
6892 }
6893
6894 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006895 public void dumpForOom(PrintWriter pw) {
6896 synchronized (mGlobalLock) {
6897 pw.println(" mHomeProcess: " + mHomeProcess);
6898 pw.println(" mPreviousProcess: " + mPreviousProcess);
6899 if (mHeavyWeightProcess != null) {
6900 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6901 }
6902 }
6903 }
6904
6905 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 public boolean canGcNow() {
6907 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006908 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909 }
6910 }
6911
6912 @Override
6913 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006914 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006915 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006916 return top != null ? top.app : null;
6917 }
6918 }
6919
6920 @Override
6921 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006922 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006923 if (mRootActivityContainer != null) {
6924 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006925 }
6926 }
6927 }
6928
6929 @Override
6930 public void scheduleDestroyAllActivities(String reason) {
6931 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006932 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006933 }
6934 }
6935
6936 @Override
6937 public void removeUser(int userId) {
6938 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006939 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 }
6941 }
6942
6943 @Override
6944 public boolean switchUser(int userId, UserState userState) {
6945 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006946 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 }
6948 }
6949
6950 @Override
6951 public void onHandleAppCrash(WindowProcessController wpc) {
6952 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006953 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 }
6955 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006956
6957 @Override
6958 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6959 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006960 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006961 }
6962 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006963
6964 @Override
6965 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006966 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006967 mActiveUids.put(uid, procState);
6968 }
6969 }
6970
6971 @Override
6972 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006973 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006974 mActiveUids.remove(uid);
6975 }
6976 }
6977
6978 @Override
6979 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006980 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006981 mActiveUids.clear();
6982 }
6983 }
6984
6985 @Override
6986 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006987 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006988 if (mActiveUids.get(uid) != null) {
6989 mActiveUids.put(uid, procState);
6990 }
6991 }
6992 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006993
6994 @Override
6995 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006996 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006997 mPendingTempWhitelist.put(uid, tag);
6998 }
6999 }
7000
7001 @Override
7002 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007003 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007004 mPendingTempWhitelist.remove(uid);
7005 }
7006 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007007
7008 @Override
7009 public boolean handleAppCrashInActivityController(String processName, int pid,
7010 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7011 Runnable killCrashingAppCallback) {
7012 synchronized (mGlobalLock) {
7013 if (mController == null) {
7014 return false;
7015 }
7016
7017 try {
7018 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7019 stackTrace)) {
7020 killCrashingAppCallback.run();
7021 return true;
7022 }
7023 } catch (RemoteException e) {
7024 mController = null;
7025 Watchdog.getInstance().setActivityController(null);
7026 }
7027 return false;
7028 }
7029 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007030
7031 @Override
7032 public void removeRecentTasksByPackageName(String packageName, int userId) {
7033 synchronized (mGlobalLock) {
7034 mRecentTasks.removeTasksByPackageName(packageName, userId);
7035 }
7036 }
7037
7038 @Override
7039 public void cleanupRecentTasksForUser(int userId) {
7040 synchronized (mGlobalLock) {
7041 mRecentTasks.cleanupLocked(userId);
7042 }
7043 }
7044
7045 @Override
7046 public void loadRecentTasksForUser(int userId) {
7047 synchronized (mGlobalLock) {
7048 mRecentTasks.loadUserRecentsLocked(userId);
7049 }
7050 }
7051
7052 @Override
7053 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7054 synchronized (mGlobalLock) {
7055 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7056 }
7057 }
7058
7059 @Override
7060 public void flushRecentTasks() {
7061 mRecentTasks.flush();
7062 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007063
7064 @Override
7065 public WindowProcessController getHomeProcess() {
7066 synchronized (mGlobalLock) {
7067 return mHomeProcess;
7068 }
7069 }
7070
7071 @Override
7072 public WindowProcessController getPreviousProcess() {
7073 synchronized (mGlobalLock) {
7074 return mPreviousProcess;
7075 }
7076 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007077
7078 @Override
7079 public void clearLockedTasks(String reason) {
7080 synchronized (mGlobalLock) {
7081 getLockTaskController().clearLockedTasks(reason);
7082 }
7083 }
7084
7085 @Override
7086 public void updateUserConfiguration() {
7087 synchronized (mGlobalLock) {
7088 final Configuration configuration = new Configuration(getGlobalConfiguration());
7089 final int currentUserId = mAmInternal.getCurrentUserId();
7090 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7091 configuration, currentUserId, Settings.System.canWrite(mContext));
7092 updateConfigurationLocked(configuration, null /* starting */,
7093 false /* initLocale */, false /* persistent */, currentUserId,
7094 false /* deferResume */);
7095 }
7096 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007097
7098 @Override
7099 public boolean canShowErrorDialogs() {
7100 synchronized (mGlobalLock) {
7101 return mShowDialogs && !mSleeping && !mShuttingDown
7102 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7103 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7104 mAmInternal.getCurrentUserId())
7105 && !(UserManager.isDeviceInDemoMode(mContext)
7106 && mAmInternal.getCurrentUser().isDemo());
7107 }
7108 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007109
7110 @Override
7111 public void setProfileApp(String profileApp) {
7112 synchronized (mGlobalLock) {
7113 mProfileApp = profileApp;
7114 }
7115 }
7116
7117 @Override
7118 public void setProfileProc(WindowProcessController wpc) {
7119 synchronized (mGlobalLock) {
7120 mProfileProc = wpc;
7121 }
7122 }
7123
7124 @Override
7125 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7126 synchronized (mGlobalLock) {
7127 mProfilerInfo = profilerInfo;
7128 }
7129 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007130
7131 @Override
7132 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7133 synchronized (mGlobalLock) {
7134 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7135 }
7136 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007137
7138 @Override
7139 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7140 synchronized (mGlobalLock) {
7141 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7142 }
7143 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007144
7145 @Override
7146 public boolean isUidForeground(int uid) {
7147 synchronized (mGlobalLock) {
7148 return ActivityTaskManagerService.this.isUidForeground(uid);
7149 }
7150 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007151
7152 @Override
7153 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7154 synchronized (mGlobalLock) {
7155 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7156 }
7157 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007158 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007159}