blob: 4a9e41e261ba0fc4ead03994d5c98ee833881545 [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
Yunfan Chen585f2932019-01-29 16:04:45 +0900765 /** For test purpose only. */
766 @VisibleForTesting
767 public ActivityTaskManagerInternal getAtmInternal() {
768 return mInternal;
769 }
770
Riddle Hsud93a6c42018-11-29 21:50:06 +0800771 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
772 Looper looper) {
773 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700775 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700776 final File systemDir = SystemServiceManager.ensureSystemDir();
777 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
778 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700779 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700780
781 mTempConfig.setToDefaults();
782 mTempConfig.setLocales(LocaleList.getDefault());
783 mConfigurationSeq = mTempConfig.seq = 1;
784 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800785 mRootActivityContainer = new RootActivityContainer(this);
786 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700787
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700788 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700789 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700790 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700791 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700792 mRecentTasks = createRecentTasks();
793 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700794 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700795 mKeyguardController = mStackSupervisor.getKeyguardController();
796 }
797
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700798 public void onActivityManagerInternalAdded() {
799 synchronized (mGlobalLock) {
800 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
801 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
802 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700803 }
804
Yunfan Chen75157d72018-07-27 14:47:21 +0900805 int increaseConfigurationSeqLocked() {
806 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
807 return mConfigurationSeq;
808 }
809
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700810 protected ActivityStackSupervisor createStackSupervisor() {
811 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
812 supervisor.initialize();
813 return supervisor;
814 }
815
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700816 public void setWindowManager(WindowManagerService wm) {
817 synchronized (mGlobalLock) {
818 mWindowManager = wm;
819 mLockTaskController.setWindowManager(wm);
820 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800821 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700822 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700823 }
824
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700825 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
826 synchronized (mGlobalLock) {
827 mUsageStatsInternal = usageStatsManager;
828 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700829 }
830
Wale Ogunwalef6733932018-06-27 05:14:34 -0700831 UserManagerService getUserManager() {
832 if (mUserManager == null) {
833 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
834 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
835 }
836 return mUserManager;
837 }
838
839 AppOpsService getAppOpsService() {
840 if (mAppOpsService == null) {
841 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
842 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
843 }
844 return mAppOpsService;
845 }
846
847 boolean hasUserRestriction(String restriction, int userId) {
848 return getUserManager().hasUserRestriction(restriction, userId);
849 }
850
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700851 protected RecentTasks createRecentTasks() {
852 return new RecentTasks(this, mStackSupervisor);
853 }
854
855 RecentTasks getRecentTasks() {
856 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700857 }
858
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700859 ClientLifecycleManager getLifecycleManager() {
860 return mLifecycleManager;
861 }
862
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700863 ActivityStartController getActivityStartController() {
864 return mActivityStartController;
865 }
866
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700867 TaskChangeNotificationController getTaskChangeNotificationController() {
868 return mTaskChangeNotificationController;
869 }
870
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700871 LockTaskController getLockTaskController() {
872 return mLockTaskController;
873 }
874
Yunfan Chen75157d72018-07-27 14:47:21 +0900875 /**
876 * Return the global configuration used by the process corresponding to the input pid. This is
877 * usually the global configuration with some overrides specific to that process.
878 */
879 Configuration getGlobalConfigurationForCallingPid() {
880 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800881 return getGlobalConfigurationForPid(pid);
882 }
883
884 /**
885 * Return the global configuration used by the process corresponding to the given pid.
886 */
887 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900888 if (pid == MY_PID || pid < 0) {
889 return getGlobalConfiguration();
890 }
891 synchronized (mGlobalLock) {
892 final WindowProcessController app = mPidMap.get(pid);
893 return app != null ? app.getConfiguration() : getGlobalConfiguration();
894 }
895 }
896
897 /**
898 * Return the device configuration info used by the process corresponding to the input pid.
899 * The value is consistent with the global configuration for the process.
900 */
901 @Override
902 public ConfigurationInfo getDeviceConfigurationInfo() {
903 ConfigurationInfo config = new ConfigurationInfo();
904 synchronized (mGlobalLock) {
905 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
906 config.reqTouchScreen = globalConfig.touchscreen;
907 config.reqKeyboardType = globalConfig.keyboard;
908 config.reqNavigation = globalConfig.navigation;
909 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
910 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
911 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
912 }
913 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
914 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
915 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
916 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700917 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900918 }
919 return config;
920 }
921
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700922 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700923 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700924 }
925
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700926 public static final class Lifecycle extends SystemService {
927 private final ActivityTaskManagerService mService;
928
929 public Lifecycle(Context context) {
930 super(context);
931 mService = new ActivityTaskManagerService(context);
932 }
933
934 @Override
935 public void onStart() {
936 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700937 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700938 }
939
Garfield Tan891146c2018-10-09 12:14:00 -0700940 @Override
941 public void onUnlockUser(int userId) {
942 synchronized (mService.getGlobalLock()) {
943 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
944 }
945 }
946
947 @Override
948 public void onCleanupUser(int userId) {
949 synchronized (mService.getGlobalLock()) {
950 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
951 }
952 }
953
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700954 public ActivityTaskManagerService getService() {
955 return mService;
956 }
957 }
958
959 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700960 public final int startActivity(IApplicationThread caller, String callingPackage,
961 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
962 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
963 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
964 resultWho, requestCode, startFlags, profilerInfo, bOptions,
965 UserHandle.getCallingUserId());
966 }
967
968 @Override
969 public final int startActivities(IApplicationThread caller, String callingPackage,
970 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
971 int userId) {
972 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700973 enforceNotIsolatedCaller(reason);
974 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700975 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000976 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
977 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
978 reason, null /* originatingPendingIntent */,
979 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980 }
981
982 @Override
983 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
984 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
985 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
986 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
987 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
988 true /*validateIncomingUser*/);
989 }
990
991 int startActivityAsUser(IApplicationThread caller, String callingPackage,
992 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
993 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
994 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700995 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700997 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
999
1000 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001001 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001002 .setCaller(caller)
1003 .setCallingPackage(callingPackage)
1004 .setResolvedType(resolvedType)
1005 .setResultTo(resultTo)
1006 .setResultWho(resultWho)
1007 .setRequestCode(requestCode)
1008 .setStartFlags(startFlags)
1009 .setProfilerInfo(profilerInfo)
1010 .setActivityOptions(bOptions)
1011 .setMayWait(userId)
1012 .execute();
1013
1014 }
1015
1016 @Override
1017 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1018 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001019 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1020 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 // Refuse possible leaked file descriptors
1022 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1023 throw new IllegalArgumentException("File descriptors passed in Intent");
1024 }
1025
1026 if (!(target instanceof PendingIntentRecord)) {
1027 throw new IllegalArgumentException("Bad PendingIntent object");
1028 }
1029
1030 PendingIntentRecord pir = (PendingIntentRecord)target;
1031
1032 synchronized (mGlobalLock) {
1033 // If this is coming from the currently resumed activity, it is
1034 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001035 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 if (stack.mResumedActivity != null &&
1037 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001038 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 }
1040 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 }
1044
1045 @Override
1046 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1047 Bundle bOptions) {
1048 // Refuse possible leaked file descriptors
1049 if (intent != null && intent.hasFileDescriptors()) {
1050 throw new IllegalArgumentException("File descriptors passed in Intent");
1051 }
1052 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1053
1054 synchronized (mGlobalLock) {
1055 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1056 if (r == null) {
1057 SafeActivityOptions.abort(options);
1058 return false;
1059 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001060 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 // The caller is not running... d'oh!
1062 SafeActivityOptions.abort(options);
1063 return false;
1064 }
1065 intent = new Intent(intent);
1066 // The caller is not allowed to change the data.
1067 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1068 // And we are resetting to find the next component...
1069 intent.setComponent(null);
1070
1071 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1072
1073 ActivityInfo aInfo = null;
1074 try {
1075 List<ResolveInfo> resolves =
1076 AppGlobals.getPackageManager().queryIntentActivities(
1077 intent, r.resolvedType,
1078 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1079 UserHandle.getCallingUserId()).getList();
1080
1081 // Look for the original activity in the list...
1082 final int N = resolves != null ? resolves.size() : 0;
1083 for (int i=0; i<N; i++) {
1084 ResolveInfo rInfo = resolves.get(i);
1085 if (rInfo.activityInfo.packageName.equals(r.packageName)
1086 && rInfo.activityInfo.name.equals(r.info.name)) {
1087 // We found the current one... the next matching is
1088 // after it.
1089 i++;
1090 if (i<N) {
1091 aInfo = resolves.get(i).activityInfo;
1092 }
1093 if (debug) {
1094 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1095 + "/" + r.info.name);
1096 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1097 ? "null" : aInfo.packageName + "/" + aInfo.name));
1098 }
1099 break;
1100 }
1101 }
1102 } catch (RemoteException e) {
1103 }
1104
1105 if (aInfo == null) {
1106 // Nobody who is next!
1107 SafeActivityOptions.abort(options);
1108 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1109 return false;
1110 }
1111
1112 intent.setComponent(new ComponentName(
1113 aInfo.applicationInfo.packageName, aInfo.name));
1114 intent.setFlags(intent.getFlags()&~(
1115 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1116 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1117 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1118 FLAG_ACTIVITY_NEW_TASK));
1119
1120 // Okay now we need to start the new activity, replacing the currently running activity.
1121 // This is a little tricky because we want to start the new one as if the current one is
1122 // finished, but not finish the current one first so that there is no flicker.
1123 // And thus...
1124 final boolean wasFinishing = r.finishing;
1125 r.finishing = true;
1126
1127 // Propagate reply information over to the new activity.
1128 final ActivityRecord resultTo = r.resultTo;
1129 final String resultWho = r.resultWho;
1130 final int requestCode = r.requestCode;
1131 r.resultTo = null;
1132 if (resultTo != null) {
1133 resultTo.removeResultsLocked(r, resultWho, requestCode);
1134 }
1135
1136 final long origId = Binder.clearCallingIdentity();
1137 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001138 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001139 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001140 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001141 .setResolvedType(r.resolvedType)
1142 .setActivityInfo(aInfo)
1143 .setResultTo(resultTo != null ? resultTo.appToken : null)
1144 .setResultWho(resultWho)
1145 .setRequestCode(requestCode)
1146 .setCallingPid(-1)
1147 .setCallingUid(r.launchedFromUid)
1148 .setCallingPackage(r.launchedFromPackage)
1149 .setRealCallingPid(-1)
1150 .setRealCallingUid(r.launchedFromUid)
1151 .setActivityOptions(options)
1152 .execute();
1153 Binder.restoreCallingIdentity(origId);
1154
1155 r.finishing = wasFinishing;
1156 if (res != ActivityManager.START_SUCCESS) {
1157 return false;
1158 }
1159 return true;
1160 }
1161 }
1162
1163 @Override
1164 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1165 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1166 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1167 final WaitResult res = new WaitResult();
1168 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001169 enforceNotIsolatedCaller("startActivityAndWait");
1170 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1171 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001172 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001173 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001174 .setCaller(caller)
1175 .setCallingPackage(callingPackage)
1176 .setResolvedType(resolvedType)
1177 .setResultTo(resultTo)
1178 .setResultWho(resultWho)
1179 .setRequestCode(requestCode)
1180 .setStartFlags(startFlags)
1181 .setActivityOptions(bOptions)
1182 .setMayWait(userId)
1183 .setProfilerInfo(profilerInfo)
1184 .setWaitResult(res)
1185 .execute();
1186 }
1187 return res;
1188 }
1189
1190 @Override
1191 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1192 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1193 int startFlags, Configuration config, Bundle bOptions, int userId) {
1194 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001195 enforceNotIsolatedCaller("startActivityWithConfig");
1196 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1197 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001198 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001199 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001200 .setCaller(caller)
1201 .setCallingPackage(callingPackage)
1202 .setResolvedType(resolvedType)
1203 .setResultTo(resultTo)
1204 .setResultWho(resultWho)
1205 .setRequestCode(requestCode)
1206 .setStartFlags(startFlags)
1207 .setGlobalConfiguration(config)
1208 .setActivityOptions(bOptions)
1209 .setMayWait(userId)
1210 .execute();
1211 }
1212 }
1213
Alison Cichowlas3e340502018-08-07 17:15:01 -04001214
1215 @Override
1216 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1217 int callingUid = Binder.getCallingUid();
1218 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1219 throw new SecurityException("Only the system process can request a permission token, "
1220 + "received request from uid: " + callingUid);
1221 }
1222 IBinder permissionToken = new Binder();
1223 synchronized (mGlobalLock) {
1224 mStartActivitySources.put(permissionToken, delegatorToken);
1225 }
1226
1227 Message expireMsg = PooledLambda.obtainMessage(
1228 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1229 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1230
1231 Message forgetMsg = PooledLambda.obtainMessage(
1232 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1233 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1234
1235 return permissionToken;
1236 }
1237
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 @Override
1239 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1240 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001241 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1242 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001243 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001244 // permission grants) as any app that may launch one of your own activities. So we only
1245 // allow this in two cases:
1246 // 1) The caller is an activity that is part of the core framework, and then only when it
1247 // is running as the system.
1248 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1249 // can only be requested by a system activity, which may then delegate this call to
1250 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001251 final ActivityRecord sourceRecord;
1252 final int targetUid;
1253 final String targetPackage;
1254 final boolean isResolver;
1255 synchronized (mGlobalLock) {
1256 if (resultTo == null) {
1257 throw new SecurityException("Must be called from an activity");
1258 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001259 final IBinder sourceToken;
1260 if (permissionToken != null) {
1261 // To even attempt to use a permissionToken, an app must also have this signature
1262 // permission.
1263 mAmInternal.enforceCallingPermission(
1264 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1265 "startActivityAsCaller");
1266 // If called with a permissionToken, we want the sourceRecord from the delegator
1267 // activity that requested this token.
1268 sourceToken = mStartActivitySources.remove(permissionToken);
1269 if (sourceToken == null) {
1270 // Invalid permissionToken, check if it recently expired.
1271 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1272 throw new SecurityException("Called with expired permission token: "
1273 + permissionToken);
1274 } else {
1275 throw new SecurityException("Called with invalid permission token: "
1276 + permissionToken);
1277 }
1278 }
1279 } else {
1280 // This method was called directly by the source.
1281 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283
Wale Ogunwaled32da472018-11-16 07:19:28 -08001284 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285 if (sourceRecord == null) {
1286 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 }
1288 if (sourceRecord.app == null) {
1289 throw new SecurityException("Called without a process attached to activity");
1290 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001291
1292 // Whether called directly or from a delegate, the source activity must be from the
1293 // android package.
1294 if (!sourceRecord.info.packageName.equals("android")) {
1295 throw new SecurityException("Must be called from an activity that is "
1296 + "declared in the android package");
1297 }
1298
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001299 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001300 // This is still okay, as long as this activity is running under the
1301 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001302 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001303 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001304 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 + " must be system uid or original calling uid "
1306 + sourceRecord.launchedFromUid);
1307 }
1308 }
1309 if (ignoreTargetSecurity) {
1310 if (intent.getComponent() == null) {
1311 throw new SecurityException(
1312 "Component must be specified with ignoreTargetSecurity");
1313 }
1314 if (intent.getSelector() != null) {
1315 throw new SecurityException(
1316 "Selector not allowed with ignoreTargetSecurity");
1317 }
1318 }
1319 targetUid = sourceRecord.launchedFromUid;
1320 targetPackage = sourceRecord.launchedFromPackage;
1321 isResolver = sourceRecord.isResolverOrChildActivity();
1322 }
1323
1324 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001325 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 }
1327
1328 // TODO: Switch to user app stacks here.
1329 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001330 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001331 .setCallingUid(targetUid)
1332 .setCallingPackage(targetPackage)
1333 .setResolvedType(resolvedType)
1334 .setResultTo(resultTo)
1335 .setResultWho(resultWho)
1336 .setRequestCode(requestCode)
1337 .setStartFlags(startFlags)
1338 .setActivityOptions(bOptions)
1339 .setMayWait(userId)
1340 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1341 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1342 .execute();
1343 } catch (SecurityException e) {
1344 // XXX need to figure out how to propagate to original app.
1345 // A SecurityException here is generally actually a fault of the original
1346 // calling activity (such as a fairly granting permissions), so propagate it
1347 // back to them.
1348 /*
1349 StringBuilder msg = new StringBuilder();
1350 msg.append("While launching");
1351 msg.append(intent.toString());
1352 msg.append(": ");
1353 msg.append(e.getMessage());
1354 */
1355 throw e;
1356 }
1357 }
1358
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001359 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1360 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1361 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1362 }
1363
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 @Override
1365 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1366 Intent intent, String resolvedType, IVoiceInteractionSession session,
1367 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1368 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001369 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 if (session == null || interactor == null) {
1371 throw new NullPointerException("null session or interactor");
1372 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001373 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001375 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001376 .setCallingUid(callingUid)
1377 .setCallingPackage(callingPackage)
1378 .setResolvedType(resolvedType)
1379 .setVoiceSession(session)
1380 .setVoiceInteractor(interactor)
1381 .setStartFlags(startFlags)
1382 .setProfilerInfo(profilerInfo)
1383 .setActivityOptions(bOptions)
1384 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001385 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 .execute();
1387 }
1388
1389 @Override
1390 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1391 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1393 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001395 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .setCallingUid(callingUid)
1397 .setCallingPackage(callingPackage)
1398 .setResolvedType(resolvedType)
1399 .setActivityOptions(bOptions)
1400 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001401 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 .execute();
1403 }
1404
1405 @Override
1406 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1407 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001408 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 final int callingPid = Binder.getCallingPid();
1410 final long origId = Binder.clearCallingIdentity();
1411 try {
1412 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001413 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1414 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415
1416 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001417 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1418 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1420 recentsUid, assistDataReceiver);
1421 }
1422 } finally {
1423 Binder.restoreCallingIdentity(origId);
1424 }
1425 }
1426
1427 @Override
1428 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001429 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001430 "startActivityFromRecents()");
1431
1432 final int callingPid = Binder.getCallingPid();
1433 final int callingUid = Binder.getCallingUid();
1434 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1435 final long origId = Binder.clearCallingIdentity();
1436 try {
1437 synchronized (mGlobalLock) {
1438 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1439 safeOptions);
1440 }
1441 } finally {
1442 Binder.restoreCallingIdentity(origId);
1443 }
1444 }
1445
1446 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001447 * Public API to check if the client is allowed to start an activity on specified display.
1448 *
1449 * If the target display is private or virtual, some restrictions will apply.
1450 *
1451 * @param displayId Target display id.
1452 * @param intent Intent used to launch the activity.
1453 * @param resolvedType The MIME type of the intent.
1454 * @param userId The id of the user for whom the call is made.
1455 * @return {@code true} if a call to start an activity on the target display should succeed and
1456 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1457 */
1458 @Override
1459 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1460 String resolvedType, int userId) {
1461 final int callingUid = Binder.getCallingUid();
1462 final int callingPid = Binder.getCallingPid();
1463 final long origId = Binder.clearCallingIdentity();
1464
1465 try {
1466 // Collect information about the target of the Intent.
1467 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1468 0 /* startFlags */, null /* profilerInfo */, userId,
1469 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1470 UserHandle.USER_NULL));
1471 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1472
1473 synchronized (mGlobalLock) {
1474 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1475 aInfo);
1476 }
1477 } finally {
1478 Binder.restoreCallingIdentity(origId);
1479 }
1480 }
1481
1482 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 * This is the internal entry point for handling Activity.finish().
1484 *
1485 * @param token The Binder token referencing the Activity we want to finish.
1486 * @param resultCode Result code, if any, from this Activity.
1487 * @param resultData Result data (Intent), if any, from this Activity.
1488 * @param finishTask Whether to finish the task associated with this Activity.
1489 *
1490 * @return Returns true if the activity successfully finished, or false if it is still running.
1491 */
1492 @Override
1493 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1494 int finishTask) {
1495 // Refuse possible leaked file descriptors
1496 if (resultData != null && resultData.hasFileDescriptors()) {
1497 throw new IllegalArgumentException("File descriptors passed in Intent");
1498 }
1499
1500 synchronized (mGlobalLock) {
1501 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1502 if (r == null) {
1503 return true;
1504 }
1505 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001506 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 ActivityRecord rootR = tr.getRootActivity();
1508 if (rootR == null) {
1509 Slog.w(TAG, "Finishing task with all activities already finished");
1510 }
1511 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1512 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001513 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001514 return false;
1515 }
1516
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001517 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1518 // We should consolidate.
1519 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001521 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001522 if (next != null) {
1523 // ask watcher if this is allowed
1524 boolean resumeOK = true;
1525 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001526 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001527 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001528 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001529 Watchdog.getInstance().setActivityController(null);
1530 }
1531
1532 if (!resumeOK) {
1533 Slog.i(TAG, "Not finishing activity because controller resumed");
1534 return false;
1535 }
1536 }
1537 }
1538 final long origId = Binder.clearCallingIdentity();
1539 try {
1540 boolean res;
1541 final boolean finishWithRootActivity =
1542 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1543 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1544 || (finishWithRootActivity && r == rootR)) {
1545 // If requested, remove the task that is associated to this activity only if it
1546 // was the root activity in the task. The result code and data is ignored
1547 // because we don't support returning them across task boundaries. Also, to
1548 // keep backwards compatibility we remove the task from recents when finishing
1549 // task with root activity.
1550 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1551 finishWithRootActivity, "finish-activity");
1552 if (!res) {
1553 Slog.i(TAG, "Removing task failed to finish activity");
1554 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001555 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001556 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 } else {
1558 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1559 resultData, "app-request", true);
1560 if (!res) {
1561 Slog.i(TAG, "Failed to finish by app-request");
1562 }
1563 }
1564 return res;
1565 } finally {
1566 Binder.restoreCallingIdentity(origId);
1567 }
1568 }
1569 }
1570
1571 @Override
1572 public boolean finishActivityAffinity(IBinder token) {
1573 synchronized (mGlobalLock) {
1574 final long origId = Binder.clearCallingIdentity();
1575 try {
1576 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1577 if (r == null) {
1578 return false;
1579 }
1580
1581 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1582 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001583 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001584 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 return false;
1586 }
1587 return task.getStack().finishActivityAffinityLocked(r);
1588 } finally {
1589 Binder.restoreCallingIdentity(origId);
1590 }
1591 }
1592 }
1593
1594 @Override
1595 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1596 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001597 try {
1598 WindowProcessController proc = null;
1599 synchronized (mGlobalLock) {
1600 ActivityStack stack = ActivityRecord.getStackLocked(token);
1601 if (stack == null) {
1602 return;
1603 }
1604 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1605 false /* fromTimeout */, false /* processPausingActivities */, config);
1606 if (r != null) {
1607 proc = r.app;
1608 }
1609 if (stopProfiling && proc != null) {
1610 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 }
1612 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001613 } finally {
1614 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 }
1617
1618 @Override
1619 public final void activityResumed(IBinder token) {
1620 final long origId = Binder.clearCallingIdentity();
1621 synchronized (mGlobalLock) {
1622 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001623 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001624 }
1625 Binder.restoreCallingIdentity(origId);
1626 }
1627
1628 @Override
1629 public final void activityPaused(IBinder token) {
1630 final long origId = Binder.clearCallingIdentity();
1631 synchronized (mGlobalLock) {
1632 ActivityStack stack = ActivityRecord.getStackLocked(token);
1633 if (stack != null) {
1634 stack.activityPausedLocked(token, false);
1635 }
1636 }
1637 Binder.restoreCallingIdentity(origId);
1638 }
1639
1640 @Override
1641 public final void activityStopped(IBinder token, Bundle icicle,
1642 PersistableBundle persistentState, CharSequence description) {
1643 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1644
1645 // Refuse possible leaked file descriptors
1646 if (icicle != null && icicle.hasFileDescriptors()) {
1647 throw new IllegalArgumentException("File descriptors passed in Bundle");
1648 }
1649
1650 final long origId = Binder.clearCallingIdentity();
1651
1652 synchronized (mGlobalLock) {
1653 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1654 if (r != null) {
1655 r.activityStoppedLocked(icicle, persistentState, description);
1656 }
1657 }
1658
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001659 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660
1661 Binder.restoreCallingIdentity(origId);
1662 }
1663
1664 @Override
1665 public final void activityDestroyed(IBinder token) {
1666 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1667 synchronized (mGlobalLock) {
1668 ActivityStack stack = ActivityRecord.getStackLocked(token);
1669 if (stack != null) {
1670 stack.activityDestroyedLocked(token, "activityDestroyed");
1671 }
1672 }
1673 }
1674
1675 @Override
1676 public final void activityRelaunched(IBinder token) {
1677 final long origId = Binder.clearCallingIdentity();
1678 synchronized (mGlobalLock) {
1679 mStackSupervisor.activityRelaunchedLocked(token);
1680 }
1681 Binder.restoreCallingIdentity(origId);
1682 }
1683
1684 public final void activitySlept(IBinder token) {
1685 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1686
1687 final long origId = Binder.clearCallingIdentity();
1688
1689 synchronized (mGlobalLock) {
1690 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1691 if (r != null) {
1692 mStackSupervisor.activitySleptLocked(r);
1693 }
1694 }
1695
1696 Binder.restoreCallingIdentity(origId);
1697 }
1698
1699 @Override
1700 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1701 synchronized (mGlobalLock) {
1702 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1703 if (r == null) {
1704 return;
1705 }
1706 final long origId = Binder.clearCallingIdentity();
1707 try {
1708 r.setRequestedOrientation(requestedOrientation);
1709 } finally {
1710 Binder.restoreCallingIdentity(origId);
1711 }
1712 }
1713 }
1714
1715 @Override
1716 public int getRequestedOrientation(IBinder token) {
1717 synchronized (mGlobalLock) {
1718 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1719 if (r == null) {
1720 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1721 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001722 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 }
1724 }
1725
1726 @Override
1727 public void setImmersive(IBinder token, boolean immersive) {
1728 synchronized (mGlobalLock) {
1729 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1730 if (r == null) {
1731 throw new IllegalArgumentException();
1732 }
1733 r.immersive = immersive;
1734
1735 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001736 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001738 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 }
1740 }
1741 }
1742
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001743 void applyUpdateLockStateLocked(ActivityRecord r) {
1744 // Modifications to the UpdateLock state are done on our handler, outside
1745 // the activity manager's locks. The new state is determined based on the
1746 // state *now* of the relevant activity record. The object is passed to
1747 // the handler solely for logging detail, not to be consulted/modified.
1748 final boolean nextState = r != null && r.immersive;
1749 mH.post(() -> {
1750 if (mUpdateLock.isHeld() != nextState) {
1751 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1752 "Applying new update lock state '" + nextState + "' for " + r);
1753 if (nextState) {
1754 mUpdateLock.acquire();
1755 } else {
1756 mUpdateLock.release();
1757 }
1758 }
1759 });
1760 }
1761
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001762 @Override
1763 public boolean isImmersive(IBinder token) {
1764 synchronized (mGlobalLock) {
1765 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1766 if (r == null) {
1767 throw new IllegalArgumentException();
1768 }
1769 return r.immersive;
1770 }
1771 }
1772
1773 @Override
1774 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001775 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001776 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001777 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 return (r != null) ? r.immersive : false;
1779 }
1780 }
1781
1782 @Override
1783 public void overridePendingTransition(IBinder token, String packageName,
1784 int enterAnim, int exitAnim) {
1785 synchronized (mGlobalLock) {
1786 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1787 if (self == null) {
1788 return;
1789 }
1790
1791 final long origId = Binder.clearCallingIdentity();
1792
1793 if (self.isState(
1794 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001795 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001796 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001797 }
1798
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801 }
1802
1803 @Override
1804 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001805 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001807 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001808 if (r == null) {
1809 return ActivityManager.COMPAT_MODE_UNKNOWN;
1810 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001811 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 }
1813 }
1814
1815 @Override
1816 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001817 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001819 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001820 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001821 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001822 if (r == null) {
1823 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1824 return;
1825 }
1826 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001827 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 }
1829 }
1830
1831 @Override
1832 public int getLaunchedFromUid(IBinder activityToken) {
1833 ActivityRecord srec;
1834 synchronized (mGlobalLock) {
1835 srec = ActivityRecord.forTokenLocked(activityToken);
1836 }
1837 if (srec == null) {
1838 return -1;
1839 }
1840 return srec.launchedFromUid;
1841 }
1842
1843 @Override
1844 public String getLaunchedFromPackage(IBinder activityToken) {
1845 ActivityRecord srec;
1846 synchronized (mGlobalLock) {
1847 srec = ActivityRecord.forTokenLocked(activityToken);
1848 }
1849 if (srec == null) {
1850 return null;
1851 }
1852 return srec.launchedFromPackage;
1853 }
1854
1855 @Override
1856 public boolean convertFromTranslucent(IBinder token) {
1857 final long origId = Binder.clearCallingIdentity();
1858 try {
1859 synchronized (mGlobalLock) {
1860 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1861 if (r == null) {
1862 return false;
1863 }
1864 final boolean translucentChanged = r.changeWindowTranslucency(true);
1865 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001866 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 return translucentChanged;
1870 }
1871 } finally {
1872 Binder.restoreCallingIdentity(origId);
1873 }
1874 }
1875
1876 @Override
1877 public boolean convertToTranslucent(IBinder token, Bundle options) {
1878 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1879 final long origId = Binder.clearCallingIdentity();
1880 try {
1881 synchronized (mGlobalLock) {
1882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1883 if (r == null) {
1884 return false;
1885 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001886 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001887 int index = task.mActivities.lastIndexOf(r);
1888 if (index > 0) {
1889 ActivityRecord under = task.mActivities.get(index - 1);
1890 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1891 }
1892 final boolean translucentChanged = r.changeWindowTranslucency(false);
1893 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001894 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001896 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001897 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001898 return translucentChanged;
1899 }
1900 } finally {
1901 Binder.restoreCallingIdentity(origId);
1902 }
1903 }
1904
1905 @Override
1906 public void notifyActivityDrawn(IBinder token) {
1907 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1908 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001909 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001910 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001911 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001912 }
1913 }
1914 }
1915
1916 @Override
1917 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1918 synchronized (mGlobalLock) {
1919 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1920 if (r == null) {
1921 return;
1922 }
1923 r.reportFullyDrawnLocked(restoredFromBundle);
1924 }
1925 }
1926
1927 @Override
1928 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1929 synchronized (mGlobalLock) {
1930 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1931 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1932 return stack.mDisplayId;
1933 }
1934 return DEFAULT_DISPLAY;
1935 }
1936 }
1937
1938 @Override
1939 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001940 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 long ident = Binder.clearCallingIdentity();
1942 try {
1943 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001944 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001946 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 }
1948 return null;
1949 }
1950 } finally {
1951 Binder.restoreCallingIdentity(ident);
1952 }
1953 }
1954
1955 @Override
1956 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001957 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1959 final long callingId = Binder.clearCallingIdentity();
1960 try {
1961 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001962 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 if (stack == null) {
1964 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1965 return;
1966 }
1967 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001968 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001969 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 }
1971 }
1972 } finally {
1973 Binder.restoreCallingIdentity(callingId);
1974 }
1975 }
1976
1977 @Override
1978 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001979 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1981 final long callingId = Binder.clearCallingIdentity();
1982 try {
1983 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001984 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001985 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 if (task == null) {
1987 return;
1988 }
1989 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001990 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001991 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 }
1993 }
1994 } finally {
1995 Binder.restoreCallingIdentity(callingId);
1996 }
1997 }
1998
1999 @Override
2000 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002001 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 synchronized (mGlobalLock) {
2003 final long ident = Binder.clearCallingIdentity();
2004 try {
2005 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2006 "remove-task");
2007 } finally {
2008 Binder.restoreCallingIdentity(ident);
2009 }
2010 }
2011 }
2012
2013 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002014 public void removeAllVisibleRecentTasks() {
2015 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2016 synchronized (mGlobalLock) {
2017 final long ident = Binder.clearCallingIdentity();
2018 try {
2019 getRecentTasks().removeAllVisibleTasks();
2020 } finally {
2021 Binder.restoreCallingIdentity(ident);
2022 }
2023 }
2024 }
2025
2026 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2028 synchronized (mGlobalLock) {
2029 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2030 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002031 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 }
2033 }
2034 return false;
2035 }
2036
2037 @Override
2038 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2039 Intent resultData) {
2040
2041 synchronized (mGlobalLock) {
2042 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2043 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002044 return r.getActivityStack().navigateUpToLocked(
2045 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 }
2047 return false;
2048 }
2049 }
2050
2051 /**
2052 * Attempts to move a task backwards in z-order (the order of activities within the task is
2053 * unchanged).
2054 *
2055 * There are several possible results of this call:
2056 * - if the task is locked, then we will show the lock toast
2057 * - if there is a task behind the provided task, then that task is made visible and resumed as
2058 * this task is moved to the back
2059 * - otherwise, if there are no other tasks in the stack:
2060 * - if this task is in the pinned stack, then we remove the stack completely, which will
2061 * have the effect of moving the task to the top or bottom of the fullscreen stack
2062 * (depending on whether it is visible)
2063 * - otherwise, we simply return home and hide this task
2064 *
2065 * @param token A reference to the activity we wish to move
2066 * @param nonRoot If false then this only works if the activity is the root
2067 * of a task; if true it will work for any activity in a task.
2068 * @return Returns true if the move completed, false if not.
2069 */
2070 @Override
2071 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 synchronized (mGlobalLock) {
2074 final long origId = Binder.clearCallingIdentity();
2075 try {
2076 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 if (task != null) {
2079 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2080 }
2081 } finally {
2082 Binder.restoreCallingIdentity(origId);
2083 }
2084 }
2085 return false;
2086 }
2087
2088 @Override
2089 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002090 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 long ident = Binder.clearCallingIdentity();
2092 Rect rect = new Rect();
2093 try {
2094 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002095 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2097 if (task == null) {
2098 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2099 return rect;
2100 }
2101 if (task.getStack() != null) {
2102 // Return the bounds from window manager since it will be adjusted for various
2103 // things like the presense of a docked stack for tasks that aren't resizeable.
2104 task.getWindowContainerBounds(rect);
2105 } else {
2106 // Task isn't in window manager yet since it isn't associated with a stack.
2107 // Return the persist value from activity manager
2108 if (!task.matchParentBounds()) {
2109 rect.set(task.getBounds());
2110 } else if (task.mLastNonFullscreenBounds != null) {
2111 rect.set(task.mLastNonFullscreenBounds);
2112 }
2113 }
2114 }
2115 } finally {
2116 Binder.restoreCallingIdentity(ident);
2117 }
2118 return rect;
2119 }
2120
2121 @Override
2122 public ActivityManager.TaskDescription getTaskDescription(int id) {
2123 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002124 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002125 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002126 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2128 if (tr != null) {
2129 return tr.lastTaskDescription;
2130 }
2131 }
2132 return null;
2133 }
2134
2135 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002136 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2137 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2138 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2139 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2140 return;
2141 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002142 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002143 synchronized (mGlobalLock) {
2144 final long ident = Binder.clearCallingIdentity();
2145 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002146 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002147 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002148 if (task == null) {
2149 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2150 return;
2151 }
2152
2153 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2154 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2155
2156 if (!task.isActivityTypeStandardOrUndefined()) {
2157 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2158 + " non-standard task " + taskId + " to windowing mode="
2159 + windowingMode);
2160 }
2161
2162 final ActivityStack stack = task.getStack();
2163 if (toTop) {
2164 stack.moveToFront("setTaskWindowingMode", task);
2165 }
2166 stack.setWindowingMode(windowingMode);
2167 } finally {
2168 Binder.restoreCallingIdentity(ident);
2169 }
2170 }
2171 }
2172
2173 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002175 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 ActivityRecord r = getCallingRecordLocked(token);
2177 return r != null ? r.info.packageName : null;
2178 }
2179 }
2180
2181 @Override
2182 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 ActivityRecord r = getCallingRecordLocked(token);
2185 return r != null ? r.intent.getComponent() : null;
2186 }
2187 }
2188
2189 private ActivityRecord getCallingRecordLocked(IBinder token) {
2190 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2191 if (r == null) {
2192 return null;
2193 }
2194 return r.resultTo;
2195 }
2196
2197 @Override
2198 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002199 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200
2201 synchronized (mGlobalLock) {
2202 final long origId = Binder.clearCallingIdentity();
2203 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002204 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002205 } finally {
2206 Binder.restoreCallingIdentity(origId);
2207 }
2208 }
2209 }
2210
2211 /**
2212 * TODO: Add mController hook
2213 */
2214 @Override
2215 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002216 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002217
2218 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2219 synchronized (mGlobalLock) {
2220 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2221 false /* fromRecents */);
2222 }
2223 }
2224
2225 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2226 boolean fromRecents) {
2227
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 Binder.getCallingUid(), -1, -1, "Task to front")) {
2230 SafeActivityOptions.abort(options);
2231 return;
2232 }
2233 final long origId = Binder.clearCallingIdentity();
2234 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002235 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 if (task == null) {
2237 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002238 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 return;
2240 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002241 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002242 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002243 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 return;
2245 }
2246 ActivityOptions realOptions = options != null
2247 ? options.getOptions(mStackSupervisor)
2248 : null;
2249 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2250 false /* forceNonResizable */);
2251
2252 final ActivityRecord topActivity = task.getTopActivity();
2253 if (topActivity != null) {
2254
2255 // We are reshowing a task, use a starting window to hide the initial draw delay
2256 // so the transition can start earlier.
2257 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2258 true /* taskSwitch */, fromRecents);
2259 }
2260 } finally {
2261 Binder.restoreCallingIdentity(origId);
2262 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002263 }
2264
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002265 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2266 int callingPid, int callingUid, String name) {
2267 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2268 return true;
2269 }
2270
2271 if (getRecentTasks().isCallerRecents(sourceUid)) {
2272 return true;
2273 }
2274
2275 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2276 if (perm == PackageManager.PERMISSION_GRANTED) {
2277 return true;
2278 }
2279 if (checkAllowAppSwitchUid(sourceUid)) {
2280 return true;
2281 }
2282
2283 // If the actual IPC caller is different from the logical source, then
2284 // also see if they are allowed to control app switches.
2285 if (callingUid != -1 && callingUid != sourceUid) {
2286 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2287 if (perm == PackageManager.PERMISSION_GRANTED) {
2288 return true;
2289 }
2290 if (checkAllowAppSwitchUid(callingUid)) {
2291 return true;
2292 }
2293 }
2294
2295 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2296 return false;
2297 }
2298
2299 private boolean checkAllowAppSwitchUid(int uid) {
2300 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2301 if (types != null) {
2302 for (int i = types.size() - 1; i >= 0; i--) {
2303 if (types.valueAt(i).intValue() == uid) {
2304 return true;
2305 }
2306 }
2307 }
2308 return false;
2309 }
2310
2311 @Override
2312 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2313 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2314 "setActivityController()");
2315 synchronized (mGlobalLock) {
2316 mController = controller;
2317 mControllerIsAMonkey = imAMonkey;
2318 Watchdog.getInstance().setActivityController(controller);
2319 }
2320 }
2321
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002322 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002323 synchronized (mGlobalLock) {
2324 return mController != null && mControllerIsAMonkey;
2325 }
2326 }
2327
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 @Override
2329 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2330 synchronized (mGlobalLock) {
2331 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2332 }
2333 }
2334
2335 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002336 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2337 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2338 }
2339
2340 @Override
2341 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2342 @WindowConfiguration.ActivityType int ignoreActivityType,
2343 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2344 final int callingUid = Binder.getCallingUid();
2345 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2346
2347 synchronized (mGlobalLock) {
2348 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2349
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002350 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002351 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002352 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002353 ignoreWindowingMode, callingUid, allowed);
2354 }
2355
2356 return list;
2357 }
2358
2359 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2361 synchronized (mGlobalLock) {
2362 final long origId = Binder.clearCallingIdentity();
2363 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2364 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002365 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 }
2367 Binder.restoreCallingIdentity(origId);
2368 }
2369 }
2370
2371 @Override
2372 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002373 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 ActivityStack stack = ActivityRecord.getStackLocked(token);
2375 if (stack != null) {
2376 return stack.willActivityBeVisibleLocked(token);
2377 }
2378 return false;
2379 }
2380 }
2381
2382 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002384 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002385 synchronized (mGlobalLock) {
2386 final long ident = Binder.clearCallingIdentity();
2387 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002388 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002389 if (task == null) {
2390 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2391 return;
2392 }
2393
2394 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2395 + " to stackId=" + stackId + " toTop=" + toTop);
2396
Wale Ogunwaled32da472018-11-16 07:19:28 -08002397 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002398 if (stack == null) {
2399 throw new IllegalStateException(
2400 "moveTaskToStack: No stack for stackId=" + stackId);
2401 }
2402 if (!stack.isActivityTypeStandardOrUndefined()) {
2403 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2404 + taskId + " to stack " + stackId);
2405 }
2406 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002407 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002408 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2409 }
2410 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2411 "moveTaskToStack");
2412 } finally {
2413 Binder.restoreCallingIdentity(ident);
2414 }
2415 }
2416 }
2417
2418 @Override
2419 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2420 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422
2423 final long ident = Binder.clearCallingIdentity();
2424 try {
2425 synchronized (mGlobalLock) {
2426 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002427 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002428 if (stack == null) {
2429 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2430 return;
2431 }
2432 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2433 throw new IllegalArgumentException("Stack: " + stackId
2434 + " doesn't support animated resize.");
2435 }
2436 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2437 animationDuration, false /* fromFullscreen */);
2438 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002439 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002440 if (stack == null) {
2441 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2442 return;
2443 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002444 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002445 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2446 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2447 }
2448 }
2449 } finally {
2450 Binder.restoreCallingIdentity(ident);
2451 }
2452 }
2453
wilsonshih5c4cf522019-01-25 09:03:47 +08002454 @Override
2455 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2456 int animationDuration) {
2457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2458
2459 final long ident = Binder.clearCallingIdentity();
2460 try {
2461 synchronized (mGlobalLock) {
2462 if (xOffset == 0 && yOffset == 0) {
2463 return;
2464 }
2465 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2466 if (stack == null) {
2467 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2468 return;
2469 }
2470 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2471 throw new IllegalArgumentException("Stack: " + stackId
2472 + " doesn't support animated resize.");
2473 }
2474 final Rect destBounds = new Rect();
2475 stack.getAnimationOrCurrentBounds(destBounds);
2476 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2477 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2478 return;
2479 }
2480 destBounds.offset(xOffset, yOffset);
2481 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2482 animationDuration, false /* fromFullscreen */);
2483 }
2484 } finally {
2485 Binder.restoreCallingIdentity(ident);
2486 }
2487 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002488 /**
2489 * Moves the specified task to the primary-split-screen stack.
2490 *
2491 * @param taskId Id of task to move.
2492 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2493 * exist already. See
2494 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2495 * and
2496 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2497 * @param toTop If the task and stack should be moved to the top.
2498 * @param animate Whether we should play an animation for the moving the task.
2499 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2500 * stack. Pass {@code null} to use default bounds.
2501 * @param showRecents If the recents activity should be shown on the other side of the task
2502 * going into split-screen mode.
2503 */
2504 @Override
2505 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2506 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002507 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 "setTaskWindowingModeSplitScreenPrimary()");
2509 synchronized (mGlobalLock) {
2510 final long ident = Binder.clearCallingIdentity();
2511 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002512 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002513 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002514 if (task == null) {
2515 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2516 return false;
2517 }
2518 if (DEBUG_STACK) Slog.d(TAG_STACK,
2519 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2520 + " to createMode=" + createMode + " toTop=" + toTop);
2521 if (!task.isActivityTypeStandardOrUndefined()) {
2522 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2523 + " non-standard task " + taskId + " to split-screen windowing mode");
2524 }
2525
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002526 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 final int windowingMode = task.getWindowingMode();
2528 final ActivityStack stack = task.getStack();
2529 if (toTop) {
2530 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2531 }
2532 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002533 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2534 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 return windowingMode != task.getWindowingMode();
2536 } finally {
2537 Binder.restoreCallingIdentity(ident);
2538 }
2539 }
2540 }
2541
2542 /**
2543 * Removes stacks in the input windowing modes from the system if they are of activity type
2544 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2545 */
2546 @Override
2547 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002548 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 "removeStacksInWindowingModes()");
2550
2551 synchronized (mGlobalLock) {
2552 final long ident = Binder.clearCallingIdentity();
2553 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002554 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 } finally {
2556 Binder.restoreCallingIdentity(ident);
2557 }
2558 }
2559 }
2560
2561 @Override
2562 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002563 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 "removeStacksWithActivityTypes()");
2565
2566 synchronized (mGlobalLock) {
2567 final long ident = Binder.clearCallingIdentity();
2568 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002569 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002570 } finally {
2571 Binder.restoreCallingIdentity(ident);
2572 }
2573 }
2574 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575
2576 @Override
2577 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2578 int userId) {
2579 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002580 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2581 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002582 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002583 final boolean detailed = checkGetTasksPermission(
2584 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2585 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 == PackageManager.PERMISSION_GRANTED;
2587
2588 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002589 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002590 callingUid);
2591 }
2592 }
2593
2594 @Override
2595 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002596 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002597 long ident = Binder.clearCallingIdentity();
2598 try {
2599 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002600 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002601 }
2602 } finally {
2603 Binder.restoreCallingIdentity(ident);
2604 }
2605 }
2606
2607 @Override
2608 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002609 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002610 long ident = Binder.clearCallingIdentity();
2611 try {
2612 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002613 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002614 }
2615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
2618 }
2619
2620 @Override
2621 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002622 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002623 final long callingUid = Binder.getCallingUid();
2624 final long origId = Binder.clearCallingIdentity();
2625 try {
2626 synchronized (mGlobalLock) {
2627 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002628 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002629 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2630 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2631 }
2632 } finally {
2633 Binder.restoreCallingIdentity(origId);
2634 }
2635 }
2636
2637 @Override
2638 public void startLockTaskModeByToken(IBinder token) {
2639 synchronized (mGlobalLock) {
2640 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2641 if (r == null) {
2642 return;
2643 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002644 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002645 }
2646 }
2647
2648 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002649 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002650 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002651 // This makes inner call to look as if it was initiated by system.
2652 long ident = Binder.clearCallingIdentity();
2653 try {
2654 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002655 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002656 MATCH_TASK_IN_STACKS_ONLY);
2657 if (task == null) {
2658 return;
2659 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660
2661 // When starting lock task mode the stack must be in front and focused
2662 task.getStack().moveToFront("startSystemLockTaskMode");
2663 startLockTaskModeLocked(task, true /* isSystemCaller */);
2664 }
2665 } finally {
2666 Binder.restoreCallingIdentity(ident);
2667 }
2668 }
2669
2670 @Override
2671 public void stopLockTaskModeByToken(IBinder token) {
2672 synchronized (mGlobalLock) {
2673 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2674 if (r == null) {
2675 return;
2676 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002677 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 }
2679 }
2680
2681 /**
2682 * This API should be called by SystemUI only when user perform certain action to dismiss
2683 * lock task mode. We should only dismiss pinned lock task mode in this case.
2684 */
2685 @Override
2686 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002687 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002688 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2689 }
2690
2691 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2692 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2693 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2694 return;
2695 }
2696
Wale Ogunwaled32da472018-11-16 07:19:28 -08002697 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002698 if (stack == null || task != stack.topTask()) {
2699 throw new IllegalArgumentException("Invalid task, not in foreground");
2700 }
2701
2702 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2703 // system or a specific app.
2704 // * System-initiated requests will only start the pinned mode (screen pinning)
2705 // * App-initiated requests
2706 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2707 // - will start the pinned mode, otherwise
2708 final int callingUid = Binder.getCallingUid();
2709 long ident = Binder.clearCallingIdentity();
2710 try {
2711 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002712 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002714 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002715 } finally {
2716 Binder.restoreCallingIdentity(ident);
2717 }
2718 }
2719
2720 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2721 final int callingUid = Binder.getCallingUid();
2722 long ident = Binder.clearCallingIdentity();
2723 try {
2724 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002725 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002726 }
2727 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2728 // task and jumping straight into a call in the case of emergency call back.
2729 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2730 if (tm != null) {
2731 tm.showInCallScreen(false);
2732 }
2733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737
2738 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002739 public void updateLockTaskPackages(int userId, String[] packages) {
2740 final int callingUid = Binder.getCallingUid();
2741 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2742 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2743 "updateLockTaskPackages()");
2744 }
2745 synchronized (this) {
2746 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2747 + Arrays.toString(packages));
2748 getLockTaskController().updateLockTaskPackages(userId, packages);
2749 }
2750 }
2751
2752 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002753 public boolean isInLockTaskMode() {
2754 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2755 }
2756
2757 @Override
2758 public int getLockTaskModeState() {
2759 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002760 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 }
2762 }
2763
2764 @Override
2765 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2766 synchronized (mGlobalLock) {
2767 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2768 if (r != null) {
2769 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002770 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002772 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 }
2774 }
2775 }
2776
2777 @Override
2778 public Bundle getActivityOptions(IBinder token) {
2779 final long origId = Binder.clearCallingIdentity();
2780 try {
2781 synchronized (mGlobalLock) {
2782 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2783 if (r != null) {
2784 final ActivityOptions activityOptions = r.takeOptionsLocked();
2785 return activityOptions == null ? null : activityOptions.toBundle();
2786 }
2787 return null;
2788 }
2789 } finally {
2790 Binder.restoreCallingIdentity(origId);
2791 }
2792 }
2793
2794 @Override
2795 public List<IBinder> getAppTasks(String callingPackage) {
2796 int callingUid = Binder.getCallingUid();
2797 long ident = Binder.clearCallingIdentity();
2798 try {
2799 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002800 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 }
2802 } finally {
2803 Binder.restoreCallingIdentity(ident);
2804 }
2805 }
2806
2807 @Override
2808 public void finishVoiceTask(IVoiceInteractionSession session) {
2809 synchronized (mGlobalLock) {
2810 final long origId = Binder.clearCallingIdentity();
2811 try {
2812 // TODO: VI Consider treating local voice interactions and voice tasks
2813 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002814 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 } finally {
2816 Binder.restoreCallingIdentity(origId);
2817 }
2818 }
2819
2820 }
2821
2822 @Override
2823 public boolean isTopOfTask(IBinder token) {
2824 synchronized (mGlobalLock) {
2825 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002826 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 }
2828 }
2829
2830 @Override
2831 public void notifyLaunchTaskBehindComplete(IBinder token) {
2832 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2833 }
2834
2835 @Override
2836 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002837 mH.post(() -> {
2838 synchronized (mGlobalLock) {
2839 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002840 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002841 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002842 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002843 } catch (RemoteException e) {
2844 }
2845 }
2846 }
2847
2848 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 }
2850
2851 /** Called from an app when assist data is ready. */
2852 @Override
2853 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2854 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 synchronized (pae) {
2857 pae.result = extras;
2858 pae.structure = structure;
2859 pae.content = content;
2860 if (referrer != null) {
2861 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2862 }
2863 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002864 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002865 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2866 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867 structure.setHomeActivity(pae.isHome);
2868 }
2869 pae.haveResult = true;
2870 pae.notifyAll();
2871 if (pae.intent == null && pae.receiver == null) {
2872 // Caller is just waiting for the result.
2873 return;
2874 }
2875 }
2876 // We are now ready to launch the assist activity.
2877 IAssistDataReceiver sendReceiver = null;
2878 Bundle sendBundle = null;
2879 synchronized (mGlobalLock) {
2880 buildAssistBundleLocked(pae, extras);
2881 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002882 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 if (!exists) {
2884 // Timed out.
2885 return;
2886 }
2887
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002888 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002889 // Caller wants result sent back to them.
2890 sendBundle = new Bundle();
2891 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2892 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2893 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2894 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2895 }
2896 }
2897 if (sendReceiver != null) {
2898 try {
2899 sendReceiver.onHandleAssistData(sendBundle);
2900 } catch (RemoteException e) {
2901 }
2902 return;
2903 }
2904
2905 final long ident = Binder.clearCallingIdentity();
2906 try {
2907 if (TextUtils.equals(pae.intent.getAction(),
2908 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2909 pae.intent.putExtras(pae.extras);
2910 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2911 } else {
2912 pae.intent.replaceExtras(pae.extras);
2913 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2914 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2915 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002916 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917
2918 try {
2919 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2920 } catch (ActivityNotFoundException e) {
2921 Slog.w(TAG, "No activity to handle assist action.", e);
2922 }
2923 }
2924 } finally {
2925 Binder.restoreCallingIdentity(ident);
2926 }
2927 }
2928
2929 @Override
2930 public int addAppTask(IBinder activityToken, Intent intent,
2931 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2932 final int callingUid = Binder.getCallingUid();
2933 final long callingIdent = Binder.clearCallingIdentity();
2934
2935 try {
2936 synchronized (mGlobalLock) {
2937 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2938 if (r == null) {
2939 throw new IllegalArgumentException("Activity does not exist; token="
2940 + activityToken);
2941 }
2942 ComponentName comp = intent.getComponent();
2943 if (comp == null) {
2944 throw new IllegalArgumentException("Intent " + intent
2945 + " must specify explicit component");
2946 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002947 if (thumbnail.getWidth() != mThumbnailWidth
2948 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 throw new IllegalArgumentException("Bad thumbnail size: got "
2950 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002951 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 }
2953 if (intent.getSelector() != null) {
2954 intent.setSelector(null);
2955 }
2956 if (intent.getSourceBounds() != null) {
2957 intent.setSourceBounds(null);
2958 }
2959 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2960 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2961 // The caller has added this as an auto-remove task... that makes no
2962 // sense, so turn off auto-remove.
2963 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2964 }
2965 }
2966 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2967 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2968 if (ainfo.applicationInfo.uid != callingUid) {
2969 throw new SecurityException(
2970 "Can't add task for another application: target uid="
2971 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2972 }
2973
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002974 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002975 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002976 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002978 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 // The app has too many tasks already and we can't add any more
2980 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2981 return INVALID_TASK_ID;
2982 }
2983 task.lastTaskDescription.copyFrom(description);
2984
2985 // TODO: Send the thumbnail to WM to store it.
2986
2987 return task.taskId;
2988 }
2989 } finally {
2990 Binder.restoreCallingIdentity(callingIdent);
2991 }
2992 }
2993
2994 @Override
2995 public Point getAppTaskThumbnailSize() {
2996 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002997 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002998 }
2999 }
3000
3001 @Override
3002 public void setTaskResizeable(int taskId, int resizeableMode) {
3003 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003004 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3006 if (task == null) {
3007 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3008 return;
3009 }
3010 task.setResizeMode(resizeableMode);
3011 }
3012 }
3013
3014 @Override
3015 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003016 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003017 long ident = Binder.clearCallingIdentity();
3018 try {
3019 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003020 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003021 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 if (task == null) {
3023 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3024 return;
3025 }
3026 // Place the task in the right stack if it isn't there already based on
3027 // the requested bounds.
3028 // The stack transition logic is:
3029 // - a null bounds on a freeform task moves that task to fullscreen
3030 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3031 // that task to freeform
3032 // - otherwise the task is not moved
3033 ActivityStack stack = task.getStack();
3034 if (!task.getWindowConfiguration().canResizeTask()) {
3035 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3036 }
3037 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3038 stack = stack.getDisplay().getOrCreateStack(
3039 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3040 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3041 stack = stack.getDisplay().getOrCreateStack(
3042 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3043 }
3044
3045 // Reparent the task to the right stack if necessary
3046 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3047 if (stack != task.getStack()) {
3048 // Defer resume until the task is resized below
3049 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3050 DEFER_RESUME, "resizeTask");
3051 preserveWindow = false;
3052 }
3053
3054 // After reparenting (which only resizes the task to the stack bounds), resize the
3055 // task to the actual bounds provided
3056 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3057 }
3058 } finally {
3059 Binder.restoreCallingIdentity(ident);
3060 }
3061 }
3062
3063 @Override
3064 public boolean releaseActivityInstance(IBinder token) {
3065 synchronized (mGlobalLock) {
3066 final long origId = Binder.clearCallingIdentity();
3067 try {
3068 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3069 if (r == null) {
3070 return false;
3071 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003072 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 } finally {
3074 Binder.restoreCallingIdentity(origId);
3075 }
3076 }
3077 }
3078
3079 @Override
3080 public void releaseSomeActivities(IApplicationThread appInt) {
3081 synchronized (mGlobalLock) {
3082 final long origId = Binder.clearCallingIdentity();
3083 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003084 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003085 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086 } finally {
3087 Binder.restoreCallingIdentity(origId);
3088 }
3089 }
3090 }
3091
3092 @Override
3093 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003094 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003095 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 != PackageManager.PERMISSION_GRANTED) {
3097 throw new SecurityException("Requires permission "
3098 + android.Manifest.permission.DEVICE_POWER);
3099 }
3100
3101 synchronized (mGlobalLock) {
3102 long ident = Binder.clearCallingIdentity();
3103 if (mKeyguardShown != keyguardShowing) {
3104 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003105 final Message msg = PooledLambda.obtainMessage(
3106 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3107 keyguardShowing);
3108 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 }
3110 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003111 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003112 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 } finally {
3114 Binder.restoreCallingIdentity(ident);
3115 }
3116 }
3117
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003118 mH.post(() -> {
3119 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3120 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3121 }
3122 });
3123 }
3124
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003125 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003126 mH.post(() -> {
3127 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3128 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3129 }
3130 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131 }
3132
3133 @Override
3134 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003135 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3136 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137
3138 final File passedIconFile = new File(filePath);
3139 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3140 passedIconFile.getName());
3141 if (!legitIconFile.getPath().equals(filePath)
3142 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3143 throw new IllegalArgumentException("Bad file path: " + filePath
3144 + " passed for userId " + userId);
3145 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003146 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 }
3148
3149 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3152 final ActivityOptions activityOptions = safeOptions != null
3153 ? safeOptions.getOptions(mStackSupervisor)
3154 : null;
3155 if (activityOptions == null
3156 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3157 || activityOptions.getCustomInPlaceResId() == 0) {
3158 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3159 "with valid animation");
3160 }
lumark588a3e82018-07-20 18:53:54 +08003161 // Get top display of front most application.
3162 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3163 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003164 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3165 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3166 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003167 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003168 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003169 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 }
3171
3172 @Override
3173 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003174 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175 synchronized (mGlobalLock) {
3176 final long ident = Binder.clearCallingIdentity();
3177 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003178 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 if (stack == null) {
3180 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3181 return;
3182 }
3183 if (!stack.isActivityTypeStandardOrUndefined()) {
3184 throw new IllegalArgumentException(
3185 "Removing non-standard stack is not allowed.");
3186 }
3187 mStackSupervisor.removeStack(stack);
3188 } finally {
3189 Binder.restoreCallingIdentity(ident);
3190 }
3191 }
3192 }
3193
3194 @Override
3195 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003196 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197
3198 synchronized (mGlobalLock) {
3199 final long ident = Binder.clearCallingIdentity();
3200 try {
3201 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3202 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003203 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 } finally {
3205 Binder.restoreCallingIdentity(ident);
3206 }
3207 }
3208 }
3209
3210 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003211 public void exitFreeformMode(IBinder token) {
3212 synchronized (mGlobalLock) {
3213 long ident = Binder.clearCallingIdentity();
3214 try {
3215 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3216 if (r == null) {
3217 throw new IllegalArgumentException(
3218 "exitFreeformMode: No activity record matching token=" + token);
3219 }
3220
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003221 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 if (stack == null || !stack.inFreeformWindowingMode()) {
3223 throw new IllegalStateException(
3224 "exitFreeformMode: You can only go fullscreen from freeform.");
3225 }
3226
3227 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3228 } finally {
3229 Binder.restoreCallingIdentity(ident);
3230 }
3231 }
3232 }
3233
3234 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3235 @Override
3236 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003237 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003239 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 }
3241
3242 /** Unregister a task stack listener so that it stops receiving callbacks. */
3243 @Override
3244 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003247 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003248 }
3249
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 @Override
3251 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3252 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3253 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3254 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3255 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3256 }
3257
3258 @Override
3259 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3260 IBinder activityToken, int flags) {
3261 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3262 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3263 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3264 }
3265
3266 @Override
3267 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3268 Bundle args) {
3269 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3270 true /* focused */, true /* newSessionId */, userHandle, args,
3271 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3272 }
3273
3274 @Override
3275 public Bundle getAssistContextExtras(int requestType) {
3276 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3277 null, null, true /* focused */, true /* newSessionId */,
3278 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3279 if (pae == null) {
3280 return null;
3281 }
3282 synchronized (pae) {
3283 while (!pae.haveResult) {
3284 try {
3285 pae.wait();
3286 } catch (InterruptedException e) {
3287 }
3288 }
3289 }
3290 synchronized (mGlobalLock) {
3291 buildAssistBundleLocked(pae, pae.result);
3292 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003293 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003294 }
3295 return pae.extras;
3296 }
3297
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003298 /**
3299 * Binder IPC calls go through the public entry point.
3300 * This can be called with or without the global lock held.
3301 */
3302 private static int checkCallingPermission(String permission) {
3303 return checkPermission(
3304 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3305 }
3306
3307 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003308 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003309 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3310 mAmInternal.enforceCallingPermission(permission, func);
3311 }
3312 }
3313
3314 @VisibleForTesting
3315 int checkGetTasksPermission(String permission, int pid, int uid) {
3316 return checkPermission(permission, pid, uid);
3317 }
3318
3319 static int checkPermission(String permission, int pid, int uid) {
3320 if (permission == null) {
3321 return PackageManager.PERMISSION_DENIED;
3322 }
3323 return checkComponentPermission(permission, pid, uid, -1, true);
3324 }
3325
Wale Ogunwale214f3482018-10-04 11:00:47 -07003326 public static int checkComponentPermission(String permission, int pid, int uid,
3327 int owningUid, boolean exported) {
3328 return ActivityManagerService.checkComponentPermission(
3329 permission, pid, uid, owningUid, exported);
3330 }
3331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003332 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3333 if (getRecentTasks().isCallerRecents(callingUid)) {
3334 // Always allow the recents component to get tasks
3335 return true;
3336 }
3337
3338 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3339 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3340 if (!allowed) {
3341 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3342 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3343 // Temporary compatibility: some existing apps on the system image may
3344 // still be requesting the old permission and not switched to the new
3345 // one; if so, we'll still allow them full access. This means we need
3346 // to see if they are holding the old permission and are a system app.
3347 try {
3348 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3349 allowed = true;
3350 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3351 + " is using old GET_TASKS but privileged; allowing");
3352 }
3353 } catch (RemoteException e) {
3354 }
3355 }
3356 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3357 + " does not hold REAL_GET_TASKS; limiting output");
3358 }
3359 return allowed;
3360 }
3361
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3363 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3364 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3365 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367 "enqueueAssistContext()");
3368
3369 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003370 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 if (activity == null) {
3372 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3373 return null;
3374 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003375 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003376 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3377 return null;
3378 }
3379 if (focused) {
3380 if (activityToken != null) {
3381 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3382 if (activity != caller) {
3383 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3384 + " is not current top " + activity);
3385 return null;
3386 }
3387 }
3388 } else {
3389 activity = ActivityRecord.forTokenLocked(activityToken);
3390 if (activity == null) {
3391 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3392 + " couldn't be found");
3393 return null;
3394 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003395 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3397 return null;
3398 }
3399 }
3400
3401 PendingAssistExtras pae;
3402 Bundle extras = new Bundle();
3403 if (args != null) {
3404 extras.putAll(args);
3405 }
3406 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003407 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408
3409 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3410 userHandle);
3411 pae.isHome = activity.isActivityTypeHome();
3412
3413 // Increment the sessionId if necessary
3414 if (newSessionId) {
3415 mViSessionId++;
3416 }
3417 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003418 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3419 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 } catch (RemoteException e) {
3423 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3424 return null;
3425 }
3426 return pae;
3427 }
3428 }
3429
3430 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3431 if (result != null) {
3432 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3433 }
3434 if (pae.hint != null) {
3435 pae.extras.putBoolean(pae.hint, true);
3436 }
3437 }
3438
3439 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3440 IAssistDataReceiver receiver;
3441 synchronized (mGlobalLock) {
3442 mPendingAssistExtras.remove(pae);
3443 receiver = pae.receiver;
3444 }
3445 if (receiver != null) {
3446 // Caller wants result sent back to them.
3447 Bundle sendBundle = new Bundle();
3448 // At least return the receiver extras
3449 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3450 try {
3451 pae.receiver.onHandleAssistData(sendBundle);
3452 } catch (RemoteException e) {
3453 }
3454 }
3455 }
3456
3457 public class PendingAssistExtras extends Binder implements Runnable {
3458 public final ActivityRecord activity;
3459 public boolean isHome;
3460 public final Bundle extras;
3461 public final Intent intent;
3462 public final String hint;
3463 public final IAssistDataReceiver receiver;
3464 public final int userHandle;
3465 public boolean haveResult = false;
3466 public Bundle result = null;
3467 public AssistStructure structure = null;
3468 public AssistContent content = null;
3469 public Bundle receiverExtras;
3470
3471 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3472 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3473 int _userHandle) {
3474 activity = _activity;
3475 extras = _extras;
3476 intent = _intent;
3477 hint = _hint;
3478 receiver = _receiver;
3479 receiverExtras = _receiverExtras;
3480 userHandle = _userHandle;
3481 }
3482
3483 @Override
3484 public void run() {
3485 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3486 synchronized (this) {
3487 haveResult = true;
3488 notifyAll();
3489 }
3490 pendingAssistExtrasTimedOut(this);
3491 }
3492 }
3493
3494 @Override
3495 public boolean isAssistDataAllowedOnCurrentActivity() {
3496 int userId;
3497 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003498 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003499 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3500 return false;
3501 }
3502
3503 final ActivityRecord activity = focusedStack.getTopActivity();
3504 if (activity == null) {
3505 return false;
3506 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003507 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 }
3509 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3510 }
3511
3512 @Override
3513 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3514 long ident = Binder.clearCallingIdentity();
3515 try {
3516 synchronized (mGlobalLock) {
3517 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003518 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 if (top != caller) {
3520 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3521 + " is not current top " + top);
3522 return false;
3523 }
3524 if (!top.nowVisible) {
3525 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3526 + " is not visible");
3527 return false;
3528 }
3529 }
3530 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3531 token);
3532 } finally {
3533 Binder.restoreCallingIdentity(ident);
3534 }
3535 }
3536
3537 @Override
3538 public boolean isRootVoiceInteraction(IBinder token) {
3539 synchronized (mGlobalLock) {
3540 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3541 if (r == null) {
3542 return false;
3543 }
3544 return r.rootVoiceInteraction;
3545 }
3546 }
3547
Wale Ogunwalef6733932018-06-27 05:14:34 -07003548 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3549 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3550 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3551 if (activityToCallback == null) return;
3552 activityToCallback.setVoiceSessionLocked(voiceSession);
3553
3554 // Inform the activity
3555 try {
3556 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3557 voiceInteractor);
3558 long token = Binder.clearCallingIdentity();
3559 try {
3560 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3561 } finally {
3562 Binder.restoreCallingIdentity(token);
3563 }
3564 // TODO: VI Should we cache the activity so that it's easier to find later
3565 // rather than scan through all the stacks and activities?
3566 } catch (RemoteException re) {
3567 activityToCallback.clearVoiceSessionLocked();
3568 // TODO: VI Should this terminate the voice session?
3569 }
3570 }
3571
3572 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3573 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3574 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3575 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3576 boolean wasRunningVoice = mRunningVoice != null;
3577 mRunningVoice = session;
3578 if (!wasRunningVoice) {
3579 mVoiceWakeLock.acquire();
3580 updateSleepIfNeededLocked();
3581 }
3582 }
3583 }
3584
3585 void finishRunningVoiceLocked() {
3586 if (mRunningVoice != null) {
3587 mRunningVoice = null;
3588 mVoiceWakeLock.release();
3589 updateSleepIfNeededLocked();
3590 }
3591 }
3592
3593 @Override
3594 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3595 synchronized (mGlobalLock) {
3596 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3597 if (keepAwake) {
3598 mVoiceWakeLock.acquire();
3599 } else {
3600 mVoiceWakeLock.release();
3601 }
3602 }
3603 }
3604 }
3605
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 @Override
3607 public ComponentName getActivityClassForToken(IBinder token) {
3608 synchronized (mGlobalLock) {
3609 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3610 if (r == null) {
3611 return null;
3612 }
3613 return r.intent.getComponent();
3614 }
3615 }
3616
3617 @Override
3618 public String getPackageForToken(IBinder token) {
3619 synchronized (mGlobalLock) {
3620 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3621 if (r == null) {
3622 return null;
3623 }
3624 return r.packageName;
3625 }
3626 }
3627
3628 @Override
3629 public void showLockTaskEscapeMessage(IBinder token) {
3630 synchronized (mGlobalLock) {
3631 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3632 if (r == null) {
3633 return;
3634 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003635 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 }
3637 }
3638
3639 @Override
3640 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003641 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 final long token = Binder.clearCallingIdentity();
3643 try {
3644 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003645 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003646 }
3647 } finally {
3648 Binder.restoreCallingIdentity(token);
3649 }
3650 }
3651
3652 /**
3653 * Try to place task to provided position. The final position might be different depending on
3654 * current user and stacks state. The task will be moved to target stack if it's currently in
3655 * different stack.
3656 */
3657 @Override
3658 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003659 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003660 synchronized (mGlobalLock) {
3661 long ident = Binder.clearCallingIdentity();
3662 try {
3663 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3664 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003665 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003666 if (task == null) {
3667 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3668 + taskId);
3669 }
3670
Wale Ogunwaled32da472018-11-16 07:19:28 -08003671 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003672
3673 if (stack == null) {
3674 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3675 + stackId);
3676 }
3677 if (!stack.isActivityTypeStandardOrUndefined()) {
3678 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3679 + " the position of task " + taskId + " in/to non-standard stack");
3680 }
3681
3682 // TODO: Have the callers of this API call a separate reparent method if that is
3683 // what they intended to do vs. having this method also do reparenting.
3684 if (task.getStack() == stack) {
3685 // Change position in current stack.
3686 stack.positionChildAt(task, position);
3687 } else {
3688 // Reparent to new stack.
3689 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3690 !DEFER_RESUME, "positionTaskInStack");
3691 }
3692 } finally {
3693 Binder.restoreCallingIdentity(ident);
3694 }
3695 }
3696 }
3697
3698 @Override
3699 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3700 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3701 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3702 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3703 synchronized (mGlobalLock) {
3704 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3705 if (record == null) {
3706 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3707 + "found for: " + token);
3708 }
3709 record.setSizeConfigurations(horizontalSizeConfiguration,
3710 verticalSizeConfigurations, smallestSizeConfigurations);
3711 }
3712 }
3713
3714 /**
3715 * Dismisses split-screen multi-window mode.
3716 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3717 */
3718 @Override
3719 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003720 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3722 final long ident = Binder.clearCallingIdentity();
3723 try {
3724 synchronized (mGlobalLock) {
3725 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003726 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003727 if (stack == null) {
3728 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3729 return;
3730 }
3731
3732 if (toTop) {
3733 // Caller wants the current split-screen primary stack to be the top stack after
3734 // it goes fullscreen, so move it to the front.
3735 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003736 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 // In this case the current split-screen primary stack shouldn't be the top
3738 // stack after it goes fullscreen, but it current has focus, so we move the
3739 // focus to the top-most split-screen secondary stack next to it.
3740 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3741 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3742 if (otherStack != null) {
3743 otherStack.moveToFront("dismissSplitScreenMode_other");
3744 }
3745 }
3746
Evan Rosky10475742018-09-05 19:02:48 -07003747 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 }
3749 } finally {
3750 Binder.restoreCallingIdentity(ident);
3751 }
3752 }
3753
3754 /**
3755 * Dismisses Pip
3756 * @param animate True if the dismissal should be animated.
3757 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3758 * default animation duration should be used.
3759 */
3760 @Override
3761 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003762 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003763 final long ident = Binder.clearCallingIdentity();
3764 try {
3765 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003766 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003767 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (stack == null) {
3769 Slog.w(TAG, "dismissPip: pinned stack not found.");
3770 return;
3771 }
3772 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3773 throw new IllegalArgumentException("Stack: " + stack
3774 + " doesn't support animated resize.");
3775 }
3776 if (animate) {
3777 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3778 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3779 } else {
3780 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3781 }
3782 }
3783 } finally {
3784 Binder.restoreCallingIdentity(ident);
3785 }
3786 }
3787
3788 @Override
3789 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003790 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 synchronized (mGlobalLock) {
3792 mSuppressResizeConfigChanges = suppress;
3793 }
3794 }
3795
3796 /**
3797 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3798 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3799 * activity and clearing the task at the same time.
3800 */
3801 @Override
3802 // TODO: API should just be about changing windowing modes...
3803 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003804 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003805 "moveTasksToFullscreenStack()");
3806 synchronized (mGlobalLock) {
3807 final long origId = Binder.clearCallingIdentity();
3808 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003809 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 if (stack != null){
3811 if (!stack.isActivityTypeStandardOrUndefined()) {
3812 throw new IllegalArgumentException(
3813 "You can't move tasks from non-standard stacks.");
3814 }
3815 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3816 }
3817 } finally {
3818 Binder.restoreCallingIdentity(origId);
3819 }
3820 }
3821 }
3822
3823 /**
3824 * Moves the top activity in the input stackId to the pinned stack.
3825 *
3826 * @param stackId Id of stack to move the top activity to pinned stack.
3827 * @param bounds Bounds to use for pinned stack.
3828 *
3829 * @return True if the top activity of the input stack was successfully moved to the pinned
3830 * stack.
3831 */
3832 @Override
3833 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003834 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003835 "moveTopActivityToPinnedStack()");
3836 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003837 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3839 + "Device doesn't support picture-in-picture mode");
3840 }
3841
3842 long ident = Binder.clearCallingIdentity();
3843 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003844 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003845 } finally {
3846 Binder.restoreCallingIdentity(ident);
3847 }
3848 }
3849 }
3850
3851 @Override
3852 public boolean isInMultiWindowMode(IBinder token) {
3853 final long origId = Binder.clearCallingIdentity();
3854 try {
3855 synchronized (mGlobalLock) {
3856 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3857 if (r == null) {
3858 return false;
3859 }
3860 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3861 return r.inMultiWindowMode();
3862 }
3863 } finally {
3864 Binder.restoreCallingIdentity(origId);
3865 }
3866 }
3867
3868 @Override
3869 public boolean isInPictureInPictureMode(IBinder token) {
3870 final long origId = Binder.clearCallingIdentity();
3871 try {
3872 synchronized (mGlobalLock) {
3873 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3874 }
3875 } finally {
3876 Binder.restoreCallingIdentity(origId);
3877 }
3878 }
3879
3880 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003881 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3882 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003883 return false;
3884 }
3885
3886 // If we are animating to fullscreen then we have already dispatched the PIP mode
3887 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003888 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3889 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890 }
3891
3892 @Override
3893 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3894 final long origId = Binder.clearCallingIdentity();
3895 try {
3896 synchronized (mGlobalLock) {
3897 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3898 "enterPictureInPictureMode", token, params);
3899
3900 // If the activity is already in picture in picture mode, then just return early
3901 if (isInPictureInPictureMode(r)) {
3902 return true;
3903 }
3904
3905 // Activity supports picture-in-picture, now check that we can enter PiP at this
3906 // point, if it is
3907 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3908 false /* beforeStopping */)) {
3909 return false;
3910 }
3911
3912 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003913 synchronized (mGlobalLock) {
3914 // Only update the saved args from the args that are set
3915 r.pictureInPictureArgs.copyOnlySet(params);
3916 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3917 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3918 // Adjust the source bounds by the insets for the transition down
3919 final Rect sourceBounds = new Rect(
3920 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003921 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003922 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003923 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003924 stack.setPictureInPictureAspectRatio(aspectRatio);
3925 stack.setPictureInPictureActions(actions);
3926 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3927 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3928 logPictureInPictureArgs(params);
3929 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 };
3931
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003932 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 // If the keyguard is showing or occluded, then try and dismiss it before
3934 // entering picture-in-picture (this will prompt the user to authenticate if the
3935 // device is currently locked).
3936 dismissKeyguard(token, new KeyguardDismissCallback() {
3937 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003938 public void onDismissSucceeded() {
3939 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 }
3941 }, null /* message */);
3942 } else {
3943 // Enter picture in picture immediately otherwise
3944 enterPipRunnable.run();
3945 }
3946 return true;
3947 }
3948 } finally {
3949 Binder.restoreCallingIdentity(origId);
3950 }
3951 }
3952
3953 @Override
3954 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3955 final long origId = Binder.clearCallingIdentity();
3956 try {
3957 synchronized (mGlobalLock) {
3958 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3959 "setPictureInPictureParams", token, params);
3960
3961 // Only update the saved args from the args that are set
3962 r.pictureInPictureArgs.copyOnlySet(params);
3963 if (r.inPinnedWindowingMode()) {
3964 // If the activity is already in picture-in-picture, update the pinned stack now
3965 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3966 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003967 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003968 if (!stack.isAnimatingBoundsToFullscreen()) {
3969 stack.setPictureInPictureAspectRatio(
3970 r.pictureInPictureArgs.getAspectRatio());
3971 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3972 }
3973 }
3974 logPictureInPictureArgs(params);
3975 }
3976 } finally {
3977 Binder.restoreCallingIdentity(origId);
3978 }
3979 }
3980
3981 @Override
3982 public int getMaxNumPictureInPictureActions(IBinder token) {
3983 // Currently, this is a static constant, but later, we may change this to be dependent on
3984 // the context of the activity
3985 return 3;
3986 }
3987
3988 private void logPictureInPictureArgs(PictureInPictureParams params) {
3989 if (params.hasSetActions()) {
3990 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3991 params.getActions().size());
3992 }
3993 if (params.hasSetAspectRatio()) {
3994 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3995 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3996 MetricsLogger.action(lm);
3997 }
3998 }
3999
4000 /**
4001 * Checks the state of the system and the activity associated with the given {@param token} to
4002 * verify that picture-in-picture is supported for that activity.
4003 *
4004 * @return the activity record for the given {@param token} if all the checks pass.
4005 */
4006 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4007 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004008 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004009 throw new IllegalStateException(caller
4010 + ": Device doesn't support picture-in-picture mode.");
4011 }
4012
4013 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4014 if (r == null) {
4015 throw new IllegalStateException(caller
4016 + ": Can't find activity for token=" + token);
4017 }
4018
4019 if (!r.supportsPictureInPicture()) {
4020 throw new IllegalStateException(caller
4021 + ": Current activity does not support picture-in-picture.");
4022 }
4023
4024 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004025 && !mWindowManager.isValidPictureInPictureAspectRatio(
4026 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 final float minAspectRatio = mContext.getResources().getFloat(
4028 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4029 final float maxAspectRatio = mContext.getResources().getFloat(
4030 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4031 throw new IllegalArgumentException(String.format(caller
4032 + ": Aspect ratio is too extreme (must be between %f and %f).",
4033 minAspectRatio, maxAspectRatio));
4034 }
4035
4036 // Truncate the number of actions if necessary
4037 params.truncateActions(getMaxNumPictureInPictureActions(token));
4038
4039 return r;
4040 }
4041
4042 @Override
4043 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004044 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 synchronized (mGlobalLock) {
4046 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4047 if (r == null) {
4048 throw new IllegalArgumentException("Activity does not exist; token="
4049 + activityToken);
4050 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004051 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 }
4053 }
4054
4055 @Override
4056 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4057 Rect tempDockedTaskInsetBounds,
4058 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004059 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 long ident = Binder.clearCallingIdentity();
4061 try {
4062 synchronized (mGlobalLock) {
4063 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4064 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4065 PRESERVE_WINDOWS);
4066 }
4067 } finally {
4068 Binder.restoreCallingIdentity(ident);
4069 }
4070 }
4071
4072 @Override
4073 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004074 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 final long ident = Binder.clearCallingIdentity();
4076 try {
4077 synchronized (mGlobalLock) {
4078 mStackSupervisor.setSplitScreenResizing(resizing);
4079 }
4080 } finally {
4081 Binder.restoreCallingIdentity(ident);
4082 }
4083 }
4084
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004085 /**
4086 * Check that we have the features required for VR-related API calls, and throw an exception if
4087 * not.
4088 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004089 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004090 if (!mContext.getPackageManager().hasSystemFeature(
4091 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4092 throw new UnsupportedOperationException("VR mode not supported on this device!");
4093 }
4094 }
4095
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004096 @Override
4097 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004098 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004099
4100 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4101
4102 ActivityRecord r;
4103 synchronized (mGlobalLock) {
4104 r = ActivityRecord.isInStackLocked(token);
4105 }
4106
4107 if (r == null) {
4108 throw new IllegalArgumentException();
4109 }
4110
4111 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004112 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 VrManagerInternal.NO_ERROR) {
4114 return err;
4115 }
4116
4117 // Clear the binder calling uid since this path may call moveToTask().
4118 final long callingId = Binder.clearCallingIdentity();
4119 try {
4120 synchronized (mGlobalLock) {
4121 r.requestedVrComponent = (enabled) ? packageName : null;
4122
4123 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004124 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004125 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 }
4127 return 0;
4128 }
4129 } finally {
4130 Binder.restoreCallingIdentity(callingId);
4131 }
4132 }
4133
4134 @Override
4135 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4136 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4137 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004138 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4140 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4141 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004142 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 || activity.voiceSession != null) {
4144 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4145 return;
4146 }
4147 if (activity.pendingVoiceInteractionStart) {
4148 Slog.w(TAG, "Pending start of voice interaction already.");
4149 return;
4150 }
4151 activity.pendingVoiceInteractionStart = true;
4152 }
4153 LocalServices.getService(VoiceInteractionManagerInternal.class)
4154 .startLocalVoiceInteraction(callingActivity, options);
4155 }
4156
4157 @Override
4158 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4159 LocalServices.getService(VoiceInteractionManagerInternal.class)
4160 .stopLocalVoiceInteraction(callingActivity);
4161 }
4162
4163 @Override
4164 public boolean supportsLocalVoiceInteraction() {
4165 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4166 .supportsLocalVoiceInteraction();
4167 }
4168
4169 /** Notifies all listeners when the pinned stack animation starts. */
4170 @Override
4171 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004172 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 }
4174
4175 /** Notifies all listeners when the pinned stack animation ends. */
4176 @Override
4177 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004178 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004179 }
4180
4181 @Override
4182 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004183 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004184 final long ident = Binder.clearCallingIdentity();
4185 try {
4186 synchronized (mGlobalLock) {
4187 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4188 }
4189 } finally {
4190 Binder.restoreCallingIdentity(ident);
4191 }
4192 }
4193
4194 @Override
4195 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004196 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197
4198 synchronized (mGlobalLock) {
4199 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004200 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 // Call might come when display is not yet added or has already been removed.
4202 if (DEBUG_CONFIGURATION) {
4203 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4204 + displayId);
4205 }
4206 return false;
4207 }
4208
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004209 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004211 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 }
4213
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004214 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004215 final Message msg = PooledLambda.obtainMessage(
4216 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4217 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 }
4219
4220 final long origId = Binder.clearCallingIdentity();
4221 try {
4222 if (values != null) {
4223 Settings.System.clearConfiguration(values);
4224 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004225 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004226 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4227 return mTmpUpdateConfigurationResult.changes != 0;
4228 } finally {
4229 Binder.restoreCallingIdentity(origId);
4230 }
4231 }
4232 }
4233
4234 @Override
4235 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237
4238 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004239 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004241 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 }
4243
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004245 final Message msg = PooledLambda.obtainMessage(
4246 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4247 DEFAULT_DISPLAY);
4248 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 }
4250
4251 final long origId = Binder.clearCallingIdentity();
4252 try {
4253 if (values != null) {
4254 Settings.System.clearConfiguration(values);
4255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 UserHandle.USER_NULL, false /* deferResume */,
4258 mTmpUpdateConfigurationResult);
4259 return mTmpUpdateConfigurationResult.changes != 0;
4260 } finally {
4261 Binder.restoreCallingIdentity(origId);
4262 }
4263 }
4264 }
4265
4266 @Override
4267 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4268 CharSequence message) {
4269 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004270 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004271 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4272 }
4273 final long callingId = Binder.clearCallingIdentity();
4274 try {
4275 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004276 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 }
4278 } finally {
4279 Binder.restoreCallingIdentity(callingId);
4280 }
4281 }
4282
4283 @Override
4284 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004285 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 "cancelTaskWindowTransition()");
4287 final long ident = Binder.clearCallingIdentity();
4288 try {
4289 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004290 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004291 MATCH_TASK_IN_STACKS_ONLY);
4292 if (task == null) {
4293 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4294 return;
4295 }
4296 task.cancelWindowTransition();
4297 }
4298 } finally {
4299 Binder.restoreCallingIdentity(ident);
4300 }
4301 }
4302
4303 @Override
4304 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004305 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004306 final long ident = Binder.clearCallingIdentity();
4307 try {
4308 final TaskRecord task;
4309 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004310 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4312 if (task == null) {
4313 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4314 return null;
4315 }
4316 }
4317 // Don't call this while holding the lock as this operation might hit the disk.
4318 return task.getSnapshot(reducedResolution);
4319 } finally {
4320 Binder.restoreCallingIdentity(ident);
4321 }
4322 }
4323
4324 @Override
4325 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4326 synchronized (mGlobalLock) {
4327 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4328 if (r == null) {
4329 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4330 + token);
4331 return;
4332 }
4333 final long origId = Binder.clearCallingIdentity();
4334 try {
4335 r.setDisablePreviewScreenshots(disable);
4336 } finally {
4337 Binder.restoreCallingIdentity(origId);
4338 }
4339 }
4340 }
4341
4342 /** Return the user id of the last resumed activity. */
4343 @Override
4344 public @UserIdInt
4345 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4348 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004349 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004350 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004352 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004353 }
4354 }
4355
4356 @Override
4357 public void updateLockTaskFeatures(int userId, int flags) {
4358 final int callingUid = Binder.getCallingUid();
4359 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004360 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 "updateLockTaskFeatures()");
4362 }
4363 synchronized (mGlobalLock) {
4364 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4365 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004366 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368 }
4369
4370 @Override
4371 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4372 synchronized (mGlobalLock) {
4373 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4374 if (r == null) {
4375 return;
4376 }
4377 final long origId = Binder.clearCallingIdentity();
4378 try {
4379 r.setShowWhenLocked(showWhenLocked);
4380 } finally {
4381 Binder.restoreCallingIdentity(origId);
4382 }
4383 }
4384 }
4385
4386 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004387 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4388 synchronized (mGlobalLock) {
4389 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4390 if (r == null) {
4391 return;
4392 }
4393 final long origId = Binder.clearCallingIdentity();
4394 try {
4395 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4396 } finally {
4397 Binder.restoreCallingIdentity(origId);
4398 }
4399 }
4400 }
4401
4402 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4404 synchronized (mGlobalLock) {
4405 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4406 if (r == null) {
4407 return;
4408 }
4409 final long origId = Binder.clearCallingIdentity();
4410 try {
4411 r.setTurnScreenOn(turnScreenOn);
4412 } finally {
4413 Binder.restoreCallingIdentity(origId);
4414 }
4415 }
4416 }
4417
4418 @Override
4419 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004420 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 "registerRemoteAnimations");
4422 definition.setCallingPid(Binder.getCallingPid());
4423 synchronized (mGlobalLock) {
4424 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4425 if (r == null) {
4426 return;
4427 }
4428 final long origId = Binder.clearCallingIdentity();
4429 try {
4430 r.registerRemoteAnimations(definition);
4431 } finally {
4432 Binder.restoreCallingIdentity(origId);
4433 }
4434 }
4435 }
4436
4437 @Override
4438 public void registerRemoteAnimationForNextActivityStart(String packageName,
4439 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004440 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 "registerRemoteAnimationForNextActivityStart");
4442 adapter.setCallingPid(Binder.getCallingPid());
4443 synchronized (mGlobalLock) {
4444 final long origId = Binder.clearCallingIdentity();
4445 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004446 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 packageName, adapter);
4448 } finally {
4449 Binder.restoreCallingIdentity(origId);
4450 }
4451 }
4452 }
4453
Evan Rosky966759f2019-01-15 10:33:58 -08004454 @Override
4455 public void registerRemoteAnimationsForDisplay(int displayId,
4456 RemoteAnimationDefinition definition) {
4457 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4458 "registerRemoteAnimations");
4459 definition.setCallingPid(Binder.getCallingPid());
4460 synchronized (mGlobalLock) {
4461 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4462 if (display == null) {
4463 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4464 return;
4465 }
4466 final long origId = Binder.clearCallingIdentity();
4467 try {
4468 display.mDisplayContent.registerRemoteAnimations(definition);
4469 } finally {
4470 Binder.restoreCallingIdentity(origId);
4471 }
4472 }
4473 }
4474
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4476 @Override
4477 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4478 synchronized (mGlobalLock) {
4479 final long origId = Binder.clearCallingIdentity();
4480 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004481 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 } finally {
4483 Binder.restoreCallingIdentity(origId);
4484 }
4485 }
4486 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004487
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004488 @Override
4489 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004490 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004491 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004492 final int pid = Binder.getCallingPid();
4493 final WindowProcessController wpc = mPidMap.get(pid);
4494 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004495 }
4496 }
4497
4498 @Override
4499 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004501 != PERMISSION_GRANTED) {
4502 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4503 + Binder.getCallingPid()
4504 + ", uid=" + Binder.getCallingUid()
4505 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4506 Slog.w(TAG, msg);
4507 throw new SecurityException(msg);
4508 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004509 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004510 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004511 final int pid = Binder.getCallingPid();
4512 final WindowProcessController proc = mPidMap.get(pid);
4513 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004514 }
4515 }
4516
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004517 @Override
4518 public void stopAppSwitches() {
4519 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4520 synchronized (mGlobalLock) {
4521 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4522 mDidAppSwitch = false;
4523 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4524 }
4525 }
4526
4527 @Override
4528 public void resumeAppSwitches() {
4529 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4530 synchronized (mGlobalLock) {
4531 // Note that we don't execute any pending app switches... we will
4532 // let those wait until either the timeout, or the next start
4533 // activity request.
4534 mAppSwitchesAllowedTime = 0;
4535 }
4536 }
4537
4538 void onStartActivitySetDidAppSwitch() {
4539 if (mDidAppSwitch) {
4540 // This is the second allowed switch since we stopped switches, so now just generally
4541 // allow switches. Use case:
4542 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4543 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4544 // anyone to switch again).
4545 mAppSwitchesAllowedTime = 0;
4546 } else {
4547 mDidAppSwitch = true;
4548 }
4549 }
4550
4551 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004552 boolean shouldDisableNonVrUiLocked() {
4553 return mVrController.shouldDisableNonVrUiLocked();
4554 }
4555
Wale Ogunwale53783742018-09-16 10:21:51 -07004556 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004557 // VR apps are expected to run in a main display. If an app is turning on VR for
4558 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4559 // fullscreen stack before enabling VR Mode.
4560 // TODO: The goal of this code is to keep the VR app on the main display. When the
4561 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4562 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4563 // option would be a better choice here.
4564 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4565 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4566 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004567 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004568 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004569 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004570 }
4571 mH.post(() -> {
4572 if (!mVrController.onVrModeChanged(r)) {
4573 return;
4574 }
4575 synchronized (mGlobalLock) {
4576 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4577 mWindowManager.disableNonVrUi(disableNonVrUi);
4578 if (disableNonVrUi) {
4579 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4580 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004581 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004582 }
4583 }
4584 });
4585 }
4586
Wale Ogunwale53783742018-09-16 10:21:51 -07004587 @Override
4588 public int getPackageScreenCompatMode(String packageName) {
4589 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4590 synchronized (mGlobalLock) {
4591 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4592 }
4593 }
4594
4595 @Override
4596 public void setPackageScreenCompatMode(String packageName, int mode) {
4597 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4598 "setPackageScreenCompatMode");
4599 synchronized (mGlobalLock) {
4600 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4601 }
4602 }
4603
4604 @Override
4605 public boolean getPackageAskScreenCompat(String packageName) {
4606 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4607 synchronized (mGlobalLock) {
4608 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4609 }
4610 }
4611
4612 @Override
4613 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4614 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4615 "setPackageAskScreenCompat");
4616 synchronized (mGlobalLock) {
4617 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4618 }
4619 }
4620
Wale Ogunwale64258362018-10-16 15:13:37 -07004621 public static String relaunchReasonToString(int relaunchReason) {
4622 switch (relaunchReason) {
4623 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4624 return "window_resize";
4625 case RELAUNCH_REASON_FREE_RESIZE:
4626 return "free_resize";
4627 default:
4628 return null;
4629 }
4630 }
4631
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004632 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004633 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004634 }
4635
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004636 /** Pokes the task persister. */
4637 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4638 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4639 }
4640
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 boolean isKeyguardLocked() {
4642 return mKeyguardController.isKeyguardLocked();
4643 }
4644
Garfield Tan01548632018-11-27 10:15:48 -08004645 /**
4646 * Clears launch params for the given package.
4647 * @param packageNames the names of the packages of which the launch params are to be cleared
4648 */
4649 @Override
4650 public void clearLaunchParamsForPackages(List<String> packageNames) {
4651 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4652 "clearLaunchParamsForPackages");
4653 synchronized (mGlobalLock) {
4654 for (int i = 0; i < packageNames.size(); ++i) {
4655 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4656 }
4657 }
4658 }
4659
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004660 /**
4661 * Makes the display with the given id a single task instance display. I.e the display can only
4662 * contain one task.
4663 */
4664 @Override
4665 public void setDisplayToSingleTaskInstance(int displayId) {
4666 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4667 "setDisplayToSingleTaskInstance");
4668 final long origId = Binder.clearCallingIdentity();
4669 try {
4670 final ActivityDisplay display =
4671 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4672 if (display != null) {
4673 display.setDisplayToSingleTaskInstance();
4674 }
4675 } finally {
4676 Binder.restoreCallingIdentity(origId);
4677 }
4678 }
4679
Wale Ogunwale31913b52018-10-13 08:29:31 -07004680 void dumpLastANRLocked(PrintWriter pw) {
4681 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4682 if (mLastANRState == null) {
4683 pw.println(" <no ANR has occurred since boot>");
4684 } else {
4685 pw.println(mLastANRState);
4686 }
4687 }
4688
4689 void dumpLastANRTracesLocked(PrintWriter pw) {
4690 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4691
4692 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4693 if (ArrayUtils.isEmpty(files)) {
4694 pw.println(" <no ANR has occurred since boot>");
4695 return;
4696 }
4697 // Find the latest file.
4698 File latest = null;
4699 for (File f : files) {
4700 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4701 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004702 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004703 }
4704 pw.print("File: ");
4705 pw.print(latest.getName());
4706 pw.println();
4707 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4708 String line;
4709 while ((line = in.readLine()) != null) {
4710 pw.println(line);
4711 }
4712 } catch (IOException e) {
4713 pw.print("Unable to read: ");
4714 pw.print(e);
4715 pw.println();
4716 }
4717 }
4718
4719 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4720 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4721 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4722 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4723 }
4724
4725 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4726 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4727 pw.println(header);
4728
Wale Ogunwaled32da472018-11-16 07:19:28 -08004729 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004730 dumpPackage);
4731 boolean needSep = printedAnything;
4732
4733 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004734 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004735 " ResumedActivity: ");
4736 if (printed) {
4737 printedAnything = true;
4738 needSep = false;
4739 }
4740
4741 if (dumpPackage == null) {
4742 if (needSep) {
4743 pw.println();
4744 }
4745 printedAnything = true;
4746 mStackSupervisor.dump(pw, " ");
4747 }
4748
4749 if (!printedAnything) {
4750 pw.println(" (nothing)");
4751 }
4752 }
4753
4754 void dumpActivityContainersLocked(PrintWriter pw) {
4755 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004756 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004757 pw.println(" ");
4758 }
4759
4760 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4761 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4762 getActivityStartController().dump(pw, "", dumpPackage);
4763 }
4764
4765 /**
4766 * There are three things that cmd can be:
4767 * - a flattened component name that matches an existing activity
4768 * - the cmd arg isn't the flattened component name of an existing activity:
4769 * dump all activity whose component contains the cmd as a substring
4770 * - A hex number of the ActivityRecord object instance.
4771 *
4772 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4773 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4774 */
4775 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4776 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4777 ArrayList<ActivityRecord> activities;
4778
4779 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004780 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004781 dumpFocusedStackOnly);
4782 }
4783
4784 if (activities.size() <= 0) {
4785 return false;
4786 }
4787
4788 String[] newArgs = new String[args.length - opti];
4789 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4790
4791 TaskRecord lastTask = null;
4792 boolean needSep = false;
4793 for (int i = activities.size() - 1; i >= 0; i--) {
4794 ActivityRecord r = activities.get(i);
4795 if (needSep) {
4796 pw.println();
4797 }
4798 needSep = true;
4799 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004800 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004801 if (lastTask != task) {
4802 lastTask = task;
4803 pw.print("TASK "); pw.print(lastTask.affinity);
4804 pw.print(" id="); pw.print(lastTask.taskId);
4805 pw.print(" userId="); pw.println(lastTask.userId);
4806 if (dumpAll) {
4807 lastTask.dump(pw, " ");
4808 }
4809 }
4810 }
4811 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4812 }
4813 return true;
4814 }
4815
4816 /**
4817 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4818 * there is a thread associated with the activity.
4819 */
4820 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4821 final ActivityRecord r, String[] args, boolean dumpAll) {
4822 String innerPrefix = prefix + " ";
4823 synchronized (mGlobalLock) {
4824 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4825 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4826 pw.print(" pid=");
4827 if (r.hasProcess()) pw.println(r.app.getPid());
4828 else pw.println("(not running)");
4829 if (dumpAll) {
4830 r.dump(pw, innerPrefix);
4831 }
4832 }
4833 if (r.attachedToProcess()) {
4834 // flush anything that is already in the PrintWriter since the thread is going
4835 // to write to the file descriptor directly
4836 pw.flush();
4837 try {
4838 TransferPipe tp = new TransferPipe();
4839 try {
4840 r.app.getThread().dumpActivity(tp.getWriteFd(),
4841 r.appToken, innerPrefix, args);
4842 tp.go(fd);
4843 } finally {
4844 tp.kill();
4845 }
4846 } catch (IOException e) {
4847 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4848 } catch (RemoteException e) {
4849 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4850 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004851 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004852 }
4853
sanryhuang498e77e2018-12-06 14:57:01 +08004854 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4855 boolean testPssMode) {
4856 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4857 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4858 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004859 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004860 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4861 st.toString());
4862 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004863 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4864 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4865 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004866 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4867 testPssMode);
4868 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 }
4870
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004871 int getCurrentUserId() {
4872 return mAmInternal.getCurrentUserId();
4873 }
4874
4875 private void enforceNotIsolatedCaller(String caller) {
4876 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4877 throw new SecurityException("Isolated process not allowed to call " + caller);
4878 }
4879 }
4880
Wale Ogunwalef6733932018-06-27 05:14:34 -07004881 public Configuration getConfiguration() {
4882 Configuration ci;
4883 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004884 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004885 ci.userSetLocale = false;
4886 }
4887 return ci;
4888 }
4889
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890 /**
4891 * Current global configuration information. Contains general settings for the entire system,
4892 * also corresponds to the merged configuration of the default display.
4893 */
4894 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004895 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004896 }
4897
4898 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4899 boolean initLocale) {
4900 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4901 }
4902
4903 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4904 boolean initLocale, boolean deferResume) {
4905 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4906 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4907 UserHandle.USER_NULL, deferResume);
4908 }
4909
Wale Ogunwale59507092018-10-29 09:00:30 -07004910 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004911 final long origId = Binder.clearCallingIdentity();
4912 try {
4913 synchronized (mGlobalLock) {
4914 updateConfigurationLocked(values, null, false, true, userId,
4915 false /* deferResume */);
4916 }
4917 } finally {
4918 Binder.restoreCallingIdentity(origId);
4919 }
4920 }
4921
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004922 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4923 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4924 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4925 deferResume, null /* result */);
4926 }
4927
4928 /**
4929 * Do either or both things: (1) change the current configuration, and (2)
4930 * make sure the given activity is running with the (now) current
4931 * configuration. Returns true if the activity has been left running, or
4932 * false if <var>starting</var> is being destroyed to match the new
4933 * configuration.
4934 *
4935 * @param userId is only used when persistent parameter is set to true to persist configuration
4936 * for that particular user
4937 */
4938 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4939 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4940 ActivityTaskManagerService.UpdateConfigurationResult result) {
4941 int changes = 0;
4942 boolean kept = true;
4943
4944 if (mWindowManager != null) {
4945 mWindowManager.deferSurfaceLayout();
4946 }
4947 try {
4948 if (values != null) {
4949 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4950 deferResume);
4951 }
4952
4953 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4954 } finally {
4955 if (mWindowManager != null) {
4956 mWindowManager.continueSurfaceLayout();
4957 }
4958 }
4959
4960 if (result != null) {
4961 result.changes = changes;
4962 result.activityRelaunched = !kept;
4963 }
4964 return kept;
4965 }
4966
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004967 /** Update default (global) configuration and notify listeners about changes. */
4968 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4969 boolean persistent, int userId, boolean deferResume) {
4970 mTempConfig.setTo(getGlobalConfiguration());
4971 final int changes = mTempConfig.updateFrom(values);
4972 if (changes == 0) {
4973 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4974 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4975 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4976 // (even if there are no actual changes) to unfreeze the window.
4977 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4978 return 0;
4979 }
4980
4981 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4982 "Updating global configuration to: " + values);
4983
4984 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4985 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4986 values.colorMode,
4987 values.densityDpi,
4988 values.fontScale,
4989 values.hardKeyboardHidden,
4990 values.keyboard,
4991 values.keyboardHidden,
4992 values.mcc,
4993 values.mnc,
4994 values.navigation,
4995 values.navigationHidden,
4996 values.orientation,
4997 values.screenHeightDp,
4998 values.screenLayout,
4999 values.screenWidthDp,
5000 values.smallestScreenWidthDp,
5001 values.touchscreen,
5002 values.uiMode);
5003
5004
5005 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5006 final LocaleList locales = values.getLocales();
5007 int bestLocaleIndex = 0;
5008 if (locales.size() > 1) {
5009 if (mSupportedSystemLocales == null) {
5010 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5011 }
5012 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5013 }
5014 SystemProperties.set("persist.sys.locale",
5015 locales.get(bestLocaleIndex).toLanguageTag());
5016 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005017
5018 final Message m = PooledLambda.obtainMessage(
5019 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5020 locales.get(bestLocaleIndex));
5021 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005022 }
5023
Yunfan Chen75157d72018-07-27 14:47:21 +09005024 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005025
5026 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005027 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005028
5029 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5030 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005031 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005032
5033 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005034 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005035
5036 AttributeCache ac = AttributeCache.instance();
5037 if (ac != null) {
5038 ac.updateConfiguration(mTempConfig);
5039 }
5040
5041 // Make sure all resources in our process are updated right now, so that anyone who is going
5042 // to retrieve resource values after we return will be sure to get the new ones. This is
5043 // especially important during boot, where the first config change needs to guarantee all
5044 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005045 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005046
5047 // We need another copy of global config because we're scheduling some calls instead of
5048 // running them in place. We need to be sure that object we send will be handled unchanged.
5049 final Configuration configCopy = new Configuration(mTempConfig);
5050 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005051 final Message msg = PooledLambda.obtainMessage(
5052 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5053 this, userId, configCopy);
5054 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005055 }
5056
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005057 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005058 final int pid = mPidMap.keyAt(i);
5059 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005060 if (DEBUG_CONFIGURATION) {
5061 Slog.v(TAG_CONFIGURATION, "Update process config of "
5062 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005063 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005064 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005065 }
5066
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005067 final Message msg = PooledLambda.obtainMessage(
5068 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5069 mAmInternal, changes, initLocale);
5070 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071
5072 // Override configuration of the default display duplicates global config, so we need to
5073 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005074 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005075 DEFAULT_DISPLAY);
5076
5077 return changes;
5078 }
5079
5080 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5081 boolean deferResume, int displayId) {
5082 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5083 displayId, null /* result */);
5084 }
5085
5086 /**
5087 * Updates override configuration specific for the selected display. If no config is provided,
5088 * new one will be computed in WM based on current display info.
5089 */
5090 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5091 ActivityRecord starting, boolean deferResume, int displayId,
5092 ActivityTaskManagerService.UpdateConfigurationResult result) {
5093 int changes = 0;
5094 boolean kept = true;
5095
5096 if (mWindowManager != null) {
5097 mWindowManager.deferSurfaceLayout();
5098 }
5099 try {
5100 if (values != null) {
5101 if (displayId == DEFAULT_DISPLAY) {
5102 // Override configuration of the default display duplicates global config, so
5103 // we're calling global config update instead for default display. It will also
5104 // apply the correct override config.
5105 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5106 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5107 } else {
5108 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5109 }
5110 }
5111
5112 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5113 } finally {
5114 if (mWindowManager != null) {
5115 mWindowManager.continueSurfaceLayout();
5116 }
5117 }
5118
5119 if (result != null) {
5120 result.changes = changes;
5121 result.activityRelaunched = !kept;
5122 }
5123 return kept;
5124 }
5125
5126 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5127 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005128 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 final int changes = mTempConfig.updateFrom(values);
5130 if (changes != 0) {
5131 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5132 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005133 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134
5135 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5136 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005137 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005138
Wale Ogunwale5c918702018-10-18 11:06:33 -07005139 // Post message to start process to avoid possible deadlock of calling into AMS with
5140 // the ATMS lock held.
5141 final Message msg = PooledLambda.obtainMessage(
5142 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5143 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5144 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005145 }
5146 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 return changes;
5148 }
5149
Wale Ogunwalef6733932018-06-27 05:14:34 -07005150 private void updateEventDispatchingLocked(boolean booted) {
5151 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5152 }
5153
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005154 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5155 final ContentResolver resolver = mContext.getContentResolver();
5156 Settings.System.putConfigurationForUser(resolver, config, userId);
5157 }
5158
5159 private void sendLocaleToMountDaemonMsg(Locale l) {
5160 try {
5161 IBinder service = ServiceManager.getService("mount");
5162 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5163 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5164 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5165 } catch (RemoteException e) {
5166 Log.e(TAG, "Error storing locale for decryption UI", e);
5167 }
5168 }
5169
Alison Cichowlas3e340502018-08-07 17:15:01 -04005170 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5171 mStartActivitySources.remove(permissionToken);
5172 mExpiredStartAsCallerTokens.add(permissionToken);
5173 }
5174
5175 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5176 mExpiredStartAsCallerTokens.remove(permissionToken);
5177 }
5178
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005179 boolean isActivityStartsLoggingEnabled() {
5180 return mAmInternal.isActivityStartsLoggingEnabled();
5181 }
5182
Michal Karpinski8596ded2018-11-14 14:43:48 +00005183 boolean isBackgroundActivityStartsEnabled() {
5184 return mAmInternal.isBackgroundActivityStartsEnabled();
5185 }
5186
Wale Ogunwalef6733932018-06-27 05:14:34 -07005187 void enableScreenAfterBoot(boolean booted) {
5188 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5189 SystemClock.uptimeMillis());
5190 mWindowManager.enableScreenAfterBoot();
5191
5192 synchronized (mGlobalLock) {
5193 updateEventDispatchingLocked(booted);
5194 }
5195 }
5196
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005197 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5198 if (r == null || !r.hasProcess()) {
5199 return KEY_DISPATCHING_TIMEOUT_MS;
5200 }
5201 return getInputDispatchingTimeoutLocked(r.app);
5202 }
5203
5204 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005205 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005206 }
5207
Wale Ogunwalef6733932018-06-27 05:14:34 -07005208 /**
5209 * Decide based on the configuration whether we should show the ANR,
5210 * crash, etc dialogs. The idea is that if there is no affordance to
5211 * press the on-screen buttons, or the user experience would be more
5212 * greatly impacted than the crash itself, we shouldn't show the dialog.
5213 *
5214 * A thought: SystemUI might also want to get told about this, the Power
5215 * dialog / global actions also might want different behaviors.
5216 */
5217 private void updateShouldShowDialogsLocked(Configuration config) {
5218 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5219 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5220 && config.navigation == Configuration.NAVIGATION_NONAV);
5221 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5222 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5223 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5224 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5225 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5226 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5227 HIDE_ERROR_DIALOGS, 0) != 0;
5228 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5229 }
5230
5231 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5232 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5233 FONT_SCALE, 1.0f, userId);
5234
5235 synchronized (this) {
5236 if (getGlobalConfiguration().fontScale == scaleFactor) {
5237 return;
5238 }
5239
5240 final Configuration configuration
5241 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5242 configuration.fontScale = scaleFactor;
5243 updatePersistentConfiguration(configuration, userId);
5244 }
5245 }
5246
5247 // Actually is sleeping or shutting down or whatever else in the future
5248 // is an inactive state.
5249 boolean isSleepingOrShuttingDownLocked() {
5250 return isSleepingLocked() || mShuttingDown;
5251 }
5252
5253 boolean isSleepingLocked() {
5254 return mSleeping;
5255 }
5256
Riddle Hsu16567132018-08-16 21:37:47 +08005257 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005258 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005259 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005260 if (task.isActivityTypeStandard()) {
5261 if (mCurAppTimeTracker != r.appTimeTracker) {
5262 // We are switching app tracking. Complete the current one.
5263 if (mCurAppTimeTracker != null) {
5264 mCurAppTimeTracker.stop();
5265 mH.obtainMessage(
5266 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005267 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005268 mCurAppTimeTracker = null;
5269 }
5270 if (r.appTimeTracker != null) {
5271 mCurAppTimeTracker = r.appTimeTracker;
5272 startTimeTrackingFocusedActivityLocked();
5273 }
5274 } else {
5275 startTimeTrackingFocusedActivityLocked();
5276 }
5277 } else {
5278 r.appTimeTracker = null;
5279 }
5280 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5281 // TODO: Probably not, because we don't want to resume voice on switching
5282 // back to this activity
5283 if (task.voiceInteractor != null) {
5284 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5285 } else {
5286 finishRunningVoiceLocked();
5287
5288 if (mLastResumedActivity != null) {
5289 final IVoiceInteractionSession session;
5290
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005291 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005292 if (lastResumedActivityTask != null
5293 && lastResumedActivityTask.voiceSession != null) {
5294 session = lastResumedActivityTask.voiceSession;
5295 } else {
5296 session = mLastResumedActivity.voiceSession;
5297 }
5298
5299 if (session != null) {
5300 // We had been in a voice interaction session, but now focused has
5301 // move to something different. Just finish the session, we can't
5302 // return to it and retain the proper state and synchronization with
5303 // the voice interaction service.
5304 finishVoiceTask(session);
5305 }
5306 }
5307 }
5308
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005309 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5310 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005311 }
5312 updateResumedAppTrace(r);
5313 mLastResumedActivity = r;
5314
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005315 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005316
5317 applyUpdateLockStateLocked(r);
5318 applyUpdateVrModeLocked(r);
5319
5320 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005321 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005322 r == null ? "NULL" : r.shortComponentName,
5323 reason);
5324 }
5325
5326 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5327 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005328 final ActivityTaskManagerInternal.SleepToken token =
5329 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005330 updateSleepIfNeededLocked();
5331 return token;
5332 }
5333 }
5334
5335 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005336 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005337 final boolean wasSleeping = mSleeping;
5338 boolean updateOomAdj = false;
5339
5340 if (!shouldSleep) {
5341 // If wasSleeping is true, we need to wake up activity manager state from when
5342 // we started sleeping. In either case, we need to apply the sleep tokens, which
5343 // will wake up stacks or put them to sleep as appropriate.
5344 if (wasSleeping) {
5345 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005346 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5347 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005348 startTimeTrackingFocusedActivityLocked();
5349 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5350 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5351 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005352 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005353 if (wasSleeping) {
5354 updateOomAdj = true;
5355 }
5356 } else if (!mSleeping && shouldSleep) {
5357 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005358 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5359 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 if (mCurAppTimeTracker != null) {
5361 mCurAppTimeTracker.stop();
5362 }
5363 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5364 mStackSupervisor.goingToSleepLocked();
5365 updateResumedAppTrace(null /* resumed */);
5366 updateOomAdj = true;
5367 }
5368 if (updateOomAdj) {
5369 mH.post(mAmInternal::updateOomAdj);
5370 }
5371 }
5372
5373 void updateOomAdj() {
5374 mH.post(mAmInternal::updateOomAdj);
5375 }
5376
Wale Ogunwale53783742018-09-16 10:21:51 -07005377 void updateCpuStats() {
5378 mH.post(mAmInternal::updateCpuStats);
5379 }
5380
Hui Yu03d12402018-12-06 18:00:37 -08005381 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5382 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005383 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5384 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005385 mH.sendMessage(m);
5386 }
5387
Hui Yu03d12402018-12-06 18:00:37 -08005388 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005389 ComponentName taskRoot = null;
5390 final TaskRecord task = activity.getTaskRecord();
5391 if (task != null) {
5392 final ActivityRecord rootActivity = task.getRootActivity();
5393 if (rootActivity != null) {
5394 taskRoot = rootActivity.mActivityComponent;
5395 }
5396 }
5397
Hui Yu03d12402018-12-06 18:00:37 -08005398 final Message m = PooledLambda.obtainMessage(
5399 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005400 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005401 mH.sendMessage(m);
5402 }
5403
Wale Ogunwale53783742018-09-16 10:21:51 -07005404 void setBooting(boolean booting) {
5405 mAmInternal.setBooting(booting);
5406 }
5407
5408 boolean isBooting() {
5409 return mAmInternal.isBooting();
5410 }
5411
5412 void setBooted(boolean booted) {
5413 mAmInternal.setBooted(booted);
5414 }
5415
5416 boolean isBooted() {
5417 return mAmInternal.isBooted();
5418 }
5419
5420 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5421 mH.post(() -> {
5422 if (finishBooting) {
5423 mAmInternal.finishBooting();
5424 }
5425 if (enableScreen) {
5426 mInternal.enableScreenAfterBoot(isBooted());
5427 }
5428 });
5429 }
5430
5431 void setHeavyWeightProcess(ActivityRecord root) {
5432 mHeavyWeightProcess = root.app;
5433 final Message m = PooledLambda.obtainMessage(
5434 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005435 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005436 mH.sendMessage(m);
5437 }
5438
5439 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5440 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5441 return;
5442 }
5443
5444 mHeavyWeightProcess = null;
5445 final Message m = PooledLambda.obtainMessage(
5446 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5447 proc.mUserId);
5448 mH.sendMessage(m);
5449 }
5450
5451 private void cancelHeavyWeightProcessNotification(int userId) {
5452 final INotificationManager inm = NotificationManager.getService();
5453 if (inm == null) {
5454 return;
5455 }
5456 try {
5457 inm.cancelNotificationWithTag("android", null,
5458 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5459 } catch (RuntimeException e) {
5460 Slog.w(TAG, "Error canceling notification for service", e);
5461 } catch (RemoteException e) {
5462 }
5463
5464 }
5465
5466 private void postHeavyWeightProcessNotification(
5467 WindowProcessController proc, Intent intent, int userId) {
5468 if (proc == null) {
5469 return;
5470 }
5471
5472 final INotificationManager inm = NotificationManager.getService();
5473 if (inm == null) {
5474 return;
5475 }
5476
5477 try {
5478 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5479 String text = mContext.getString(R.string.heavy_weight_notification,
5480 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5481 Notification notification =
5482 new Notification.Builder(context,
5483 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5484 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5485 .setWhen(0)
5486 .setOngoing(true)
5487 .setTicker(text)
5488 .setColor(mContext.getColor(
5489 com.android.internal.R.color.system_notification_accent_color))
5490 .setContentTitle(text)
5491 .setContentText(
5492 mContext.getText(R.string.heavy_weight_notification_detail))
5493 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5494 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5495 new UserHandle(userId)))
5496 .build();
5497 try {
5498 inm.enqueueNotificationWithTag("android", "android", null,
5499 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5500 } catch (RuntimeException e) {
5501 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5502 } catch (RemoteException e) {
5503 }
5504 } catch (PackageManager.NameNotFoundException e) {
5505 Slog.w(TAG, "Unable to create context for heavy notification", e);
5506 }
5507
5508 }
5509
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005510 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5511 IBinder token, String resultWho, int requestCode, Intent[] intents,
5512 String[] resolvedTypes, int flags, Bundle bOptions) {
5513
5514 ActivityRecord activity = null;
5515 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5516 activity = ActivityRecord.isInStackLocked(token);
5517 if (activity == null) {
5518 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5519 return null;
5520 }
5521 if (activity.finishing) {
5522 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5523 return null;
5524 }
5525 }
5526
5527 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5528 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5529 bOptions);
5530 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5531 if (noCreate) {
5532 return rec;
5533 }
5534 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5535 if (activity.pendingResults == null) {
5536 activity.pendingResults = new HashSet<>();
5537 }
5538 activity.pendingResults.add(rec.ref);
5539 }
5540 return rec;
5541 }
5542
Andrii Kulian52d255c2018-07-13 11:32:19 -07005543 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005545 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5547 mCurAppTimeTracker.start(resumedActivity.packageName);
5548 }
5549 }
5550
5551 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5552 if (mTracedResumedActivity != null) {
5553 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5554 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5555 }
5556 if (resumed != null) {
5557 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5558 constructResumedTraceName(resumed.packageName), 0);
5559 }
5560 mTracedResumedActivity = resumed;
5561 }
5562
5563 private String constructResumedTraceName(String packageName) {
5564 return "focused app: " + packageName;
5565 }
5566
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005567 /** Applies latest configuration and/or visibility updates if needed. */
5568 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5569 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005570 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005571 // mainStack is null during startup.
5572 if (mainStack != null) {
5573 if (changes != 0 && starting == null) {
5574 // If the configuration changed, and the caller is not already
5575 // in the process of starting an activity, then find the top
5576 // activity to check if its configuration needs to change.
5577 starting = mainStack.topRunningActivityLocked();
5578 }
5579
5580 if (starting != null) {
5581 kept = starting.ensureActivityConfiguration(changes,
5582 false /* preserveWindow */);
5583 // And we need to make sure at this point that all other activities
5584 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005585 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005586 !PRESERVE_WINDOWS);
5587 }
5588 }
5589
5590 return kept;
5591 }
5592
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005593 void scheduleAppGcsLocked() {
5594 mH.post(() -> mAmInternal.scheduleAppGcs());
5595 }
5596
Wale Ogunwale53783742018-09-16 10:21:51 -07005597 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5598 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5599 }
5600
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005601 /**
5602 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5603 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5604 * on demand.
5605 */
5606 IPackageManager getPackageManager() {
5607 return AppGlobals.getPackageManager();
5608 }
5609
5610 PackageManagerInternal getPackageManagerInternalLocked() {
5611 if (mPmInternal == null) {
5612 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5613 }
5614 return mPmInternal;
5615 }
5616
Wale Ogunwale008163e2018-07-23 23:11:08 -07005617 AppWarnings getAppWarningsLocked() {
5618 return mAppWarnings;
5619 }
5620
Wale Ogunwale214f3482018-10-04 11:00:47 -07005621 Intent getHomeIntent() {
5622 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5623 intent.setComponent(mTopComponent);
5624 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5625 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5626 intent.addCategory(Intent.CATEGORY_HOME);
5627 }
5628 return intent;
5629 }
5630
Chilun2ef71f72018-11-16 17:57:15 +08005631 /**
5632 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5633 * activities.
5634 *
5635 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5636 * component defined in config_secondaryHomeComponent.
5637 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5638 */
5639 Intent getSecondaryHomeIntent(String preferredPackage) {
5640 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5641 if (preferredPackage == null) {
5642 // Using the component stored in config if no package name.
5643 final String secondaryHomeComponent = mContext.getResources().getString(
5644 com.android.internal.R.string.config_secondaryHomeComponent);
5645 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5646 } else {
5647 intent.setPackage(preferredPackage);
5648 }
5649 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5650 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5651 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5652 }
5653 return intent;
5654 }
5655
Wale Ogunwale214f3482018-10-04 11:00:47 -07005656 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5657 if (info == null) return null;
5658 ApplicationInfo newInfo = new ApplicationInfo(info);
5659 newInfo.initForUser(userId);
5660 return newInfo;
5661 }
5662
Wale Ogunwale9c103022018-10-18 07:44:54 -07005663 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005664 if (uid == SYSTEM_UID) {
5665 // The system gets to run in any process. If there are multiple processes with the same
5666 // uid, just pick the first (this should never happen).
5667 final SparseArray<WindowProcessController> procs =
5668 mProcessNames.getMap().get(processName);
5669 if (procs == null) return null;
5670 final int procCount = procs.size();
5671 for (int i = 0; i < procCount; i++) {
5672 final int procUid = procs.keyAt(i);
5673 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5674 // Don't use an app process or different user process for system component.
5675 continue;
5676 }
5677 return procs.valueAt(i);
5678 }
5679 }
5680
5681 return mProcessNames.get(processName, uid);
5682 }
5683
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005684 WindowProcessController getProcessController(IApplicationThread thread) {
5685 if (thread == null) {
5686 return null;
5687 }
5688
5689 final IBinder threadBinder = thread.asBinder();
5690 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5691 for (int i = pmap.size()-1; i >= 0; i--) {
5692 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5693 for (int j = procs.size() - 1; j >= 0; j--) {
5694 final WindowProcessController proc = procs.valueAt(j);
5695 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5696 return proc;
5697 }
5698 }
5699 }
5700
5701 return null;
5702 }
5703
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005704 WindowProcessController getProcessController(int pid, int uid) {
5705 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5706 for (int i = pmap.size()-1; i >= 0; i--) {
5707 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5708 for (int j = procs.size() - 1; j >= 0; j--) {
5709 final WindowProcessController proc = procs.valueAt(j);
5710 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5711 return proc;
5712 }
5713 }
5714 }
5715 return null;
5716 }
5717
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005718 int getUidStateLocked(int uid) {
5719 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5720 }
5721
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005722 boolean isUidForeground(int uid) {
5723 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5724 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5725 }
5726
Michal Karpinski4026cae2019-02-12 11:51:47 +00005727 boolean isDeviceOwner(String packageName) {
5728 if (packageName == null) {
5729 return false;
5730 }
5731 return packageName.equals(mDeviceOwnerPackageName);
5732 }
5733
5734 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5735 mDeviceOwnerPackageName = deviceOwnerPkg;
5736 }
5737
Wale Ogunwale9de19442018-10-18 19:05:03 -07005738 /**
5739 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5740 * the whitelist
5741 */
5742 String getPendingTempWhitelistTagForUidLocked(int uid) {
5743 return mPendingTempWhitelist.get(uid);
5744 }
5745
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005746 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5747 if (true || Build.IS_USER) {
5748 return;
5749 }
5750
5751 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5752 StrictMode.allowThreadDiskWrites();
5753 try {
5754 File tracesDir = new File("/data/anr");
5755 File tracesFile = null;
5756 try {
5757 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5758
5759 StringBuilder sb = new StringBuilder();
5760 Time tobj = new Time();
5761 tobj.set(System.currentTimeMillis());
5762 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5763 sb.append(": ");
5764 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5765 sb.append(" since ");
5766 sb.append(msg);
5767 FileOutputStream fos = new FileOutputStream(tracesFile);
5768 fos.write(sb.toString().getBytes());
5769 if (app == null) {
5770 fos.write("\n*** No application process!".getBytes());
5771 }
5772 fos.close();
5773 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5774 } catch (IOException e) {
5775 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5776 return;
5777 }
5778
5779 if (app != null && app.getPid() > 0) {
5780 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5781 firstPids.add(app.getPid());
5782 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5783 }
5784
5785 File lastTracesFile = null;
5786 File curTracesFile = null;
5787 for (int i=9; i>=0; i--) {
5788 String name = String.format(Locale.US, "slow%02d.txt", i);
5789 curTracesFile = new File(tracesDir, name);
5790 if (curTracesFile.exists()) {
5791 if (lastTracesFile != null) {
5792 curTracesFile.renameTo(lastTracesFile);
5793 } else {
5794 curTracesFile.delete();
5795 }
5796 }
5797 lastTracesFile = curTracesFile;
5798 }
5799 tracesFile.renameTo(curTracesFile);
5800 } finally {
5801 StrictMode.setThreadPolicy(oldPolicy);
5802 }
5803 }
5804
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005805 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005806 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005807
5808
Wale Ogunwale98875612018-10-12 07:53:02 -07005809 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5810 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005811
Riddle Hsud93a6c42018-11-29 21:50:06 +08005812 H(Looper looper) {
5813 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005814 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005815
5816 @Override
5817 public void handleMessage(Message msg) {
5818 switch (msg.what) {
5819 case REPORT_TIME_TRACKER_MSG: {
5820 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5821 tracker.deliverResult(mContext);
5822 } break;
5823 }
5824 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005825 }
5826
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005827 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005828 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005829
5830 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005831 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005832 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005833
5834 @Override
5835 public void handleMessage(Message msg) {
5836 switch (msg.what) {
5837 case DISMISS_DIALOG_UI_MSG: {
5838 final Dialog d = (Dialog) msg.obj;
5839 d.dismiss();
5840 break;
5841 }
5842 }
5843 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 }
5845
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005846 final class LocalService extends ActivityTaskManagerInternal {
5847 @Override
5848 public SleepToken acquireSleepToken(String tag, int displayId) {
5849 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005850 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005851 }
5852
5853 @Override
5854 public ComponentName getHomeActivityForUser(int userId) {
5855 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005856 final ActivityRecord homeActivity =
5857 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005858 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005859 }
5860 }
5861
5862 @Override
5863 public void onLocalVoiceInteractionStarted(IBinder activity,
5864 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5865 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005866 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005867 }
5868 }
5869
5870 @Override
5871 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5872 synchronized (mGlobalLock) {
5873 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5874 reasons, timestamp);
5875 }
5876 }
5877
5878 @Override
5879 public void notifyAppTransitionFinished() {
5880 synchronized (mGlobalLock) {
5881 mStackSupervisor.notifyAppTransitionDone();
5882 }
5883 }
5884
5885 @Override
5886 public void notifyAppTransitionCancelled() {
5887 synchronized (mGlobalLock) {
5888 mStackSupervisor.notifyAppTransitionDone();
5889 }
5890 }
5891
5892 @Override
5893 public List<IBinder> getTopVisibleActivities() {
5894 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005895 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005896 }
5897 }
5898
5899 @Override
5900 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5901 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005902 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005903 }
5904 }
5905
5906 @Override
5907 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5908 Bundle bOptions) {
5909 Preconditions.checkNotNull(intents, "intents");
5910 final String[] resolvedTypes = new String[intents.length];
5911
5912 // UID of the package on user userId.
5913 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5914 // packageUid may not be initialized.
5915 int packageUid = 0;
5916 final long ident = Binder.clearCallingIdentity();
5917
5918 try {
5919 for (int i = 0; i < intents.length; i++) {
5920 resolvedTypes[i] =
5921 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5922 }
5923
5924 packageUid = AppGlobals.getPackageManager().getPackageUid(
5925 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5926 } catch (RemoteException e) {
5927 // Shouldn't happen.
5928 } finally {
5929 Binder.restoreCallingIdentity(ident);
5930 }
5931
5932 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005933 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005934 packageUid, packageName,
5935 intents, resolvedTypes, null /* resultTo */,
5936 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005937 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5938 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005939 }
5940 }
5941
5942 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005943 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5944 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5945 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5946 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005947 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005948 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005949 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5950 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5951 userId, validateIncomingUser, originatingPendingIntent,
5952 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005953 }
5954 }
5955
5956 @Override
5957 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5958 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5959 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5960 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005961 PendingIntentRecord originatingPendingIntent,
5962 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005963 synchronized (mGlobalLock) {
5964 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5965 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5966 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005967 validateIncomingUser, originatingPendingIntent,
5968 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005969 }
5970 }
5971
5972 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005973 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5974 Intent intent, Bundle options, int userId) {
5975 return ActivityTaskManagerService.this.startActivityAsUser(
5976 caller, callerPacakge, intent,
5977 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5978 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5979 false /*validateIncomingUser*/);
5980 }
5981
5982 @Override
lumark588a3e82018-07-20 18:53:54 +08005983 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005984 synchronized (mGlobalLock) {
5985
5986 // We might change the visibilities here, so prepare an empty app transition which
5987 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005988 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005989 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005990 if (activityDisplay == null) {
5991 return;
5992 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005993 final DisplayContent dc = activityDisplay.mDisplayContent;
5994 final boolean wasTransitionSet =
5995 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005996 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005997 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005998 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005999 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006000
6001 // If there was a transition set already we don't want to interfere with it as we
6002 // might be starting it too early.
6003 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006004 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006005 }
6006 }
6007 if (callback != null) {
6008 callback.run();
6009 }
6010 }
6011
6012 @Override
6013 public void notifyKeyguardTrustedChanged() {
6014 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006015 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006016 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006017 }
6018 }
6019 }
6020
6021 /**
6022 * Called after virtual display Id is updated by
6023 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6024 * {@param vrVr2dDisplayId}.
6025 */
6026 @Override
6027 public void setVr2dDisplayId(int vr2dDisplayId) {
6028 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6029 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006030 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 }
6032 }
6033
6034 @Override
6035 public void setFocusedActivity(IBinder token) {
6036 synchronized (mGlobalLock) {
6037 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6038 if (r == null) {
6039 throw new IllegalArgumentException(
6040 "setFocusedActivity: No activity record matching token=" + token);
6041 }
Louis Chang19443452018-10-09 12:10:21 +08006042 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006043 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006044 }
6045 }
6046 }
6047
6048 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006049 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006050 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006051 }
6052
6053 @Override
6054 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006055 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 }
6057
6058 @Override
6059 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006060 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062
6063 @Override
6064 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6065 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6066 }
6067
6068 @Override
6069 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006070 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006071 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006072
6073 @Override
6074 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6075 synchronized (mGlobalLock) {
6076 mActiveVoiceInteractionServiceComponent = component;
6077 }
6078 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006079
6080 @Override
6081 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6082 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6083 return;
6084 }
6085 synchronized (mGlobalLock) {
6086 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6087 if (types == null) {
6088 if (uid < 0) {
6089 return;
6090 }
6091 types = new ArrayMap<>();
6092 mAllowAppSwitchUids.put(userId, types);
6093 }
6094 if (uid < 0) {
6095 types.remove(type);
6096 } else {
6097 types.put(type, uid);
6098 }
6099 }
6100 }
6101
6102 @Override
6103 public void onUserStopped(int userId) {
6104 synchronized (mGlobalLock) {
6105 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6106 mAllowAppSwitchUids.remove(userId);
6107 }
6108 }
6109
6110 @Override
6111 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6112 synchronized (mGlobalLock) {
6113 return ActivityTaskManagerService.this.isGetTasksAllowed(
6114 caller, callingPid, callingUid);
6115 }
6116 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006117
6118 @Override
6119 public void onProcessAdded(WindowProcessController proc) {
6120 synchronized (mGlobalLock) {
6121 mProcessNames.put(proc.mName, proc.mUid, proc);
6122 }
6123 }
6124
6125 @Override
6126 public void onProcessRemoved(String name, int uid) {
6127 synchronized (mGlobalLock) {
6128 mProcessNames.remove(name, uid);
6129 }
6130 }
6131
6132 @Override
6133 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6134 synchronized (mGlobalLock) {
6135 if (proc == mHomeProcess) {
6136 mHomeProcess = null;
6137 }
6138 if (proc == mPreviousProcess) {
6139 mPreviousProcess = null;
6140 }
6141 }
6142 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006143
6144 @Override
6145 public int getTopProcessState() {
6146 synchronized (mGlobalLock) {
6147 return mTopProcessState;
6148 }
6149 }
6150
6151 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006152 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6153 synchronized (mGlobalLock) {
6154 return proc == mHeavyWeightProcess;
6155 }
6156 }
6157
6158 @Override
6159 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6160 synchronized (mGlobalLock) {
6161 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6162 }
6163 }
6164
6165 @Override
6166 public void finishHeavyWeightApp() {
6167 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006168 if (mHeavyWeightProcess != null) {
6169 mHeavyWeightProcess.finishActivities();
6170 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006171 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6172 mHeavyWeightProcess);
6173 }
6174 }
6175
6176 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006177 public boolean isSleeping() {
6178 synchronized (mGlobalLock) {
6179 return isSleepingLocked();
6180 }
6181 }
6182
6183 @Override
6184 public boolean isShuttingDown() {
6185 synchronized (mGlobalLock) {
6186 return mShuttingDown;
6187 }
6188 }
6189
6190 @Override
6191 public boolean shuttingDown(boolean booted, int timeout) {
6192 synchronized (mGlobalLock) {
6193 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006194 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006195 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006196 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006197 return mStackSupervisor.shutdownLocked(timeout);
6198 }
6199 }
6200
6201 @Override
6202 public void enableScreenAfterBoot(boolean booted) {
6203 synchronized (mGlobalLock) {
6204 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6205 SystemClock.uptimeMillis());
6206 mWindowManager.enableScreenAfterBoot();
6207 updateEventDispatchingLocked(booted);
6208 }
6209 }
6210
6211 @Override
6212 public boolean showStrictModeViolationDialog() {
6213 synchronized (mGlobalLock) {
6214 return mShowDialogs && !mSleeping && !mShuttingDown;
6215 }
6216 }
6217
6218 @Override
6219 public void showSystemReadyErrorDialogsIfNeeded() {
6220 synchronized (mGlobalLock) {
6221 try {
6222 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6223 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6224 + " data partition or your device will be unstable.");
6225 mUiHandler.post(() -> {
6226 if (mShowDialogs) {
6227 AlertDialog d = new BaseErrorDialog(mUiContext);
6228 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6229 d.setCancelable(false);
6230 d.setTitle(mUiContext.getText(R.string.android_system_label));
6231 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6232 d.setButton(DialogInterface.BUTTON_POSITIVE,
6233 mUiContext.getText(R.string.ok),
6234 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6235 d.show();
6236 }
6237 });
6238 }
6239 } catch (RemoteException e) {
6240 }
6241
6242 if (!Build.isBuildConsistent()) {
6243 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6244 mUiHandler.post(() -> {
6245 if (mShowDialogs) {
6246 AlertDialog d = new BaseErrorDialog(mUiContext);
6247 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6248 d.setCancelable(false);
6249 d.setTitle(mUiContext.getText(R.string.android_system_label));
6250 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6251 d.setButton(DialogInterface.BUTTON_POSITIVE,
6252 mUiContext.getText(R.string.ok),
6253 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6254 d.show();
6255 }
6256 });
6257 }
6258 }
6259 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006260
6261 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006262 public void onProcessMapped(int pid, WindowProcessController proc) {
6263 synchronized (mGlobalLock) {
6264 mPidMap.put(pid, proc);
6265 }
6266 }
6267
6268 @Override
6269 public void onProcessUnMapped(int pid) {
6270 synchronized (mGlobalLock) {
6271 mPidMap.remove(pid);
6272 }
6273 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006274
6275 @Override
6276 public void onPackageDataCleared(String name) {
6277 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006278 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006279 mAppWarnings.onPackageDataCleared(name);
6280 }
6281 }
6282
6283 @Override
6284 public void onPackageUninstalled(String name) {
6285 synchronized (mGlobalLock) {
6286 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006287 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006288 }
6289 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006290
6291 @Override
6292 public void onPackageAdded(String name, boolean replacing) {
6293 synchronized (mGlobalLock) {
6294 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6295 }
6296 }
6297
6298 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006299 public void onPackageReplaced(ApplicationInfo aInfo) {
6300 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006301 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006302 }
6303 }
6304
6305 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006306 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6307 synchronized (mGlobalLock) {
6308 return compatibilityInfoForPackageLocked(ai);
6309 }
6310 }
6311
Yunfan Chen75157d72018-07-27 14:47:21 +09006312 /**
6313 * Set the corresponding display information for the process global configuration. To be
6314 * called when we need to show IME on a different display.
6315 *
6316 * @param pid The process id associated with the IME window.
6317 * @param displayId The ID of the display showing the IME.
6318 */
6319 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006320 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006321 if (pid == MY_PID || pid < 0) {
6322 if (DEBUG_CONFIGURATION) {
6323 Slog.w(TAG,
6324 "Trying to update display configuration for system/invalid process.");
6325 }
6326 return;
6327 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006328 synchronized (mGlobalLock) {
6329 final ActivityDisplay activityDisplay =
6330 mRootActivityContainer.getActivityDisplay(displayId);
6331 if (activityDisplay == null) {
6332 // Call might come when display is not yet added or has been removed.
6333 if (DEBUG_CONFIGURATION) {
6334 Slog.w(TAG, "Trying to update display configuration for non-existing "
6335 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006336 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006337 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006338 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006339 final WindowProcessController process = mPidMap.get(pid);
6340 if (process == null) {
6341 if (DEBUG_CONFIGURATION) {
6342 Slog.w(TAG, "Trying to update display configuration for invalid "
6343 + "process, pid=" + pid);
6344 }
6345 return;
6346 }
6347 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6348 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006349 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006350
6351 @Override
6352 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6353 int requestCode, int resultCode, Intent data) {
6354 synchronized (mGlobalLock) {
6355 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006356 if (r != null && r.getActivityStack() != null) {
6357 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6358 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006359 }
6360 }
6361 }
6362
6363 @Override
6364 public void clearPendingResultForActivity(IBinder activityToken,
6365 WeakReference<PendingIntentRecord> pir) {
6366 synchronized (mGlobalLock) {
6367 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6368 if (r != null && r.pendingResults != null) {
6369 r.pendingResults.remove(pir);
6370 }
6371 }
6372 }
6373
6374 @Override
6375 public IIntentSender getIntentSender(int type, String packageName,
6376 int callingUid, int userId, IBinder token, String resultWho,
6377 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6378 Bundle bOptions) {
6379 synchronized (mGlobalLock) {
6380 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6381 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6382 }
6383 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006384
6385 @Override
6386 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6387 synchronized (mGlobalLock) {
6388 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6389 if (r == null) {
6390 return null;
6391 }
6392 if (r.mServiceConnectionsHolder == null) {
6393 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6394 ActivityTaskManagerService.this, r);
6395 }
6396
6397 return r.mServiceConnectionsHolder;
6398 }
6399 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006400
6401 @Override
6402 public Intent getHomeIntent() {
6403 synchronized (mGlobalLock) {
6404 return ActivityTaskManagerService.this.getHomeIntent();
6405 }
6406 }
6407
6408 @Override
6409 public boolean startHomeActivity(int userId, String reason) {
6410 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006411 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006412 }
6413 }
6414
6415 @Override
6416 public boolean startHomeOnAllDisplays(int userId, String reason) {
6417 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006418 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006419 }
6420 }
6421
6422 @Override
6423 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6424 synchronized (mGlobalLock) {
6425 if (mFactoryTest == FACTORY_TEST_OFF) {
6426 return false;
6427 }
6428 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6429 && wpc.mName.equals(mTopComponent.getPackageName())) {
6430 return true;
6431 }
6432 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6433 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6434 }
6435 }
6436
6437 @Override
6438 public void updateTopComponentForFactoryTest() {
6439 synchronized (mGlobalLock) {
6440 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6441 return;
6442 }
6443 final ResolveInfo ri = mContext.getPackageManager()
6444 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6445 final CharSequence errorMsg;
6446 if (ri != null) {
6447 final ActivityInfo ai = ri.activityInfo;
6448 final ApplicationInfo app = ai.applicationInfo;
6449 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6450 mTopAction = Intent.ACTION_FACTORY_TEST;
6451 mTopData = null;
6452 mTopComponent = new ComponentName(app.packageName, ai.name);
6453 errorMsg = null;
6454 } else {
6455 errorMsg = mContext.getResources().getText(
6456 com.android.internal.R.string.factorytest_not_system);
6457 }
6458 } else {
6459 errorMsg = mContext.getResources().getText(
6460 com.android.internal.R.string.factorytest_no_action);
6461 }
6462 if (errorMsg == null) {
6463 return;
6464 }
6465
6466 mTopAction = null;
6467 mTopData = null;
6468 mTopComponent = null;
6469 mUiHandler.post(() -> {
6470 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6471 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006472 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006473 });
6474 }
6475 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006476
6477 @Override
6478 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6479 Runnable finishInstrumentationCallback) {
6480 synchronized (mGlobalLock) {
6481 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006482 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006483
6484 wpc.clearRecentTasks();
6485 wpc.clearActivities();
6486
6487 if (wpc.isInstrumenting()) {
6488 finishInstrumentationCallback.run();
6489 }
6490
Jorim Jaggid0752812018-10-16 16:07:20 +02006491 if (!restarting && hasVisibleActivities) {
6492 mWindowManager.deferSurfaceLayout();
6493 try {
6494 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6495 // If there was nothing to resume, and we are not already restarting
6496 // this process, but there is a visible activity that is hosted by the
6497 // process...then make sure all visible activities are running, taking
6498 // care of restarting this process.
6499 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6500 !PRESERVE_WINDOWS);
6501 }
6502 } finally {
6503 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006504 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006505 }
6506 }
6507 }
6508
6509 @Override
6510 public void closeSystemDialogs(String reason) {
6511 enforceNotIsolatedCaller("closeSystemDialogs");
6512
6513 final int pid = Binder.getCallingPid();
6514 final int uid = Binder.getCallingUid();
6515 final long origId = Binder.clearCallingIdentity();
6516 try {
6517 synchronized (mGlobalLock) {
6518 // Only allow this from foreground processes, so that background
6519 // applications can't abuse it to prevent system UI from being shown.
6520 if (uid >= FIRST_APPLICATION_UID) {
6521 final WindowProcessController proc = mPidMap.get(pid);
6522 if (!proc.isPerceptible()) {
6523 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6524 + " from background process " + proc);
6525 return;
6526 }
6527 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006528 mWindowManager.closeSystemDialogs(reason);
6529
Wale Ogunwaled32da472018-11-16 07:19:28 -08006530 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006531 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006532 // Call into AM outside the synchronized block.
6533 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006534 } finally {
6535 Binder.restoreCallingIdentity(origId);
6536 }
6537 }
6538
6539 @Override
6540 public void cleanupDisabledPackageComponents(
6541 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6542 synchronized (mGlobalLock) {
6543 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006544 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006545 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006546 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006547 mStackSupervisor.scheduleIdleLocked();
6548 }
6549
6550 // Clean-up disabled tasks
6551 getRecentTasks().cleanupDisabledPackageTasksLocked(
6552 packageName, disabledClasses, userId);
6553 }
6554 }
6555
6556 @Override
6557 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6558 int userId) {
6559 synchronized (mGlobalLock) {
6560
6561 boolean didSomething =
6562 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006563 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006564 null, doit, evenPersistent, userId);
6565 return didSomething;
6566 }
6567 }
6568
6569 @Override
6570 public void resumeTopActivities(boolean scheduleIdle) {
6571 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006572 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006573 if (scheduleIdle) {
6574 mStackSupervisor.scheduleIdleLocked();
6575 }
6576 }
6577 }
6578
6579 @Override
6580 public void preBindApplication(WindowProcessController wpc) {
6581 synchronized (mGlobalLock) {
6582 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6583 }
6584 }
6585
6586 @Override
6587 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6588 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006589 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006590 }
6591 }
6592
6593 @Override
6594 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6595 try {
6596 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6597 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6598 }
6599 } catch (RemoteException ex) {
6600 throw new SecurityException("Fail to check is caller a privileged app", ex);
6601 }
6602
6603 synchronized (mGlobalLock) {
6604 final long ident = Binder.clearCallingIdentity();
6605 try {
6606 if (mAmInternal.shouldConfirmCredentials(userId)) {
6607 if (mKeyguardController.isKeyguardLocked()) {
6608 // Showing launcher to avoid user entering credential twice.
6609 startHomeActivity(currentUserId, "notifyLockedProfile");
6610 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006611 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006612 }
6613 } finally {
6614 Binder.restoreCallingIdentity(ident);
6615 }
6616 }
6617 }
6618
6619 @Override
6620 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6621 mAmInternal.enforceCallingPermission(
6622 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6623
6624 synchronized (mGlobalLock) {
6625 final long ident = Binder.clearCallingIdentity();
6626 try {
6627 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6628 FLAG_ACTIVITY_TASK_ON_HOME);
6629 ActivityOptions activityOptions = options != null
6630 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006631 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006632 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006633 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006634 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006635 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006636 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6637 UserHandle.CURRENT);
6638 } finally {
6639 Binder.restoreCallingIdentity(ident);
6640 }
6641 }
6642 }
6643
6644 @Override
6645 public void writeActivitiesToProto(ProtoOutputStream proto) {
6646 synchronized (mGlobalLock) {
6647 // The output proto of "activity --proto activities"
6648 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006649 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006650 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6651 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006652 }
6653 }
6654
6655 @Override
6656 public void saveANRState(String reason) {
6657 synchronized (mGlobalLock) {
6658 final StringWriter sw = new StringWriter();
6659 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6660 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6661 if (reason != null) {
6662 pw.println(" Reason: " + reason);
6663 }
6664 pw.println();
6665 getActivityStartController().dump(pw, " ", null);
6666 pw.println();
6667 pw.println("-------------------------------------------------------------------------------");
6668 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6669 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6670 "" /* header */);
6671 pw.println();
6672 pw.close();
6673
6674 mLastANRState = sw.toString();
6675 }
6676 }
6677
6678 @Override
6679 public void clearSavedANRState() {
6680 synchronized (mGlobalLock) {
6681 mLastANRState = null;
6682 }
6683 }
6684
6685 @Override
6686 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6687 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6688 synchronized (mGlobalLock) {
6689 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6690 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6691 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6692 dumpLastANRLocked(pw);
6693 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6694 dumpLastANRTracesLocked(pw);
6695 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6696 dumpActivityStarterLocked(pw, dumpPackage);
6697 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6698 dumpActivityContainersLocked(pw);
6699 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6700 if (getRecentTasks() != null) {
6701 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6702 }
6703 }
6704 }
6705 }
6706
6707 @Override
6708 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6709 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6710 int wakefulness) {
6711 synchronized (mGlobalLock) {
6712 if (mHomeProcess != null && (dumpPackage == null
6713 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6714 if (needSep) {
6715 pw.println();
6716 needSep = false;
6717 }
6718 pw.println(" mHomeProcess: " + mHomeProcess);
6719 }
6720 if (mPreviousProcess != null && (dumpPackage == null
6721 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6722 if (needSep) {
6723 pw.println();
6724 needSep = false;
6725 }
6726 pw.println(" mPreviousProcess: " + mPreviousProcess);
6727 }
6728 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6729 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6730 StringBuilder sb = new StringBuilder(128);
6731 sb.append(" mPreviousProcessVisibleTime: ");
6732 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6733 pw.println(sb);
6734 }
6735 if (mHeavyWeightProcess != null && (dumpPackage == null
6736 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6737 if (needSep) {
6738 pw.println();
6739 needSep = false;
6740 }
6741 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6742 }
6743 if (dumpPackage == null) {
6744 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006745 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 }
6747 if (dumpAll) {
6748 if (dumpPackage == null) {
6749 pw.println(" mConfigWillChange: "
6750 + getTopDisplayFocusedStack().mConfigWillChange);
6751 }
6752 if (mCompatModePackages.getPackages().size() > 0) {
6753 boolean printed = false;
6754 for (Map.Entry<String, Integer> entry
6755 : mCompatModePackages.getPackages().entrySet()) {
6756 String pkg = entry.getKey();
6757 int mode = entry.getValue();
6758 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6759 continue;
6760 }
6761 if (!printed) {
6762 pw.println(" mScreenCompatPackages:");
6763 printed = true;
6764 }
6765 pw.println(" " + pkg + ": " + mode);
6766 }
6767 }
6768 }
6769
6770 if (dumpPackage == null) {
6771 pw.println(" mWakefulness="
6772 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006773 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774 if (mRunningVoice != null) {
6775 pw.println(" mRunningVoice=" + mRunningVoice);
6776 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6777 }
6778 pw.println(" mSleeping=" + mSleeping);
6779 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6780 pw.println(" mVrController=" + mVrController);
6781 }
6782 if (mCurAppTimeTracker != null) {
6783 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6784 }
6785 if (mAllowAppSwitchUids.size() > 0) {
6786 boolean printed = false;
6787 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6788 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6789 for (int j = 0; j < types.size(); j++) {
6790 if (dumpPackage == null ||
6791 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6792 if (needSep) {
6793 pw.println();
6794 needSep = false;
6795 }
6796 if (!printed) {
6797 pw.println(" mAllowAppSwitchUids:");
6798 printed = true;
6799 }
6800 pw.print(" User ");
6801 pw.print(mAllowAppSwitchUids.keyAt(i));
6802 pw.print(": Type ");
6803 pw.print(types.keyAt(j));
6804 pw.print(" = ");
6805 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6806 pw.println();
6807 }
6808 }
6809 }
6810 }
6811 if (dumpPackage == null) {
6812 if (mController != null) {
6813 pw.println(" mController=" + mController
6814 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6815 }
6816 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6817 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6818 }
6819
6820 return needSep;
6821 }
6822 }
6823
6824 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006825 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6826 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 synchronized (mGlobalLock) {
6828 if (dumpPackage == null) {
6829 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6830 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006831 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6832 if (mRunningVoice != null) {
6833 final long vrToken = proto.start(
6834 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6835 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6836 mRunningVoice.toString());
6837 mVoiceWakeLock.writeToProto(
6838 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6839 proto.end(vrToken);
6840 }
6841 mVrController.writeToProto(proto,
6842 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 if (mController != null) {
6844 final long token = proto.start(CONTROLLER);
6845 proto.write(CONTROLLER, mController.toString());
6846 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6847 proto.end(token);
6848 }
6849 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6850 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6851 }
6852
6853 if (mHomeProcess != null && (dumpPackage == null
6854 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006855 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006856 }
6857
6858 if (mPreviousProcess != null && (dumpPackage == null
6859 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006860 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6862 }
6863
6864 if (mHeavyWeightProcess != null && (dumpPackage == null
6865 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006866 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006867 }
6868
6869 for (Map.Entry<String, Integer> entry
6870 : mCompatModePackages.getPackages().entrySet()) {
6871 String pkg = entry.getKey();
6872 int mode = entry.getValue();
6873 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6874 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6875 proto.write(PACKAGE, pkg);
6876 proto.write(MODE, mode);
6877 proto.end(compatToken);
6878 }
6879 }
6880
6881 if (mCurAppTimeTracker != null) {
6882 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6883 }
6884
6885 }
6886 }
6887
6888 @Override
6889 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6890 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6891 boolean dumpFocusedStackOnly) {
6892 synchronized (mGlobalLock) {
6893 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6894 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6895 }
6896 }
6897
6898 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006899 public void dumpForOom(PrintWriter pw) {
6900 synchronized (mGlobalLock) {
6901 pw.println(" mHomeProcess: " + mHomeProcess);
6902 pw.println(" mPreviousProcess: " + mPreviousProcess);
6903 if (mHeavyWeightProcess != null) {
6904 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6905 }
6906 }
6907 }
6908
6909 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006910 public boolean canGcNow() {
6911 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006912 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006913 }
6914 }
6915
6916 @Override
6917 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006918 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006919 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 return top != null ? top.app : null;
6921 }
6922 }
6923
6924 @Override
6925 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006926 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006927 if (mRootActivityContainer != null) {
6928 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 }
6930 }
6931 }
6932
6933 @Override
6934 public void scheduleDestroyAllActivities(String reason) {
6935 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006936 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 }
6938 }
6939
6940 @Override
6941 public void removeUser(int userId) {
6942 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006943 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 }
6945 }
6946
6947 @Override
6948 public boolean switchUser(int userId, UserState userState) {
6949 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006950 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006951 }
6952 }
6953
6954 @Override
6955 public void onHandleAppCrash(WindowProcessController wpc) {
6956 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006957 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006958 }
6959 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006960
6961 @Override
6962 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6963 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006964 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006965 }
6966 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006967
6968 @Override
6969 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006970 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006971 mActiveUids.put(uid, procState);
6972 }
6973 }
6974
6975 @Override
6976 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006977 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006978 mActiveUids.remove(uid);
6979 }
6980 }
6981
6982 @Override
6983 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006984 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006985 mActiveUids.clear();
6986 }
6987 }
6988
6989 @Override
6990 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006991 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006992 if (mActiveUids.get(uid) != null) {
6993 mActiveUids.put(uid, procState);
6994 }
6995 }
6996 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006997
6998 @Override
6999 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007000 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007001 mPendingTempWhitelist.put(uid, tag);
7002 }
7003 }
7004
7005 @Override
7006 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007007 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007008 mPendingTempWhitelist.remove(uid);
7009 }
7010 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007011
7012 @Override
7013 public boolean handleAppCrashInActivityController(String processName, int pid,
7014 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7015 Runnable killCrashingAppCallback) {
7016 synchronized (mGlobalLock) {
7017 if (mController == null) {
7018 return false;
7019 }
7020
7021 try {
7022 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7023 stackTrace)) {
7024 killCrashingAppCallback.run();
7025 return true;
7026 }
7027 } catch (RemoteException e) {
7028 mController = null;
7029 Watchdog.getInstance().setActivityController(null);
7030 }
7031 return false;
7032 }
7033 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007034
7035 @Override
7036 public void removeRecentTasksByPackageName(String packageName, int userId) {
7037 synchronized (mGlobalLock) {
7038 mRecentTasks.removeTasksByPackageName(packageName, userId);
7039 }
7040 }
7041
7042 @Override
7043 public void cleanupRecentTasksForUser(int userId) {
7044 synchronized (mGlobalLock) {
7045 mRecentTasks.cleanupLocked(userId);
7046 }
7047 }
7048
7049 @Override
7050 public void loadRecentTasksForUser(int userId) {
7051 synchronized (mGlobalLock) {
7052 mRecentTasks.loadUserRecentsLocked(userId);
7053 }
7054 }
7055
7056 @Override
7057 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7058 synchronized (mGlobalLock) {
7059 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7060 }
7061 }
7062
7063 @Override
7064 public void flushRecentTasks() {
7065 mRecentTasks.flush();
7066 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007067
7068 @Override
7069 public WindowProcessController getHomeProcess() {
7070 synchronized (mGlobalLock) {
7071 return mHomeProcess;
7072 }
7073 }
7074
7075 @Override
7076 public WindowProcessController getPreviousProcess() {
7077 synchronized (mGlobalLock) {
7078 return mPreviousProcess;
7079 }
7080 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007081
7082 @Override
7083 public void clearLockedTasks(String reason) {
7084 synchronized (mGlobalLock) {
7085 getLockTaskController().clearLockedTasks(reason);
7086 }
7087 }
7088
7089 @Override
7090 public void updateUserConfiguration() {
7091 synchronized (mGlobalLock) {
7092 final Configuration configuration = new Configuration(getGlobalConfiguration());
7093 final int currentUserId = mAmInternal.getCurrentUserId();
7094 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7095 configuration, currentUserId, Settings.System.canWrite(mContext));
7096 updateConfigurationLocked(configuration, null /* starting */,
7097 false /* initLocale */, false /* persistent */, currentUserId,
7098 false /* deferResume */);
7099 }
7100 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007101
7102 @Override
7103 public boolean canShowErrorDialogs() {
7104 synchronized (mGlobalLock) {
7105 return mShowDialogs && !mSleeping && !mShuttingDown
7106 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7107 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7108 mAmInternal.getCurrentUserId())
7109 && !(UserManager.isDeviceInDemoMode(mContext)
7110 && mAmInternal.getCurrentUser().isDemo());
7111 }
7112 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007113
7114 @Override
7115 public void setProfileApp(String profileApp) {
7116 synchronized (mGlobalLock) {
7117 mProfileApp = profileApp;
7118 }
7119 }
7120
7121 @Override
7122 public void setProfileProc(WindowProcessController wpc) {
7123 synchronized (mGlobalLock) {
7124 mProfileProc = wpc;
7125 }
7126 }
7127
7128 @Override
7129 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7130 synchronized (mGlobalLock) {
7131 mProfilerInfo = profilerInfo;
7132 }
7133 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007134
7135 @Override
7136 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7137 synchronized (mGlobalLock) {
7138 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7139 }
7140 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007141
7142 @Override
7143 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7144 synchronized (mGlobalLock) {
7145 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7146 }
7147 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007148
7149 @Override
7150 public boolean isUidForeground(int uid) {
7151 synchronized (mGlobalLock) {
7152 return ActivityTaskManagerService.this.isUidForeground(uid);
7153 }
7154 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007155
7156 @Override
7157 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7158 synchronized (mGlobalLock) {
7159 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7160 }
7161 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007162 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007163}