blob: 450893c8e5143ab8ea472010da33c7fb2b100746 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700263import com.android.server.pm.UserManagerService;
264import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266
Wale Ogunwale31913b52018-10-13 08:29:31 -0700267import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700270import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700273import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700274import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700275import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700277import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700278import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400280import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700283import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Map;
285import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286
287/**
288 * System service for managing activities and their containers (task, stacks, displays,... ).
289 *
290 * {@hide}
291 */
292public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700293 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700295 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
296 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
297 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
298 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
299 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700300 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700302 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700303 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 /** Used to indicate that an app transition should be animated. */
308 static final boolean ANIMATE = true;
309
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700310 /** Hardware-reported OpenGLES version. */
311 final int GL_ES_VERSION;
312
Wale Ogunwale31913b52018-10-13 08:29:31 -0700313 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
314 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
315 public static final String DUMP_LASTANR_CMD = "lastanr" ;
316 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
317 public static final String DUMP_STARTER_CMD = "starter" ;
318 public static final String DUMP_CONTAINERS_CMD = "containers" ;
319 public static final String DUMP_RECENTS_CMD = "recents" ;
320 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
321
Wale Ogunwale64258362018-10-16 15:13:37 -0700322 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
323 public static final int RELAUNCH_REASON_NONE = 0;
324 /** This activity is being relaunched due to windowing mode change. */
325 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
326 /** This activity is being relaunched due to a free-resize operation. */
327 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
328
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700329 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700330
Wale Ogunwalef6733932018-06-27 05:14:34 -0700331 /**
332 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
333 * change at runtime. Use mContext for non-UI purposes.
334 */
335 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700336 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700337 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700340 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700341 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800342 @VisibleForTesting
343 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 PowerManagerInternal mPowerManagerInternal;
345 private UsageStatsManagerInternal mUsageStatsInternal;
346
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700347 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 IntentFirewall mIntentFirewall;
349
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700350 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800351 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800352 /**
353 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
354 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
355 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
356 *
357 * @see WindowManagerThreadPriorityBooster
358 */
359 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700360 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800361 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700362 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700363 private UserManagerService mUserManager;
364 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700365 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700366 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
367 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700368 /** All processes currently running that might have a window organized by name. */
369 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700370 /** All processes we currently have running mapped by pid */
371 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700372 /** This is the process holding what we currently consider to be the "home" activity. */
373 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700374 /** The currently running heavy-weight process, if any. */
375 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700376 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /**
378 * This is the process holding the activity the user last visited that is in a different process
379 * from the one they are currently in.
380 */
381 WindowProcessController mPreviousProcess;
382 /** The time at which the previous process was last visible. */
383 long mPreviousProcessVisibleTime;
384
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700385 /** List of intents that were used to start the most recent tasks. */
386 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700387 /** State of external calls telling us if the device is awake or asleep. */
388 private boolean mKeyguardShown = false;
389
390 // Wrapper around VoiceInteractionServiceManager
391 private AssistUtils mAssistUtils;
392
393 // VoiceInteraction session ID that changes for each new request except when
394 // being called for multi-window assist in a single session.
395 private int mViSessionId = 1000;
396
397 // How long to wait in getAssistContextExtras for the activity and foreground services
398 // to respond with the result.
399 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
400
401 // How long top wait when going through the modern assist (which doesn't need to block
402 // on getting this result before starting to launch its UI).
403 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
404
405 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
406 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
407
Alison Cichowlas3e340502018-08-07 17:15:01 -0400408 // Permission tokens are used to temporarily granted a trusted app the ability to call
409 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
410 // showing any appropriate error messages to the user.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
412 10 * MINUTE_IN_MILLIS;
413
414 // How long before the service actually expires a token. This is slightly longer than
415 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
416 // expiration exception.
417 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
418 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
419
420 // How long the service will remember expired tokens, for the purpose of providing error
421 // messaging when a client uses an expired token.
422 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
423 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
424
425 // Activity tokens of system activities that are delegating their call to
426 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
427 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
428
429 // Permission tokens that have expired, but we remember for error reporting.
430 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
431
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700432 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
433
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700434 // Keeps track of the active voice interaction service component, notified from
435 // VoiceInteractionManagerService
436 ComponentName mActiveVoiceInteractionServiceComponent;
437
Wale Ogunwalee2172292018-10-25 10:11:10 -0700438 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439 KeyguardController mKeyguardController;
440 private final ClientLifecycleManager mLifecycleManager;
441 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700442 /** The controller for all operations related to locktask. */
443 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700444 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 boolean mSuppressResizeConfigChanges;
447
448 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
449 new UpdateConfigurationResult();
450
451 static final class UpdateConfigurationResult {
452 // Configuration changes that were updated.
453 int changes;
454 // If the activity was relaunched to match the new configuration.
455 boolean activityRelaunched;
456
457 void reset() {
458 changes = 0;
459 activityRelaunched = false;
460 }
461 }
462
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700463 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700464 private int mConfigurationSeq;
465 // To cache the list of supported system locales
466 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700467
468 /**
469 * Temp object used when global and/or display override configuration is updated. It is also
470 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
471 * anyone...
472 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700473 private Configuration mTempConfig = new Configuration();
474
Wale Ogunwalef6733932018-06-27 05:14:34 -0700475 /** Temporary to avoid allocations. */
476 final StringBuilder mStringBuilder = new StringBuilder(256);
477
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 // Amount of time after a call to stopAppSwitches() during which we will
479 // prevent further untrusted switches from happening.
480 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
481
482 /**
483 * The time at which we will allow normal application switches again,
484 * after a call to {@link #stopAppSwitches()}.
485 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700486 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 /**
488 * This is set to true after the first switch after mAppSwitchesAllowedTime
489 * is set; any switches after that will clear the time.
490 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492
493 IActivityController mController = null;
494 boolean mControllerIsAMonkey = false;
495
Wale Ogunwale214f3482018-10-04 11:00:47 -0700496 final int mFactoryTest;
497
498 /** Used to control how we initialize the service. */
499 ComponentName mTopComponent;
500 String mTopAction = Intent.ACTION_MAIN;
501 String mTopData;
502
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800503 /** Profiling app information. */
504 String mProfileApp = null;
505 WindowProcessController mProfileProc = null;
506 ProfilerInfo mProfilerInfo = null;
507
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700509 * Dump of the activity state at the time of the last ANR. Cleared after
510 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
511 */
512 String mLastANRState;
513
514 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 * Used to retain an update lock when the foreground activity is in
516 * immersive mode.
517 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519
520 /**
521 * Packages that are being allowed to perform unrestricted app switches. Mapping is
522 * User -> Type -> uid.
523 */
524 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
525
526 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700527 private int mThumbnailWidth;
528 private int mThumbnailHeight;
529 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530
531 /**
532 * Flag that indicates if multi-window is enabled.
533 *
534 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
535 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
536 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
537 * At least one of the forms of multi-window must be enabled in order for this flag to be
538 * initialized to 'true'.
539 *
540 * @see #mSupportsSplitScreenMultiWindow
541 * @see #mSupportsFreeformWindowManagement
542 * @see #mSupportsPictureInPicture
543 * @see #mSupportsMultiDisplay
544 */
545 boolean mSupportsMultiWindow;
546 boolean mSupportsSplitScreenMultiWindow;
547 boolean mSupportsFreeformWindowManagement;
548 boolean mSupportsPictureInPicture;
549 boolean mSupportsMultiDisplay;
550 boolean mForceResizableActivities;
551
552 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
553
554 // VR Vr2d Display Id.
555 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700556
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 /**
558 * Set while we are wanting to sleep, to prevent any
559 * activities from being started/resumed.
560 *
561 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
562 *
563 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
564 * while in the sleep state until there is a pending transition out of sleep, in which case
565 * mSleeping is set to false, and remains false while awake.
566 *
567 * Whether mSleeping can quickly toggled between true/false without the device actually
568 * display changing states is undefined.
569 */
570 private boolean mSleeping = false;
571
572 /**
573 * The process state used for processes that are running the top activities.
574 * This changes between TOP and TOP_SLEEPING to following mSleeping.
575 */
576 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
577
578 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
579 // automatically. Important for devices without direct input devices.
580 private boolean mShowDialogs = true;
581
582 /** Set if we are shutting down the system, similar to sleeping. */
583 boolean mShuttingDown = false;
584
585 /**
586 * We want to hold a wake lock while running a voice interaction session, since
587 * this may happen with the screen off and we need to keep the CPU running to
588 * be able to continue to interact with the user.
589 */
590 PowerManager.WakeLock mVoiceWakeLock;
591
592 /**
593 * Set while we are running a voice interaction. This overrides sleeping while it is active.
594 */
595 IVoiceInteractionSession mRunningVoice;
596
597 /**
598 * The last resumed activity. This is identical to the current resumed activity most
599 * of the time but could be different when we're pausing one activity before we resume
600 * another activity.
601 */
602 ActivityRecord mLastResumedActivity;
603
604 /**
605 * The activity that is currently being traced as the active resumed activity.
606 *
607 * @see #updateResumedAppTrace
608 */
609 private @Nullable ActivityRecord mTracedResumedActivity;
610
611 /** If non-null, we are tracking the time the user spends in the currently focused app. */
612 AppTimeTracker mCurAppTimeTracker;
613
Wale Ogunwale008163e2018-07-23 23:11:08 -0700614 private AppWarnings mAppWarnings;
615
Wale Ogunwale53783742018-09-16 10:21:51 -0700616 /**
617 * Packages that the user has asked to have run in screen size
618 * compatibility mode instead of filling the screen.
619 */
620 CompatModePackages mCompatModePackages;
621
Wale Ogunwalef6733932018-06-27 05:14:34 -0700622 private FontScaleSettingObserver mFontScaleSettingObserver;
623
Michal Karpinski4026cae2019-02-12 11:51:47 +0000624 private String mDeviceOwnerPackageName;
625
Wale Ogunwalef6733932018-06-27 05:14:34 -0700626 private final class FontScaleSettingObserver extends ContentObserver {
627 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
628 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
629
630 public FontScaleSettingObserver() {
631 super(mH);
632 final ContentResolver resolver = mContext.getContentResolver();
633 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
634 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
635 UserHandle.USER_ALL);
636 }
637
638 @Override
639 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
640 if (mFontScaleUri.equals(uri)) {
641 updateFontScaleIfNeeded(userId);
642 } else if (mHideErrorDialogsUri.equals(uri)) {
643 synchronized (mGlobalLock) {
644 updateShouldShowDialogsLocked(getGlobalConfiguration());
645 }
646 }
647 }
648 }
649
Charles Chen8d98dd22018-12-26 17:36:54 +0800650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
651 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700652 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700653 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700654 mSystemThread = ActivityThread.currentActivityThread();
655 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800657 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700658 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700659 }
660
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 public void onSystemReady() {
662 synchronized (mGlobalLock) {
663 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
664 PackageManager.FEATURE_CANT_SAVE_STATE);
665 mAssistUtils = new AssistUtils(mContext);
666 mVrController.onSystemReady();
667 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700668 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700669 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void onInitPowerManagement() {
673 synchronized (mGlobalLock) {
674 mStackSupervisor.initPowerManagement();
675 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
676 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
677 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
678 mVoiceWakeLock.setReferenceCounted(false);
679 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700680 }
681
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700682 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700683 mFontScaleSettingObserver = new FontScaleSettingObserver();
684 }
685
Wale Ogunwale59507092018-10-29 09:00:30 -0700686 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean freeformWindowManagement =
688 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
689 || Settings.Global.getInt(
690 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
691
692 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
693 final boolean supportsPictureInPicture = supportsMultiWindow &&
694 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
695 final boolean supportsSplitScreenMultiWindow =
696 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
697 final boolean supportsMultiDisplay = mContext.getPackageManager()
698 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700699 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
700 final boolean forceResizable = Settings.Global.getInt(
701 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700702 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700703
704 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900705 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706
707 final Configuration configuration = new Configuration();
708 Settings.System.getConfiguration(resolver, configuration);
709 if (forceRtl) {
710 // This will take care of setting the correct layout direction flags
711 configuration.setLayoutDirection(configuration.locale);
712 }
713
714 synchronized (mGlobalLock) {
715 mForceResizableActivities = forceResizable;
716 final boolean multiWindowFormEnabled = freeformWindowManagement
717 || supportsSplitScreenMultiWindow
718 || supportsPictureInPicture
719 || supportsMultiDisplay;
720 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
721 mSupportsMultiWindow = true;
722 mSupportsFreeformWindowManagement = freeformWindowManagement;
723 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
724 mSupportsPictureInPicture = supportsPictureInPicture;
725 mSupportsMultiDisplay = supportsMultiDisplay;
726 } else {
727 mSupportsMultiWindow = false;
728 mSupportsFreeformWindowManagement = false;
729 mSupportsSplitScreenMultiWindow = false;
730 mSupportsPictureInPicture = false;
731 mSupportsMultiDisplay = false;
732 }
733 mWindowManager.setForceResizableTasks(mForceResizableActivities);
734 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700735 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
736 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737 // This happens before any activities are started, so we can change global configuration
738 // in-place.
739 updateConfigurationLocked(configuration, null, true);
740 final Configuration globalConfig = getGlobalConfiguration();
741 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
742
743 // Load resources only after the current configuration has been set.
744 final Resources res = mContext.getResources();
745 mThumbnailWidth = res.getDimensionPixelSize(
746 com.android.internal.R.dimen.thumbnail_width);
747 mThumbnailHeight = res.getDimensionPixelSize(
748 com.android.internal.R.dimen.thumbnail_height);
749
750 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
751 mFullscreenThumbnailScale = (float) res
752 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
753 (float) globalConfig.screenWidthDp;
754 } else {
755 mFullscreenThumbnailScale = res.getFraction(
756 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
757 }
758 }
759 }
760
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800761 public WindowManagerGlobalLock getGlobalLock() {
762 return mGlobalLock;
763 }
764
Riddle Hsud93a6c42018-11-29 21:50:06 +0800765 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
766 Looper looper) {
767 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700769 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700770 final File systemDir = SystemServiceManager.ensureSystemDir();
771 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
772 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700773 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774
775 mTempConfig.setToDefaults();
776 mTempConfig.setLocales(LocaleList.getDefault());
777 mConfigurationSeq = mTempConfig.seq = 1;
778 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800779 mRootActivityContainer = new RootActivityContainer(this);
780 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700781
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700782 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700784 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700785 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700786 mRecentTasks = createRecentTasks();
787 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700788 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700789 mKeyguardController = mStackSupervisor.getKeyguardController();
790 }
791
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700792 public void onActivityManagerInternalAdded() {
793 synchronized (mGlobalLock) {
794 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
795 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
796 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700797 }
798
Yunfan Chen75157d72018-07-27 14:47:21 +0900799 int increaseConfigurationSeqLocked() {
800 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
801 return mConfigurationSeq;
802 }
803
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804 protected ActivityStackSupervisor createStackSupervisor() {
805 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
806 supervisor.initialize();
807 return supervisor;
808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setWindowManager(WindowManagerService wm) {
811 synchronized (mGlobalLock) {
812 mWindowManager = wm;
813 mLockTaskController.setWindowManager(wm);
814 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700816 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700817 }
818
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700819 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
820 synchronized (mGlobalLock) {
821 mUsageStatsInternal = usageStatsManager;
822 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 }
824
Wale Ogunwalef6733932018-06-27 05:14:34 -0700825 UserManagerService getUserManager() {
826 if (mUserManager == null) {
827 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
828 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
829 }
830 return mUserManager;
831 }
832
833 AppOpsService getAppOpsService() {
834 if (mAppOpsService == null) {
835 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
836 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
837 }
838 return mAppOpsService;
839 }
840
841 boolean hasUserRestriction(String restriction, int userId) {
842 return getUserManager().hasUserRestriction(restriction, userId);
843 }
844
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700845 protected RecentTasks createRecentTasks() {
846 return new RecentTasks(this, mStackSupervisor);
847 }
848
849 RecentTasks getRecentTasks() {
850 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700851 }
852
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700853 ClientLifecycleManager getLifecycleManager() {
854 return mLifecycleManager;
855 }
856
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700857 ActivityStartController getActivityStartController() {
858 return mActivityStartController;
859 }
860
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700861 TaskChangeNotificationController getTaskChangeNotificationController() {
862 return mTaskChangeNotificationController;
863 }
864
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700865 LockTaskController getLockTaskController() {
866 return mLockTaskController;
867 }
868
Yunfan Chen75157d72018-07-27 14:47:21 +0900869 /**
870 * Return the global configuration used by the process corresponding to the input pid. This is
871 * usually the global configuration with some overrides specific to that process.
872 */
873 Configuration getGlobalConfigurationForCallingPid() {
874 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800875 return getGlobalConfigurationForPid(pid);
876 }
877
878 /**
879 * Return the global configuration used by the process corresponding to the given pid.
880 */
881 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900882 if (pid == MY_PID || pid < 0) {
883 return getGlobalConfiguration();
884 }
885 synchronized (mGlobalLock) {
886 final WindowProcessController app = mPidMap.get(pid);
887 return app != null ? app.getConfiguration() : getGlobalConfiguration();
888 }
889 }
890
891 /**
892 * Return the device configuration info used by the process corresponding to the input pid.
893 * The value is consistent with the global configuration for the process.
894 */
895 @Override
896 public ConfigurationInfo getDeviceConfigurationInfo() {
897 ConfigurationInfo config = new ConfigurationInfo();
898 synchronized (mGlobalLock) {
899 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
900 config.reqTouchScreen = globalConfig.touchscreen;
901 config.reqKeyboardType = globalConfig.keyboard;
902 config.reqNavigation = globalConfig.navigation;
903 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
904 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
905 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
906 }
907 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
908 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
909 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
910 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700911 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 }
913 return config;
914 }
915
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700916 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700917 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700918 }
919
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 public static final class Lifecycle extends SystemService {
921 private final ActivityTaskManagerService mService;
922
923 public Lifecycle(Context context) {
924 super(context);
925 mService = new ActivityTaskManagerService(context);
926 }
927
928 @Override
929 public void onStart() {
930 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700931 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700932 }
933
Garfield Tan891146c2018-10-09 12:14:00 -0700934 @Override
935 public void onUnlockUser(int userId) {
936 synchronized (mService.getGlobalLock()) {
937 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
938 }
939 }
940
941 @Override
942 public void onCleanupUser(int userId) {
943 synchronized (mService.getGlobalLock()) {
944 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
945 }
946 }
947
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700948 public ActivityTaskManagerService getService() {
949 return mService;
950 }
951 }
952
953 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700954 public final int startActivity(IApplicationThread caller, String callingPackage,
955 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
956 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
957 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
958 resultWho, requestCode, startFlags, profilerInfo, bOptions,
959 UserHandle.getCallingUserId());
960 }
961
962 @Override
963 public final int startActivities(IApplicationThread caller, String callingPackage,
964 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
965 int userId) {
966 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700967 enforceNotIsolatedCaller(reason);
968 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000970 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
971 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
972 reason, null /* originatingPendingIntent */,
973 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700974 }
975
976 @Override
977 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
978 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
979 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
980 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
981 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
982 true /*validateIncomingUser*/);
983 }
984
985 int startActivityAsUser(IApplicationThread caller, String callingPackage,
986 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
987 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
988 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700989 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700990
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700991 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700992 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
993
994 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700995 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 .setCaller(caller)
997 .setCallingPackage(callingPackage)
998 .setResolvedType(resolvedType)
999 .setResultTo(resultTo)
1000 .setResultWho(resultWho)
1001 .setRequestCode(requestCode)
1002 .setStartFlags(startFlags)
1003 .setProfilerInfo(profilerInfo)
1004 .setActivityOptions(bOptions)
1005 .setMayWait(userId)
1006 .execute();
1007
1008 }
1009
1010 @Override
1011 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1012 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001013 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1014 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 // Refuse possible leaked file descriptors
1016 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1017 throw new IllegalArgumentException("File descriptors passed in Intent");
1018 }
1019
1020 if (!(target instanceof PendingIntentRecord)) {
1021 throw new IllegalArgumentException("Bad PendingIntent object");
1022 }
1023
1024 PendingIntentRecord pir = (PendingIntentRecord)target;
1025
1026 synchronized (mGlobalLock) {
1027 // If this is coming from the currently resumed activity, it is
1028 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001029 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 if (stack.mResumedActivity != null &&
1031 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 }
1034 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 }
1038
1039 @Override
1040 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1041 Bundle bOptions) {
1042 // Refuse possible leaked file descriptors
1043 if (intent != null && intent.hasFileDescriptors()) {
1044 throw new IllegalArgumentException("File descriptors passed in Intent");
1045 }
1046 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1047
1048 synchronized (mGlobalLock) {
1049 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1050 if (r == null) {
1051 SafeActivityOptions.abort(options);
1052 return false;
1053 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001054 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 // The caller is not running... d'oh!
1056 SafeActivityOptions.abort(options);
1057 return false;
1058 }
1059 intent = new Intent(intent);
1060 // The caller is not allowed to change the data.
1061 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1062 // And we are resetting to find the next component...
1063 intent.setComponent(null);
1064
1065 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1066
1067 ActivityInfo aInfo = null;
1068 try {
1069 List<ResolveInfo> resolves =
1070 AppGlobals.getPackageManager().queryIntentActivities(
1071 intent, r.resolvedType,
1072 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1073 UserHandle.getCallingUserId()).getList();
1074
1075 // Look for the original activity in the list...
1076 final int N = resolves != null ? resolves.size() : 0;
1077 for (int i=0; i<N; i++) {
1078 ResolveInfo rInfo = resolves.get(i);
1079 if (rInfo.activityInfo.packageName.equals(r.packageName)
1080 && rInfo.activityInfo.name.equals(r.info.name)) {
1081 // We found the current one... the next matching is
1082 // after it.
1083 i++;
1084 if (i<N) {
1085 aInfo = resolves.get(i).activityInfo;
1086 }
1087 if (debug) {
1088 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1089 + "/" + r.info.name);
1090 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1091 ? "null" : aInfo.packageName + "/" + aInfo.name));
1092 }
1093 break;
1094 }
1095 }
1096 } catch (RemoteException e) {
1097 }
1098
1099 if (aInfo == null) {
1100 // Nobody who is next!
1101 SafeActivityOptions.abort(options);
1102 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1103 return false;
1104 }
1105
1106 intent.setComponent(new ComponentName(
1107 aInfo.applicationInfo.packageName, aInfo.name));
1108 intent.setFlags(intent.getFlags()&~(
1109 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1110 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1111 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1112 FLAG_ACTIVITY_NEW_TASK));
1113
1114 // Okay now we need to start the new activity, replacing the currently running activity.
1115 // This is a little tricky because we want to start the new one as if the current one is
1116 // finished, but not finish the current one first so that there is no flicker.
1117 // And thus...
1118 final boolean wasFinishing = r.finishing;
1119 r.finishing = true;
1120
1121 // Propagate reply information over to the new activity.
1122 final ActivityRecord resultTo = r.resultTo;
1123 final String resultWho = r.resultWho;
1124 final int requestCode = r.requestCode;
1125 r.resultTo = null;
1126 if (resultTo != null) {
1127 resultTo.removeResultsLocked(r, resultWho, requestCode);
1128 }
1129
1130 final long origId = Binder.clearCallingIdentity();
1131 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001132 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001133 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001134 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 .setResolvedType(r.resolvedType)
1136 .setActivityInfo(aInfo)
1137 .setResultTo(resultTo != null ? resultTo.appToken : null)
1138 .setResultWho(resultWho)
1139 .setRequestCode(requestCode)
1140 .setCallingPid(-1)
1141 .setCallingUid(r.launchedFromUid)
1142 .setCallingPackage(r.launchedFromPackage)
1143 .setRealCallingPid(-1)
1144 .setRealCallingUid(r.launchedFromUid)
1145 .setActivityOptions(options)
1146 .execute();
1147 Binder.restoreCallingIdentity(origId);
1148
1149 r.finishing = wasFinishing;
1150 if (res != ActivityManager.START_SUCCESS) {
1151 return false;
1152 }
1153 return true;
1154 }
1155 }
1156
1157 @Override
1158 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1159 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1160 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1161 final WaitResult res = new WaitResult();
1162 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001163 enforceNotIsolatedCaller("startActivityAndWait");
1164 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1165 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001166 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001167 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 .setCaller(caller)
1169 .setCallingPackage(callingPackage)
1170 .setResolvedType(resolvedType)
1171 .setResultTo(resultTo)
1172 .setResultWho(resultWho)
1173 .setRequestCode(requestCode)
1174 .setStartFlags(startFlags)
1175 .setActivityOptions(bOptions)
1176 .setMayWait(userId)
1177 .setProfilerInfo(profilerInfo)
1178 .setWaitResult(res)
1179 .execute();
1180 }
1181 return res;
1182 }
1183
1184 @Override
1185 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1186 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1187 int startFlags, Configuration config, Bundle bOptions, int userId) {
1188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001189 enforceNotIsolatedCaller("startActivityWithConfig");
1190 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1191 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .setCaller(caller)
1195 .setCallingPackage(callingPackage)
1196 .setResolvedType(resolvedType)
1197 .setResultTo(resultTo)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setStartFlags(startFlags)
1201 .setGlobalConfiguration(config)
1202 .setActivityOptions(bOptions)
1203 .setMayWait(userId)
1204 .execute();
1205 }
1206 }
1207
Alison Cichowlas3e340502018-08-07 17:15:01 -04001208
1209 @Override
1210 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1211 int callingUid = Binder.getCallingUid();
1212 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1213 throw new SecurityException("Only the system process can request a permission token, "
1214 + "received request from uid: " + callingUid);
1215 }
1216 IBinder permissionToken = new Binder();
1217 synchronized (mGlobalLock) {
1218 mStartActivitySources.put(permissionToken, delegatorToken);
1219 }
1220
1221 Message expireMsg = PooledLambda.obtainMessage(
1222 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1223 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1224
1225 Message forgetMsg = PooledLambda.obtainMessage(
1226 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1227 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1228
1229 return permissionToken;
1230 }
1231
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001232 @Override
1233 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1236 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001238 // permission grants) as any app that may launch one of your own activities. So we only
1239 // allow this in two cases:
1240 // 1) The caller is an activity that is part of the core framework, and then only when it
1241 // is running as the system.
1242 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1243 // can only be requested by a system activity, which may then delegate this call to
1244 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 final ActivityRecord sourceRecord;
1246 final int targetUid;
1247 final String targetPackage;
1248 final boolean isResolver;
1249 synchronized (mGlobalLock) {
1250 if (resultTo == null) {
1251 throw new SecurityException("Must be called from an activity");
1252 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001253 final IBinder sourceToken;
1254 if (permissionToken != null) {
1255 // To even attempt to use a permissionToken, an app must also have this signature
1256 // permission.
1257 mAmInternal.enforceCallingPermission(
1258 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1259 "startActivityAsCaller");
1260 // If called with a permissionToken, we want the sourceRecord from the delegator
1261 // activity that requested this token.
1262 sourceToken = mStartActivitySources.remove(permissionToken);
1263 if (sourceToken == null) {
1264 // Invalid permissionToken, check if it recently expired.
1265 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1266 throw new SecurityException("Called with expired permission token: "
1267 + permissionToken);
1268 } else {
1269 throw new SecurityException("Called with invalid permission token: "
1270 + permissionToken);
1271 }
1272 }
1273 } else {
1274 // This method was called directly by the source.
1275 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277
Wale Ogunwaled32da472018-11-16 07:19:28 -08001278 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 if (sourceRecord == null) {
1280 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 }
1282 if (sourceRecord.app == null) {
1283 throw new SecurityException("Called without a process attached to activity");
1284 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285
1286 // Whether called directly or from a delegate, the source activity must be from the
1287 // android package.
1288 if (!sourceRecord.info.packageName.equals("android")) {
1289 throw new SecurityException("Must be called from an activity that is "
1290 + "declared in the android package");
1291 }
1292
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001293 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001294 // This is still okay, as long as this activity is running under the
1295 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001296 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001298 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 + " must be system uid or original calling uid "
1300 + sourceRecord.launchedFromUid);
1301 }
1302 }
1303 if (ignoreTargetSecurity) {
1304 if (intent.getComponent() == null) {
1305 throw new SecurityException(
1306 "Component must be specified with ignoreTargetSecurity");
1307 }
1308 if (intent.getSelector() != null) {
1309 throw new SecurityException(
1310 "Selector not allowed with ignoreTargetSecurity");
1311 }
1312 }
1313 targetUid = sourceRecord.launchedFromUid;
1314 targetPackage = sourceRecord.launchedFromPackage;
1315 isResolver = sourceRecord.isResolverOrChildActivity();
1316 }
1317
1318 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001319 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
1321
1322 // TODO: Switch to user app stacks here.
1323 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001324 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 .setCallingUid(targetUid)
1326 .setCallingPackage(targetPackage)
1327 .setResolvedType(resolvedType)
1328 .setResultTo(resultTo)
1329 .setResultWho(resultWho)
1330 .setRequestCode(requestCode)
1331 .setStartFlags(startFlags)
1332 .setActivityOptions(bOptions)
1333 .setMayWait(userId)
1334 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1335 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1336 .execute();
1337 } catch (SecurityException e) {
1338 // XXX need to figure out how to propagate to original app.
1339 // A SecurityException here is generally actually a fault of the original
1340 // calling activity (such as a fairly granting permissions), so propagate it
1341 // back to them.
1342 /*
1343 StringBuilder msg = new StringBuilder();
1344 msg.append("While launching");
1345 msg.append(intent.toString());
1346 msg.append(": ");
1347 msg.append(e.getMessage());
1348 */
1349 throw e;
1350 }
1351 }
1352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1354 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1355 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1356 }
1357
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 @Override
1359 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1360 Intent intent, String resolvedType, IVoiceInteractionSession session,
1361 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1362 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001363 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 if (session == null || interactor == null) {
1365 throw new NullPointerException("null session or interactor");
1366 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001369 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 .setCallingUid(callingUid)
1371 .setCallingPackage(callingPackage)
1372 .setResolvedType(resolvedType)
1373 .setVoiceSession(session)
1374 .setVoiceInteractor(interactor)
1375 .setStartFlags(startFlags)
1376 .setProfilerInfo(profilerInfo)
1377 .setActivityOptions(bOptions)
1378 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001379 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 .execute();
1381 }
1382
1383 @Override
1384 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1385 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001386 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1387 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001389 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 .setCallingUid(callingUid)
1391 .setCallingPackage(callingPackage)
1392 .setResolvedType(resolvedType)
1393 .setActivityOptions(bOptions)
1394 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001395 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .execute();
1397 }
1398
1399 @Override
1400 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1401 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001402 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 final int callingPid = Binder.getCallingPid();
1404 final long origId = Binder.clearCallingIdentity();
1405 try {
1406 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001407 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1408 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409
1410 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1412 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1414 recentsUid, assistDataReceiver);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(origId);
1418 }
1419 }
1420
1421 @Override
1422 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 "startActivityFromRecents()");
1425
1426 final int callingPid = Binder.getCallingPid();
1427 final int callingUid = Binder.getCallingUid();
1428 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1429 final long origId = Binder.clearCallingIdentity();
1430 try {
1431 synchronized (mGlobalLock) {
1432 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1433 safeOptions);
1434 }
1435 } finally {
1436 Binder.restoreCallingIdentity(origId);
1437 }
1438 }
1439
1440 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001441 * Public API to check if the client is allowed to start an activity on specified display.
1442 *
1443 * If the target display is private or virtual, some restrictions will apply.
1444 *
1445 * @param displayId Target display id.
1446 * @param intent Intent used to launch the activity.
1447 * @param resolvedType The MIME type of the intent.
1448 * @param userId The id of the user for whom the call is made.
1449 * @return {@code true} if a call to start an activity on the target display should succeed and
1450 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1451 */
1452 @Override
1453 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1454 String resolvedType, int userId) {
1455 final int callingUid = Binder.getCallingUid();
1456 final int callingPid = Binder.getCallingPid();
1457 final long origId = Binder.clearCallingIdentity();
1458
1459 try {
1460 // Collect information about the target of the Intent.
1461 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1462 0 /* startFlags */, null /* profilerInfo */, userId,
1463 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1464 UserHandle.USER_NULL));
1465 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1466
1467 synchronized (mGlobalLock) {
1468 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1469 aInfo);
1470 }
1471 } finally {
1472 Binder.restoreCallingIdentity(origId);
1473 }
1474 }
1475
1476 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 * This is the internal entry point for handling Activity.finish().
1478 *
1479 * @param token The Binder token referencing the Activity we want to finish.
1480 * @param resultCode Result code, if any, from this Activity.
1481 * @param resultData Result data (Intent), if any, from this Activity.
1482 * @param finishTask Whether to finish the task associated with this Activity.
1483 *
1484 * @return Returns true if the activity successfully finished, or false if it is still running.
1485 */
1486 @Override
1487 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1488 int finishTask) {
1489 // Refuse possible leaked file descriptors
1490 if (resultData != null && resultData.hasFileDescriptors()) {
1491 throw new IllegalArgumentException("File descriptors passed in Intent");
1492 }
1493
1494 synchronized (mGlobalLock) {
1495 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1496 if (r == null) {
1497 return true;
1498 }
1499 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001500 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001501 ActivityRecord rootR = tr.getRootActivity();
1502 if (rootR == null) {
1503 Slog.w(TAG, "Finishing task with all activities already finished");
1504 }
1505 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1506 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001507 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 return false;
1509 }
1510
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001511 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1512 // We should consolidate.
1513 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001514 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001515 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 if (next != null) {
1517 // ask watcher if this is allowed
1518 boolean resumeOK = true;
1519 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001520 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001522 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 Watchdog.getInstance().setActivityController(null);
1524 }
1525
1526 if (!resumeOK) {
1527 Slog.i(TAG, "Not finishing activity because controller resumed");
1528 return false;
1529 }
1530 }
1531 }
1532 final long origId = Binder.clearCallingIdentity();
1533 try {
1534 boolean res;
1535 final boolean finishWithRootActivity =
1536 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1537 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1538 || (finishWithRootActivity && r == rootR)) {
1539 // If requested, remove the task that is associated to this activity only if it
1540 // was the root activity in the task. The result code and data is ignored
1541 // because we don't support returning them across task boundaries. Also, to
1542 // keep backwards compatibility we remove the task from recents when finishing
1543 // task with root activity.
1544 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1545 finishWithRootActivity, "finish-activity");
1546 if (!res) {
1547 Slog.i(TAG, "Removing task failed to finish activity");
1548 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001549 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001550 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 } else {
1552 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1553 resultData, "app-request", true);
1554 if (!res) {
1555 Slog.i(TAG, "Failed to finish by app-request");
1556 }
1557 }
1558 return res;
1559 } finally {
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562 }
1563 }
1564
1565 @Override
1566 public boolean finishActivityAffinity(IBinder token) {
1567 synchronized (mGlobalLock) {
1568 final long origId = Binder.clearCallingIdentity();
1569 try {
1570 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1571 if (r == null) {
1572 return false;
1573 }
1574
1575 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1576 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001577 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001578 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 return false;
1580 }
1581 return task.getStack().finishActivityAffinityLocked(r);
1582 } finally {
1583 Binder.restoreCallingIdentity(origId);
1584 }
1585 }
1586 }
1587
1588 @Override
1589 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1590 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001591 try {
1592 WindowProcessController proc = null;
1593 synchronized (mGlobalLock) {
1594 ActivityStack stack = ActivityRecord.getStackLocked(token);
1595 if (stack == null) {
1596 return;
1597 }
1598 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1599 false /* fromTimeout */, false /* processPausingActivities */, config);
1600 if (r != null) {
1601 proc = r.app;
1602 }
1603 if (stopProfiling && proc != null) {
1604 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 }
1606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001607 } finally {
1608 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 }
1611
1612 @Override
1613 public final void activityResumed(IBinder token) {
1614 final long origId = Binder.clearCallingIdentity();
1615 synchronized (mGlobalLock) {
1616 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001617 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityPaused(IBinder token) {
1624 final long origId = Binder.clearCallingIdentity();
1625 synchronized (mGlobalLock) {
1626 ActivityStack stack = ActivityRecord.getStackLocked(token);
1627 if (stack != null) {
1628 stack.activityPausedLocked(token, false);
1629 }
1630 }
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633
1634 @Override
1635 public final void activityStopped(IBinder token, Bundle icicle,
1636 PersistableBundle persistentState, CharSequence description) {
1637 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1638
1639 // Refuse possible leaked file descriptors
1640 if (icicle != null && icicle.hasFileDescriptors()) {
1641 throw new IllegalArgumentException("File descriptors passed in Bundle");
1642 }
1643
1644 final long origId = Binder.clearCallingIdentity();
1645
1646 synchronized (mGlobalLock) {
1647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1648 if (r != null) {
1649 r.activityStoppedLocked(icicle, persistentState, description);
1650 }
1651 }
1652
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001653 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654
1655 Binder.restoreCallingIdentity(origId);
1656 }
1657
1658 @Override
1659 public final void activityDestroyed(IBinder token) {
1660 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1661 synchronized (mGlobalLock) {
1662 ActivityStack stack = ActivityRecord.getStackLocked(token);
1663 if (stack != null) {
1664 stack.activityDestroyedLocked(token, "activityDestroyed");
1665 }
1666 }
1667 }
1668
1669 @Override
1670 public final void activityRelaunched(IBinder token) {
1671 final long origId = Binder.clearCallingIdentity();
1672 synchronized (mGlobalLock) {
1673 mStackSupervisor.activityRelaunchedLocked(token);
1674 }
1675 Binder.restoreCallingIdentity(origId);
1676 }
1677
1678 public final void activitySlept(IBinder token) {
1679 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1680
1681 final long origId = Binder.clearCallingIdentity();
1682
1683 synchronized (mGlobalLock) {
1684 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r != null) {
1686 mStackSupervisor.activitySleptLocked(r);
1687 }
1688 }
1689
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
1694 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1695 synchronized (mGlobalLock) {
1696 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1697 if (r == null) {
1698 return;
1699 }
1700 final long origId = Binder.clearCallingIdentity();
1701 try {
1702 r.setRequestedOrientation(requestedOrientation);
1703 } finally {
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706 }
1707 }
1708
1709 @Override
1710 public int getRequestedOrientation(IBinder token) {
1711 synchronized (mGlobalLock) {
1712 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1713 if (r == null) {
1714 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1715 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001716 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 }
1718 }
1719
1720 @Override
1721 public void setImmersive(IBinder token, boolean immersive) {
1722 synchronized (mGlobalLock) {
1723 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1724 if (r == null) {
1725 throw new IllegalArgumentException();
1726 }
1727 r.immersive = immersive;
1728
1729 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001730 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001732 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734 }
1735 }
1736
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001737 void applyUpdateLockStateLocked(ActivityRecord r) {
1738 // Modifications to the UpdateLock state are done on our handler, outside
1739 // the activity manager's locks. The new state is determined based on the
1740 // state *now* of the relevant activity record. The object is passed to
1741 // the handler solely for logging detail, not to be consulted/modified.
1742 final boolean nextState = r != null && r.immersive;
1743 mH.post(() -> {
1744 if (mUpdateLock.isHeld() != nextState) {
1745 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1746 "Applying new update lock state '" + nextState + "' for " + r);
1747 if (nextState) {
1748 mUpdateLock.acquire();
1749 } else {
1750 mUpdateLock.release();
1751 }
1752 }
1753 });
1754 }
1755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 @Override
1757 public boolean isImmersive(IBinder token) {
1758 synchronized (mGlobalLock) {
1759 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1760 if (r == null) {
1761 throw new IllegalArgumentException();
1762 }
1763 return r.immersive;
1764 }
1765 }
1766
1767 @Override
1768 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001769 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001771 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 return (r != null) ? r.immersive : false;
1773 }
1774 }
1775
1776 @Override
1777 public void overridePendingTransition(IBinder token, String packageName,
1778 int enterAnim, int exitAnim) {
1779 synchronized (mGlobalLock) {
1780 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1781 if (self == null) {
1782 return;
1783 }
1784
1785 final long origId = Binder.clearCallingIdentity();
1786
1787 if (self.isState(
1788 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001789 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001790 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795 }
1796
1797 @Override
1798 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001801 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 if (r == null) {
1803 return ActivityManager.COMPAT_MODE_UNKNOWN;
1804 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001805 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
1807 }
1808
1809 @Override
1810 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001815 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 if (r == null) {
1817 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1818 return;
1819 }
1820 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001821 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001822 }
1823 }
1824
1825 @Override
1826 public int getLaunchedFromUid(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return -1;
1833 }
1834 return srec.launchedFromUid;
1835 }
1836
1837 @Override
1838 public String getLaunchedFromPackage(IBinder activityToken) {
1839 ActivityRecord srec;
1840 synchronized (mGlobalLock) {
1841 srec = ActivityRecord.forTokenLocked(activityToken);
1842 }
1843 if (srec == null) {
1844 return null;
1845 }
1846 return srec.launchedFromPackage;
1847 }
1848
1849 @Override
1850 public boolean convertFromTranslucent(IBinder token) {
1851 final long origId = Binder.clearCallingIdentity();
1852 try {
1853 synchronized (mGlobalLock) {
1854 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 return false;
1857 }
1858 final boolean translucentChanged = r.changeWindowTranslucency(true);
1859 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001860 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 return translucentChanged;
1864 }
1865 } finally {
1866 Binder.restoreCallingIdentity(origId);
1867 }
1868 }
1869
1870 @Override
1871 public boolean convertToTranslucent(IBinder token, Bundle options) {
1872 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1873 final long origId = Binder.clearCallingIdentity();
1874 try {
1875 synchronized (mGlobalLock) {
1876 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1877 if (r == null) {
1878 return false;
1879 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001880 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 int index = task.mActivities.lastIndexOf(r);
1882 if (index > 0) {
1883 ActivityRecord under = task.mActivities.get(index - 1);
1884 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1885 }
1886 final boolean translucentChanged = r.changeWindowTranslucency(false);
1887 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001888 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001890 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 return translucentChanged;
1893 }
1894 } finally {
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898
1899 @Override
1900 public void notifyActivityDrawn(IBinder token) {
1901 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1902 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001903 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001905 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908 }
1909
1910 @Override
1911 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 return;
1916 }
1917 r.reportFullyDrawnLocked(restoredFromBundle);
1918 }
1919 }
1920
1921 @Override
1922 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1923 synchronized (mGlobalLock) {
1924 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1925 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1926 return stack.mDisplayId;
1927 }
1928 return DEFAULT_DISPLAY;
1929 }
1930 }
1931
1932 @Override
1933 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 long ident = Binder.clearCallingIdentity();
1936 try {
1937 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001938 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001940 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 }
1942 return null;
1943 }
1944 } finally {
1945 Binder.restoreCallingIdentity(ident);
1946 }
1947 }
1948
1949 @Override
1950 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1953 final long callingId = Binder.clearCallingIdentity();
1954 try {
1955 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001956 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 if (stack == null) {
1958 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1959 return;
1960 }
1961 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001962 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966 } finally {
1967 Binder.restoreCallingIdentity(callingId);
1968 }
1969 }
1970
1971 @Override
1972 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001973 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1975 final long callingId = Binder.clearCallingIdentity();
1976 try {
1977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001978 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001979 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 if (task == null) {
1981 return;
1982 }
1983 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001984 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001985 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
1987 }
1988 } finally {
1989 Binder.restoreCallingIdentity(callingId);
1990 }
1991 }
1992
1993 @Override
1994 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 synchronized (mGlobalLock) {
1997 final long ident = Binder.clearCallingIdentity();
1998 try {
1999 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2000 "remove-task");
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 }
2005 }
2006
2007 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002008 public void removeAllVisibleRecentTasks() {
2009 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2010 synchronized (mGlobalLock) {
2011 final long ident = Binder.clearCallingIdentity();
2012 try {
2013 getRecentTasks().removeAllVisibleTasks();
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018 }
2019
2020 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2022 synchronized (mGlobalLock) {
2023 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2024 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 }
2028 return false;
2029 }
2030
2031 @Override
2032 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2033 Intent resultData) {
2034
2035 synchronized (mGlobalLock) {
2036 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2037 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002038 return r.getActivityStack().navigateUpToLocked(
2039 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return false;
2042 }
2043 }
2044
2045 /**
2046 * Attempts to move a task backwards in z-order (the order of activities within the task is
2047 * unchanged).
2048 *
2049 * There are several possible results of this call:
2050 * - if the task is locked, then we will show the lock toast
2051 * - if there is a task behind the provided task, then that task is made visible and resumed as
2052 * this task is moved to the back
2053 * - otherwise, if there are no other tasks in the stack:
2054 * - if this task is in the pinned stack, then we remove the stack completely, which will
2055 * have the effect of moving the task to the top or bottom of the fullscreen stack
2056 * (depending on whether it is visible)
2057 * - otherwise, we simply return home and hide this task
2058 *
2059 * @param token A reference to the activity we wish to move
2060 * @param nonRoot If false then this only works if the activity is the root
2061 * of a task; if true it will work for any activity in a task.
2062 * @return Returns true if the move completed, false if not.
2063 */
2064 @Override
2065 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 synchronized (mGlobalLock) {
2068 final long origId = Binder.clearCallingIdentity();
2069 try {
2070 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 if (task != null) {
2073 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(origId);
2077 }
2078 }
2079 return false;
2080 }
2081
2082 @Override
2083 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 long ident = Binder.clearCallingIdentity();
2086 Rect rect = new Rect();
2087 try {
2088 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002089 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2091 if (task == null) {
2092 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2093 return rect;
2094 }
2095 if (task.getStack() != null) {
2096 // Return the bounds from window manager since it will be adjusted for various
2097 // things like the presense of a docked stack for tasks that aren't resizeable.
2098 task.getWindowContainerBounds(rect);
2099 } else {
2100 // Task isn't in window manager yet since it isn't associated with a stack.
2101 // Return the persist value from activity manager
2102 if (!task.matchParentBounds()) {
2103 rect.set(task.getBounds());
2104 } else if (task.mLastNonFullscreenBounds != null) {
2105 rect.set(task.mLastNonFullscreenBounds);
2106 }
2107 }
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
2112 return rect;
2113 }
2114
2115 @Override
2116 public ActivityManager.TaskDescription getTaskDescription(int id) {
2117 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002120 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2122 if (tr != null) {
2123 return tr.lastTaskDescription;
2124 }
2125 }
2126 return null;
2127 }
2128
2129 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2131 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2132 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2133 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2134 return;
2135 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002136 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002137 synchronized (mGlobalLock) {
2138 final long ident = Binder.clearCallingIdentity();
2139 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002140 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002141 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002142 if (task == null) {
2143 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2144 return;
2145 }
2146
2147 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2148 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2149
2150 if (!task.isActivityTypeStandardOrUndefined()) {
2151 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2152 + " non-standard task " + taskId + " to windowing mode="
2153 + windowingMode);
2154 }
2155
2156 final ActivityStack stack = task.getStack();
2157 if (toTop) {
2158 stack.moveToFront("setTaskWindowingMode", task);
2159 }
2160 stack.setWindowingMode(windowingMode);
2161 } finally {
2162 Binder.restoreCallingIdentity(ident);
2163 }
2164 }
2165 }
2166
2167 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002169 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 ActivityRecord r = getCallingRecordLocked(token);
2171 return r != null ? r.info.packageName : null;
2172 }
2173 }
2174
2175 @Override
2176 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002177 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 ActivityRecord r = getCallingRecordLocked(token);
2179 return r != null ? r.intent.getComponent() : null;
2180 }
2181 }
2182
2183 private ActivityRecord getCallingRecordLocked(IBinder token) {
2184 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2185 if (r == null) {
2186 return null;
2187 }
2188 return r.resultTo;
2189 }
2190
2191 @Override
2192 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194
2195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002198 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 } finally {
2200 Binder.restoreCallingIdentity(origId);
2201 }
2202 }
2203 }
2204
2205 /**
2206 * TODO: Add mController hook
2207 */
2208 @Override
2209 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211
2212 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2213 synchronized (mGlobalLock) {
2214 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2215 false /* fromRecents */);
2216 }
2217 }
2218
2219 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2220 boolean fromRecents) {
2221
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 Binder.getCallingUid(), -1, -1, "Task to front")) {
2224 SafeActivityOptions.abort(options);
2225 return;
2226 }
2227 final long origId = Binder.clearCallingIdentity();
2228 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002229 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 if (task == null) {
2231 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002232 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 return;
2234 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002235 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002237 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 return;
2239 }
2240 ActivityOptions realOptions = options != null
2241 ? options.getOptions(mStackSupervisor)
2242 : null;
2243 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2244 false /* forceNonResizable */);
2245
2246 final ActivityRecord topActivity = task.getTopActivity();
2247 if (topActivity != null) {
2248
2249 // We are reshowing a task, use a starting window to hide the initial draw delay
2250 // so the transition can start earlier.
2251 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2252 true /* taskSwitch */, fromRecents);
2253 }
2254 } finally {
2255 Binder.restoreCallingIdentity(origId);
2256 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 }
2258
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2260 int callingPid, int callingUid, String name) {
2261 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2262 return true;
2263 }
2264
2265 if (getRecentTasks().isCallerRecents(sourceUid)) {
2266 return true;
2267 }
2268
2269 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2270 if (perm == PackageManager.PERMISSION_GRANTED) {
2271 return true;
2272 }
2273 if (checkAllowAppSwitchUid(sourceUid)) {
2274 return true;
2275 }
2276
2277 // If the actual IPC caller is different from the logical source, then
2278 // also see if they are allowed to control app switches.
2279 if (callingUid != -1 && callingUid != sourceUid) {
2280 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2281 if (perm == PackageManager.PERMISSION_GRANTED) {
2282 return true;
2283 }
2284 if (checkAllowAppSwitchUid(callingUid)) {
2285 return true;
2286 }
2287 }
2288
2289 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2290 return false;
2291 }
2292
2293 private boolean checkAllowAppSwitchUid(int uid) {
2294 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2295 if (types != null) {
2296 for (int i = types.size() - 1; i >= 0; i--) {
2297 if (types.valueAt(i).intValue() == uid) {
2298 return true;
2299 }
2300 }
2301 }
2302 return false;
2303 }
2304
2305 @Override
2306 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2307 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2308 "setActivityController()");
2309 synchronized (mGlobalLock) {
2310 mController = controller;
2311 mControllerIsAMonkey = imAMonkey;
2312 Watchdog.getInstance().setActivityController(controller);
2313 }
2314 }
2315
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002316 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002317 synchronized (mGlobalLock) {
2318 return mController != null && mControllerIsAMonkey;
2319 }
2320 }
2321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 @Override
2323 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2324 synchronized (mGlobalLock) {
2325 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2326 }
2327 }
2328
2329 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2331 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2332 }
2333
2334 @Override
2335 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2336 @WindowConfiguration.ActivityType int ignoreActivityType,
2337 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2338 final int callingUid = Binder.getCallingUid();
2339 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2340
2341 synchronized (mGlobalLock) {
2342 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2343
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002345 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002346 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002347 ignoreWindowingMode, callingUid, allowed);
2348 }
2349
2350 return list;
2351 }
2352
2353 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2355 synchronized (mGlobalLock) {
2356 final long origId = Binder.clearCallingIdentity();
2357 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2358 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002359 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 }
2361 Binder.restoreCallingIdentity(origId);
2362 }
2363 }
2364
2365 @Override
2366 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 ActivityStack stack = ActivityRecord.getStackLocked(token);
2369 if (stack != null) {
2370 return stack.willActivityBeVisibleLocked(token);
2371 }
2372 return false;
2373 }
2374 }
2375
2376 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002377 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002378 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 synchronized (mGlobalLock) {
2380 final long ident = Binder.clearCallingIdentity();
2381 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002382 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 if (task == null) {
2384 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2385 return;
2386 }
2387
2388 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2389 + " to stackId=" + stackId + " toTop=" + toTop);
2390
Wale Ogunwaled32da472018-11-16 07:19:28 -08002391 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002392 if (stack == null) {
2393 throw new IllegalStateException(
2394 "moveTaskToStack: No stack for stackId=" + stackId);
2395 }
2396 if (!stack.isActivityTypeStandardOrUndefined()) {
2397 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2398 + taskId + " to stack " + stackId);
2399 }
2400 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2403 }
2404 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2405 "moveTaskToStack");
2406 } finally {
2407 Binder.restoreCallingIdentity(ident);
2408 }
2409 }
2410 }
2411
2412 @Override
2413 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2414 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416
2417 final long ident = Binder.clearCallingIdentity();
2418 try {
2419 synchronized (mGlobalLock) {
2420 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002421 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 if (stack == null) {
2423 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2424 return;
2425 }
2426 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2427 throw new IllegalArgumentException("Stack: " + stackId
2428 + " doesn't support animated resize.");
2429 }
2430 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2431 animationDuration, false /* fromFullscreen */);
2432 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002433 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002434 if (stack == null) {
2435 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2436 return;
2437 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002438 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2440 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2441 }
2442 }
2443 } finally {
2444 Binder.restoreCallingIdentity(ident);
2445 }
2446 }
2447
wilsonshih5c4cf522019-01-25 09:03:47 +08002448 @Override
2449 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2450 int animationDuration) {
2451 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2452
2453 final long ident = Binder.clearCallingIdentity();
2454 try {
2455 synchronized (mGlobalLock) {
2456 if (xOffset == 0 && yOffset == 0) {
2457 return;
2458 }
2459 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2460 if (stack == null) {
2461 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2462 return;
2463 }
2464 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2465 throw new IllegalArgumentException("Stack: " + stackId
2466 + " doesn't support animated resize.");
2467 }
2468 final Rect destBounds = new Rect();
2469 stack.getAnimationOrCurrentBounds(destBounds);
2470 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2471 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2472 return;
2473 }
2474 destBounds.offset(xOffset, yOffset);
2475 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2476 animationDuration, false /* fromFullscreen */);
2477 }
2478 } finally {
2479 Binder.restoreCallingIdentity(ident);
2480 }
2481 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002482 /**
2483 * Moves the specified task to the primary-split-screen stack.
2484 *
2485 * @param taskId Id of task to move.
2486 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2487 * exist already. See
2488 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2489 * and
2490 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2491 * @param toTop If the task and stack should be moved to the top.
2492 * @param animate Whether we should play an animation for the moving the task.
2493 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2494 * stack. Pass {@code null} to use default bounds.
2495 * @param showRecents If the recents activity should be shown on the other side of the task
2496 * going into split-screen mode.
2497 */
2498 @Override
2499 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2500 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002501 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 "setTaskWindowingModeSplitScreenPrimary()");
2503 synchronized (mGlobalLock) {
2504 final long ident = Binder.clearCallingIdentity();
2505 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002506 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002507 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 if (task == null) {
2509 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2510 return false;
2511 }
2512 if (DEBUG_STACK) Slog.d(TAG_STACK,
2513 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2514 + " to createMode=" + createMode + " toTop=" + toTop);
2515 if (!task.isActivityTypeStandardOrUndefined()) {
2516 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2517 + " non-standard task " + taskId + " to split-screen windowing mode");
2518 }
2519
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002520 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 final int windowingMode = task.getWindowingMode();
2522 final ActivityStack stack = task.getStack();
2523 if (toTop) {
2524 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2525 }
2526 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002527 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2528 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002529 return windowingMode != task.getWindowingMode();
2530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
2533 }
2534 }
2535
2536 /**
2537 * Removes stacks in the input windowing modes from the system if they are of activity type
2538 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2539 */
2540 @Override
2541 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002542 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 "removeStacksInWindowingModes()");
2544
2545 synchronized (mGlobalLock) {
2546 final long ident = Binder.clearCallingIdentity();
2547 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
2552 }
2553 }
2554
2555 @Override
2556 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 "removeStacksWithActivityTypes()");
2559
2560 synchronized (mGlobalLock) {
2561 final long ident = Binder.clearCallingIdentity();
2562 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002569
2570 @Override
2571 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2572 int userId) {
2573 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2575 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002577 final boolean detailed = checkGetTasksPermission(
2578 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2579 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002580 == PackageManager.PERMISSION_GRANTED;
2581
2582 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002583 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002584 callingUid);
2585 }
2586 }
2587
2588 @Override
2589 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002590 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002595 }
2596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
2599 }
2600
2601 @Override
2602 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 long ident = Binder.clearCallingIdentity();
2605 try {
2606 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002607 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608 }
2609 } finally {
2610 Binder.restoreCallingIdentity(ident);
2611 }
2612 }
2613
2614 @Override
2615 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002616 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002617 final long callingUid = Binder.getCallingUid();
2618 final long origId = Binder.clearCallingIdentity();
2619 try {
2620 synchronized (mGlobalLock) {
2621 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002622 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002623 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2624 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(origId);
2628 }
2629 }
2630
2631 @Override
2632 public void startLockTaskModeByToken(IBinder token) {
2633 synchronized (mGlobalLock) {
2634 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2635 if (r == null) {
2636 return;
2637 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002638 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639 }
2640 }
2641
2642 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002643 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002644 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002645 // This makes inner call to look as if it was initiated by system.
2646 long ident = Binder.clearCallingIdentity();
2647 try {
2648 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002649 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002650 MATCH_TASK_IN_STACKS_ONLY);
2651 if (task == null) {
2652 return;
2653 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654
2655 // When starting lock task mode the stack must be in front and focused
2656 task.getStack().moveToFront("startSystemLockTaskMode");
2657 startLockTaskModeLocked(task, true /* isSystemCaller */);
2658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(ident);
2661 }
2662 }
2663
2664 @Override
2665 public void stopLockTaskModeByToken(IBinder token) {
2666 synchronized (mGlobalLock) {
2667 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2668 if (r == null) {
2669 return;
2670 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002671 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002672 }
2673 }
2674
2675 /**
2676 * This API should be called by SystemUI only when user perform certain action to dismiss
2677 * lock task mode. We should only dismiss pinned lock task mode in this case.
2678 */
2679 @Override
2680 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002681 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2683 }
2684
2685 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2686 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2687 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2688 return;
2689 }
2690
Wale Ogunwaled32da472018-11-16 07:19:28 -08002691 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002692 if (stack == null || task != stack.topTask()) {
2693 throw new IllegalArgumentException("Invalid task, not in foreground");
2694 }
2695
2696 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2697 // system or a specific app.
2698 // * System-initiated requests will only start the pinned mode (screen pinning)
2699 // * App-initiated requests
2700 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2701 // - will start the pinned mode, otherwise
2702 final int callingUid = Binder.getCallingUid();
2703 long ident = Binder.clearCallingIdentity();
2704 try {
2705 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002706 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002707
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002708 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713
2714 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2715 final int callingUid = Binder.getCallingUid();
2716 long ident = Binder.clearCallingIdentity();
2717 try {
2718 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002719 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 }
2721 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2722 // task and jumping straight into a call in the case of emergency call back.
2723 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2724 if (tm != null) {
2725 tm.showInCallScreen(false);
2726 }
2727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731
2732 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002733 public void updateLockTaskPackages(int userId, String[] packages) {
2734 final int callingUid = Binder.getCallingUid();
2735 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2736 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2737 "updateLockTaskPackages()");
2738 }
2739 synchronized (this) {
2740 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2741 + Arrays.toString(packages));
2742 getLockTaskController().updateLockTaskPackages(userId, packages);
2743 }
2744 }
2745
2746 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 public boolean isInLockTaskMode() {
2748 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2749 }
2750
2751 @Override
2752 public int getLockTaskModeState() {
2753 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002754 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 }
2756 }
2757
2758 @Override
2759 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2760 synchronized (mGlobalLock) {
2761 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2762 if (r != null) {
2763 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002764 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002766 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 }
2769 }
2770
2771 @Override
2772 public Bundle getActivityOptions(IBinder token) {
2773 final long origId = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mGlobalLock) {
2776 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2777 if (r != null) {
2778 final ActivityOptions activityOptions = r.takeOptionsLocked();
2779 return activityOptions == null ? null : activityOptions.toBundle();
2780 }
2781 return null;
2782 }
2783 } finally {
2784 Binder.restoreCallingIdentity(origId);
2785 }
2786 }
2787
2788 @Override
2789 public List<IBinder> getAppTasks(String callingPackage) {
2790 int callingUid = Binder.getCallingUid();
2791 long ident = Binder.clearCallingIdentity();
2792 try {
2793 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002794 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
2799 }
2800
2801 @Override
2802 public void finishVoiceTask(IVoiceInteractionSession session) {
2803 synchronized (mGlobalLock) {
2804 final long origId = Binder.clearCallingIdentity();
2805 try {
2806 // TODO: VI Consider treating local voice interactions and voice tasks
2807 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002808 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 } finally {
2810 Binder.restoreCallingIdentity(origId);
2811 }
2812 }
2813
2814 }
2815
2816 @Override
2817 public boolean isTopOfTask(IBinder token) {
2818 synchronized (mGlobalLock) {
2819 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002820 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 }
2823
2824 @Override
2825 public void notifyLaunchTaskBehindComplete(IBinder token) {
2826 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2827 }
2828
2829 @Override
2830 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002831 mH.post(() -> {
2832 synchronized (mGlobalLock) {
2833 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002834 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002835 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002836 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002837 } catch (RemoteException e) {
2838 }
2839 }
2840 }
2841
2842 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 }
2844
2845 /** Called from an app when assist data is ready. */
2846 @Override
2847 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2848 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002849 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 synchronized (pae) {
2851 pae.result = extras;
2852 pae.structure = structure;
2853 pae.content = content;
2854 if (referrer != null) {
2855 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2856 }
2857 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002858 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002859 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2860 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002861 structure.setHomeActivity(pae.isHome);
2862 }
2863 pae.haveResult = true;
2864 pae.notifyAll();
2865 if (pae.intent == null && pae.receiver == null) {
2866 // Caller is just waiting for the result.
2867 return;
2868 }
2869 }
2870 // We are now ready to launch the assist activity.
2871 IAssistDataReceiver sendReceiver = null;
2872 Bundle sendBundle = null;
2873 synchronized (mGlobalLock) {
2874 buildAssistBundleLocked(pae, extras);
2875 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002876 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 if (!exists) {
2878 // Timed out.
2879 return;
2880 }
2881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002882 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 // Caller wants result sent back to them.
2884 sendBundle = new Bundle();
2885 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2886 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2887 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2888 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2889 }
2890 }
2891 if (sendReceiver != null) {
2892 try {
2893 sendReceiver.onHandleAssistData(sendBundle);
2894 } catch (RemoteException e) {
2895 }
2896 return;
2897 }
2898
2899 final long ident = Binder.clearCallingIdentity();
2900 try {
2901 if (TextUtils.equals(pae.intent.getAction(),
2902 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2903 pae.intent.putExtras(pae.extras);
2904 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2905 } else {
2906 pae.intent.replaceExtras(pae.extras);
2907 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2908 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2909 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002910 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911
2912 try {
2913 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2914 } catch (ActivityNotFoundException e) {
2915 Slog.w(TAG, "No activity to handle assist action.", e);
2916 }
2917 }
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
2923 @Override
2924 public int addAppTask(IBinder activityToken, Intent intent,
2925 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2926 final int callingUid = Binder.getCallingUid();
2927 final long callingIdent = Binder.clearCallingIdentity();
2928
2929 try {
2930 synchronized (mGlobalLock) {
2931 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2932 if (r == null) {
2933 throw new IllegalArgumentException("Activity does not exist; token="
2934 + activityToken);
2935 }
2936 ComponentName comp = intent.getComponent();
2937 if (comp == null) {
2938 throw new IllegalArgumentException("Intent " + intent
2939 + " must specify explicit component");
2940 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002941 if (thumbnail.getWidth() != mThumbnailWidth
2942 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 throw new IllegalArgumentException("Bad thumbnail size: got "
2944 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002945 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 if (intent.getSelector() != null) {
2948 intent.setSelector(null);
2949 }
2950 if (intent.getSourceBounds() != null) {
2951 intent.setSourceBounds(null);
2952 }
2953 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2954 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2955 // The caller has added this as an auto-remove task... that makes no
2956 // sense, so turn off auto-remove.
2957 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2958 }
2959 }
2960 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2961 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2962 if (ainfo.applicationInfo.uid != callingUid) {
2963 throw new SecurityException(
2964 "Can't add task for another application: target uid="
2965 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2966 }
2967
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002968 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002970 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002972 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 // The app has too many tasks already and we can't add any more
2974 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2975 return INVALID_TASK_ID;
2976 }
2977 task.lastTaskDescription.copyFrom(description);
2978
2979 // TODO: Send the thumbnail to WM to store it.
2980
2981 return task.taskId;
2982 }
2983 } finally {
2984 Binder.restoreCallingIdentity(callingIdent);
2985 }
2986 }
2987
2988 @Override
2989 public Point getAppTaskThumbnailSize() {
2990 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002991 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void setTaskResizeable(int taskId, int resizeableMode) {
2997 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002998 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3000 if (task == null) {
3001 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3002 return;
3003 }
3004 task.setResizeMode(resizeableMode);
3005 }
3006 }
3007
3008 @Override
3009 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 long ident = Binder.clearCallingIdentity();
3012 try {
3013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003014 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003015 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 if (task == null) {
3017 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3018 return;
3019 }
3020 // Place the task in the right stack if it isn't there already based on
3021 // the requested bounds.
3022 // The stack transition logic is:
3023 // - a null bounds on a freeform task moves that task to fullscreen
3024 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3025 // that task to freeform
3026 // - otherwise the task is not moved
3027 ActivityStack stack = task.getStack();
3028 if (!task.getWindowConfiguration().canResizeTask()) {
3029 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3030 }
3031 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3032 stack = stack.getDisplay().getOrCreateStack(
3033 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3034 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3035 stack = stack.getDisplay().getOrCreateStack(
3036 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3037 }
3038
3039 // Reparent the task to the right stack if necessary
3040 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3041 if (stack != task.getStack()) {
3042 // Defer resume until the task is resized below
3043 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3044 DEFER_RESUME, "resizeTask");
3045 preserveWindow = false;
3046 }
3047
3048 // After reparenting (which only resizes the task to the stack bounds), resize the
3049 // task to the actual bounds provided
3050 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3051 }
3052 } finally {
3053 Binder.restoreCallingIdentity(ident);
3054 }
3055 }
3056
3057 @Override
3058 public boolean releaseActivityInstance(IBinder token) {
3059 synchronized (mGlobalLock) {
3060 final long origId = Binder.clearCallingIdentity();
3061 try {
3062 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3063 if (r == null) {
3064 return false;
3065 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003066 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 } finally {
3068 Binder.restoreCallingIdentity(origId);
3069 }
3070 }
3071 }
3072
3073 @Override
3074 public void releaseSomeActivities(IApplicationThread appInt) {
3075 synchronized (mGlobalLock) {
3076 final long origId = Binder.clearCallingIdentity();
3077 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003078 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003079 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 } finally {
3081 Binder.restoreCallingIdentity(origId);
3082 }
3083 }
3084 }
3085
3086 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003087 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003088 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 != PackageManager.PERMISSION_GRANTED) {
3090 throw new SecurityException("Requires permission "
3091 + android.Manifest.permission.DEVICE_POWER);
3092 }
3093
3094 synchronized (mGlobalLock) {
3095 long ident = Binder.clearCallingIdentity();
3096 if (mKeyguardShown != keyguardShowing) {
3097 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003098 final Message msg = PooledLambda.obtainMessage(
3099 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3100 keyguardShowing);
3101 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 }
3103 try {
wilsonshih177261f2019-02-22 12:02:18 +08003104 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003105 } finally {
3106 Binder.restoreCallingIdentity(ident);
3107 }
3108 }
3109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 mH.post(() -> {
3111 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3112 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3113 }
3114 });
3115 }
3116
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003117 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003118 mH.post(() -> {
3119 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3120 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3121 }
3122 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 }
3124
3125 @Override
3126 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003127 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3128 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003129
3130 final File passedIconFile = new File(filePath);
3131 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3132 passedIconFile.getName());
3133 if (!legitIconFile.getPath().equals(filePath)
3134 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3135 throw new IllegalArgumentException("Bad file path: " + filePath
3136 + " passed for userId " + userId);
3137 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003138 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 }
3140
3141 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003142 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003143 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3144 final ActivityOptions activityOptions = safeOptions != null
3145 ? safeOptions.getOptions(mStackSupervisor)
3146 : null;
3147 if (activityOptions == null
3148 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3149 || activityOptions.getCustomInPlaceResId() == 0) {
3150 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3151 "with valid animation");
3152 }
lumark588a3e82018-07-20 18:53:54 +08003153 // Get top display of front most application.
3154 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3155 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003156 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3157 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3158 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003159 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003160 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003161 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 }
3163
3164 @Override
3165 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003166 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003167 synchronized (mGlobalLock) {
3168 final long ident = Binder.clearCallingIdentity();
3169 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003170 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 if (stack == null) {
3172 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3173 return;
3174 }
3175 if (!stack.isActivityTypeStandardOrUndefined()) {
3176 throw new IllegalArgumentException(
3177 "Removing non-standard stack is not allowed.");
3178 }
3179 mStackSupervisor.removeStack(stack);
3180 } finally {
3181 Binder.restoreCallingIdentity(ident);
3182 }
3183 }
3184 }
3185
3186 @Override
3187 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189
3190 synchronized (mGlobalLock) {
3191 final long ident = Binder.clearCallingIdentity();
3192 try {
3193 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3194 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003195 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 } finally {
3197 Binder.restoreCallingIdentity(ident);
3198 }
3199 }
3200 }
3201
3202 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 public void exitFreeformMode(IBinder token) {
3204 synchronized (mGlobalLock) {
3205 long ident = Binder.clearCallingIdentity();
3206 try {
3207 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3208 if (r == null) {
3209 throw new IllegalArgumentException(
3210 "exitFreeformMode: No activity record matching token=" + token);
3211 }
3212
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003213 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 if (stack == null || !stack.inFreeformWindowingMode()) {
3215 throw new IllegalStateException(
3216 "exitFreeformMode: You can only go fullscreen from freeform.");
3217 }
3218
3219 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3220 } finally {
3221 Binder.restoreCallingIdentity(ident);
3222 }
3223 }
3224 }
3225
3226 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3227 @Override
3228 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003229 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003231 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003232 }
3233
3234 /** Unregister a task stack listener so that it stops receiving callbacks. */
3235 @Override
3236 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003237 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003239 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 }
3241
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 @Override
3243 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3244 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3245 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3246 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3247 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3248 }
3249
3250 @Override
3251 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3252 IBinder activityToken, int flags) {
3253 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3254 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3255 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3256 }
3257
3258 @Override
3259 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3260 Bundle args) {
3261 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3262 true /* focused */, true /* newSessionId */, userHandle, args,
3263 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3264 }
3265
3266 @Override
3267 public Bundle getAssistContextExtras(int requestType) {
3268 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3269 null, null, true /* focused */, true /* newSessionId */,
3270 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3271 if (pae == null) {
3272 return null;
3273 }
3274 synchronized (pae) {
3275 while (!pae.haveResult) {
3276 try {
3277 pae.wait();
3278 } catch (InterruptedException e) {
3279 }
3280 }
3281 }
3282 synchronized (mGlobalLock) {
3283 buildAssistBundleLocked(pae, pae.result);
3284 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003285 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003286 }
3287 return pae.extras;
3288 }
3289
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003290 /**
3291 * Binder IPC calls go through the public entry point.
3292 * This can be called with or without the global lock held.
3293 */
3294 private static int checkCallingPermission(String permission) {
3295 return checkPermission(
3296 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3297 }
3298
3299 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003300 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3302 mAmInternal.enforceCallingPermission(permission, func);
3303 }
3304 }
3305
3306 @VisibleForTesting
3307 int checkGetTasksPermission(String permission, int pid, int uid) {
3308 return checkPermission(permission, pid, uid);
3309 }
3310
3311 static int checkPermission(String permission, int pid, int uid) {
3312 if (permission == null) {
3313 return PackageManager.PERMISSION_DENIED;
3314 }
3315 return checkComponentPermission(permission, pid, uid, -1, true);
3316 }
3317
Wale Ogunwale214f3482018-10-04 11:00:47 -07003318 public static int checkComponentPermission(String permission, int pid, int uid,
3319 int owningUid, boolean exported) {
3320 return ActivityManagerService.checkComponentPermission(
3321 permission, pid, uid, owningUid, exported);
3322 }
3323
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003324 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3325 if (getRecentTasks().isCallerRecents(callingUid)) {
3326 // Always allow the recents component to get tasks
3327 return true;
3328 }
3329
3330 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3331 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3332 if (!allowed) {
3333 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3334 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3335 // Temporary compatibility: some existing apps on the system image may
3336 // still be requesting the old permission and not switched to the new
3337 // one; if so, we'll still allow them full access. This means we need
3338 // to see if they are holding the old permission and are a system app.
3339 try {
3340 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3341 allowed = true;
3342 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3343 + " is using old GET_TASKS but privileged; allowing");
3344 }
3345 } catch (RemoteException e) {
3346 }
3347 }
3348 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3349 + " does not hold REAL_GET_TASKS; limiting output");
3350 }
3351 return allowed;
3352 }
3353
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3355 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3356 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3357 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003358 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 "enqueueAssistContext()");
3360
3361 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003362 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363 if (activity == null) {
3364 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3365 return null;
3366 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003367 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3369 return null;
3370 }
3371 if (focused) {
3372 if (activityToken != null) {
3373 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3374 if (activity != caller) {
3375 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3376 + " is not current top " + activity);
3377 return null;
3378 }
3379 }
3380 } else {
3381 activity = ActivityRecord.forTokenLocked(activityToken);
3382 if (activity == null) {
3383 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3384 + " couldn't be found");
3385 return null;
3386 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003387 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3389 return null;
3390 }
3391 }
3392
3393 PendingAssistExtras pae;
3394 Bundle extras = new Bundle();
3395 if (args != null) {
3396 extras.putAll(args);
3397 }
3398 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003399 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400
3401 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3402 userHandle);
3403 pae.isHome = activity.isActivityTypeHome();
3404
3405 // Increment the sessionId if necessary
3406 if (newSessionId) {
3407 mViSessionId++;
3408 }
3409 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003410 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3411 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003413 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 } catch (RemoteException e) {
3415 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3416 return null;
3417 }
3418 return pae;
3419 }
3420 }
3421
3422 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3423 if (result != null) {
3424 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3425 }
3426 if (pae.hint != null) {
3427 pae.extras.putBoolean(pae.hint, true);
3428 }
3429 }
3430
3431 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3432 IAssistDataReceiver receiver;
3433 synchronized (mGlobalLock) {
3434 mPendingAssistExtras.remove(pae);
3435 receiver = pae.receiver;
3436 }
3437 if (receiver != null) {
3438 // Caller wants result sent back to them.
3439 Bundle sendBundle = new Bundle();
3440 // At least return the receiver extras
3441 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3442 try {
3443 pae.receiver.onHandleAssistData(sendBundle);
3444 } catch (RemoteException e) {
3445 }
3446 }
3447 }
3448
3449 public class PendingAssistExtras extends Binder implements Runnable {
3450 public final ActivityRecord activity;
3451 public boolean isHome;
3452 public final Bundle extras;
3453 public final Intent intent;
3454 public final String hint;
3455 public final IAssistDataReceiver receiver;
3456 public final int userHandle;
3457 public boolean haveResult = false;
3458 public Bundle result = null;
3459 public AssistStructure structure = null;
3460 public AssistContent content = null;
3461 public Bundle receiverExtras;
3462
3463 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3464 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3465 int _userHandle) {
3466 activity = _activity;
3467 extras = _extras;
3468 intent = _intent;
3469 hint = _hint;
3470 receiver = _receiver;
3471 receiverExtras = _receiverExtras;
3472 userHandle = _userHandle;
3473 }
3474
3475 @Override
3476 public void run() {
3477 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3478 synchronized (this) {
3479 haveResult = true;
3480 notifyAll();
3481 }
3482 pendingAssistExtrasTimedOut(this);
3483 }
3484 }
3485
3486 @Override
3487 public boolean isAssistDataAllowedOnCurrentActivity() {
3488 int userId;
3489 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003490 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003491 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3492 return false;
3493 }
3494
3495 final ActivityRecord activity = focusedStack.getTopActivity();
3496 if (activity == null) {
3497 return false;
3498 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003499 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003500 }
3501 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3502 }
3503
3504 @Override
3505 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3506 long ident = Binder.clearCallingIdentity();
3507 try {
3508 synchronized (mGlobalLock) {
3509 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003510 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 if (top != caller) {
3512 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3513 + " is not current top " + top);
3514 return false;
3515 }
3516 if (!top.nowVisible) {
3517 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3518 + " is not visible");
3519 return false;
3520 }
3521 }
3522 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3523 token);
3524 } finally {
3525 Binder.restoreCallingIdentity(ident);
3526 }
3527 }
3528
3529 @Override
3530 public boolean isRootVoiceInteraction(IBinder token) {
3531 synchronized (mGlobalLock) {
3532 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3533 if (r == null) {
3534 return false;
3535 }
3536 return r.rootVoiceInteraction;
3537 }
3538 }
3539
Wale Ogunwalef6733932018-06-27 05:14:34 -07003540 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3541 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3542 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3543 if (activityToCallback == null) return;
3544 activityToCallback.setVoiceSessionLocked(voiceSession);
3545
3546 // Inform the activity
3547 try {
3548 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3549 voiceInteractor);
3550 long token = Binder.clearCallingIdentity();
3551 try {
3552 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3553 } finally {
3554 Binder.restoreCallingIdentity(token);
3555 }
3556 // TODO: VI Should we cache the activity so that it's easier to find later
3557 // rather than scan through all the stacks and activities?
3558 } catch (RemoteException re) {
3559 activityToCallback.clearVoiceSessionLocked();
3560 // TODO: VI Should this terminate the voice session?
3561 }
3562 }
3563
3564 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3565 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3566 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3567 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3568 boolean wasRunningVoice = mRunningVoice != null;
3569 mRunningVoice = session;
3570 if (!wasRunningVoice) {
3571 mVoiceWakeLock.acquire();
3572 updateSleepIfNeededLocked();
3573 }
3574 }
3575 }
3576
3577 void finishRunningVoiceLocked() {
3578 if (mRunningVoice != null) {
3579 mRunningVoice = null;
3580 mVoiceWakeLock.release();
3581 updateSleepIfNeededLocked();
3582 }
3583 }
3584
3585 @Override
3586 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3587 synchronized (mGlobalLock) {
3588 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3589 if (keepAwake) {
3590 mVoiceWakeLock.acquire();
3591 } else {
3592 mVoiceWakeLock.release();
3593 }
3594 }
3595 }
3596 }
3597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 @Override
3599 public ComponentName getActivityClassForToken(IBinder token) {
3600 synchronized (mGlobalLock) {
3601 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3602 if (r == null) {
3603 return null;
3604 }
3605 return r.intent.getComponent();
3606 }
3607 }
3608
3609 @Override
3610 public String getPackageForToken(IBinder token) {
3611 synchronized (mGlobalLock) {
3612 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3613 if (r == null) {
3614 return null;
3615 }
3616 return r.packageName;
3617 }
3618 }
3619
3620 @Override
3621 public void showLockTaskEscapeMessage(IBinder token) {
3622 synchronized (mGlobalLock) {
3623 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3624 if (r == null) {
3625 return;
3626 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003627 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003628 }
3629 }
3630
3631 @Override
3632 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003633 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003634 final long token = Binder.clearCallingIdentity();
3635 try {
3636 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003637 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 }
3639 } finally {
3640 Binder.restoreCallingIdentity(token);
3641 }
3642 }
3643
3644 /**
3645 * Try to place task to provided position. The final position might be different depending on
3646 * current user and stacks state. The task will be moved to target stack if it's currently in
3647 * different stack.
3648 */
3649 @Override
3650 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003651 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003652 synchronized (mGlobalLock) {
3653 long ident = Binder.clearCallingIdentity();
3654 try {
3655 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3656 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003657 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 if (task == null) {
3659 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3660 + taskId);
3661 }
3662
Wale Ogunwaled32da472018-11-16 07:19:28 -08003663 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003664
3665 if (stack == null) {
3666 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3667 + stackId);
3668 }
3669 if (!stack.isActivityTypeStandardOrUndefined()) {
3670 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3671 + " the position of task " + taskId + " in/to non-standard stack");
3672 }
3673
3674 // TODO: Have the callers of this API call a separate reparent method if that is
3675 // what they intended to do vs. having this method also do reparenting.
3676 if (task.getStack() == stack) {
3677 // Change position in current stack.
3678 stack.positionChildAt(task, position);
3679 } else {
3680 // Reparent to new stack.
3681 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3682 !DEFER_RESUME, "positionTaskInStack");
3683 }
3684 } finally {
3685 Binder.restoreCallingIdentity(ident);
3686 }
3687 }
3688 }
3689
3690 @Override
3691 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3692 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3693 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3694 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3695 synchronized (mGlobalLock) {
3696 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3697 if (record == null) {
3698 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3699 + "found for: " + token);
3700 }
3701 record.setSizeConfigurations(horizontalSizeConfiguration,
3702 verticalSizeConfigurations, smallestSizeConfigurations);
3703 }
3704 }
3705
3706 /**
3707 * Dismisses split-screen multi-window mode.
3708 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3709 */
3710 @Override
3711 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003712 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003713 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3714 final long ident = Binder.clearCallingIdentity();
3715 try {
3716 synchronized (mGlobalLock) {
3717 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003718 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003719 if (stack == null) {
3720 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3721 return;
3722 }
3723
3724 if (toTop) {
3725 // Caller wants the current split-screen primary stack to be the top stack after
3726 // it goes fullscreen, so move it to the front.
3727 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003728 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 // In this case the current split-screen primary stack shouldn't be the top
3730 // stack after it goes fullscreen, but it current has focus, so we move the
3731 // focus to the top-most split-screen secondary stack next to it.
3732 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3733 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3734 if (otherStack != null) {
3735 otherStack.moveToFront("dismissSplitScreenMode_other");
3736 }
3737 }
3738
Evan Rosky10475742018-09-05 19:02:48 -07003739 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 }
3741 } finally {
3742 Binder.restoreCallingIdentity(ident);
3743 }
3744 }
3745
3746 /**
3747 * Dismisses Pip
3748 * @param animate True if the dismissal should be animated.
3749 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3750 * default animation duration should be used.
3751 */
3752 @Override
3753 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003754 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 final long ident = Binder.clearCallingIdentity();
3756 try {
3757 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003758 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003759 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003760 if (stack == null) {
3761 Slog.w(TAG, "dismissPip: pinned stack not found.");
3762 return;
3763 }
3764 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3765 throw new IllegalArgumentException("Stack: " + stack
3766 + " doesn't support animated resize.");
3767 }
3768 if (animate) {
3769 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3770 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3771 } else {
3772 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3773 }
3774 }
3775 } finally {
3776 Binder.restoreCallingIdentity(ident);
3777 }
3778 }
3779
3780 @Override
3781 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003782 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 synchronized (mGlobalLock) {
3784 mSuppressResizeConfigChanges = suppress;
3785 }
3786 }
3787
3788 /**
3789 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3790 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3791 * activity and clearing the task at the same time.
3792 */
3793 @Override
3794 // TODO: API should just be about changing windowing modes...
3795 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003796 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003797 "moveTasksToFullscreenStack()");
3798 synchronized (mGlobalLock) {
3799 final long origId = Binder.clearCallingIdentity();
3800 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003801 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003802 if (stack != null){
3803 if (!stack.isActivityTypeStandardOrUndefined()) {
3804 throw new IllegalArgumentException(
3805 "You can't move tasks from non-standard stacks.");
3806 }
3807 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3808 }
3809 } finally {
3810 Binder.restoreCallingIdentity(origId);
3811 }
3812 }
3813 }
3814
3815 /**
3816 * Moves the top activity in the input stackId to the pinned stack.
3817 *
3818 * @param stackId Id of stack to move the top activity to pinned stack.
3819 * @param bounds Bounds to use for pinned stack.
3820 *
3821 * @return True if the top activity of the input stack was successfully moved to the pinned
3822 * stack.
3823 */
3824 @Override
3825 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003826 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827 "moveTopActivityToPinnedStack()");
3828 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003829 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3831 + "Device doesn't support picture-in-picture mode");
3832 }
3833
3834 long ident = Binder.clearCallingIdentity();
3835 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003836 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 } finally {
3838 Binder.restoreCallingIdentity(ident);
3839 }
3840 }
3841 }
3842
3843 @Override
3844 public boolean isInMultiWindowMode(IBinder token) {
3845 final long origId = Binder.clearCallingIdentity();
3846 try {
3847 synchronized (mGlobalLock) {
3848 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3849 if (r == null) {
3850 return false;
3851 }
3852 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3853 return r.inMultiWindowMode();
3854 }
3855 } finally {
3856 Binder.restoreCallingIdentity(origId);
3857 }
3858 }
3859
3860 @Override
3861 public boolean isInPictureInPictureMode(IBinder token) {
3862 final long origId = Binder.clearCallingIdentity();
3863 try {
3864 synchronized (mGlobalLock) {
3865 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3866 }
3867 } finally {
3868 Binder.restoreCallingIdentity(origId);
3869 }
3870 }
3871
3872 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003873 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3874 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875 return false;
3876 }
3877
3878 // If we are animating to fullscreen then we have already dispatched the PIP mode
3879 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003880 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3881 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 }
3883
3884 @Override
3885 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3886 final long origId = Binder.clearCallingIdentity();
3887 try {
3888 synchronized (mGlobalLock) {
3889 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3890 "enterPictureInPictureMode", token, params);
3891
3892 // If the activity is already in picture in picture mode, then just return early
3893 if (isInPictureInPictureMode(r)) {
3894 return true;
3895 }
3896
3897 // Activity supports picture-in-picture, now check that we can enter PiP at this
3898 // point, if it is
3899 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3900 false /* beforeStopping */)) {
3901 return false;
3902 }
3903
3904 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003905 synchronized (mGlobalLock) {
3906 // Only update the saved args from the args that are set
3907 r.pictureInPictureArgs.copyOnlySet(params);
3908 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3909 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3910 // Adjust the source bounds by the insets for the transition down
3911 final Rect sourceBounds = new Rect(
3912 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003913 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003914 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003915 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003916 stack.setPictureInPictureAspectRatio(aspectRatio);
3917 stack.setPictureInPictureActions(actions);
3918 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3919 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3920 logPictureInPictureArgs(params);
3921 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 };
3923
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003924 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 // If the keyguard is showing or occluded, then try and dismiss it before
3926 // entering picture-in-picture (this will prompt the user to authenticate if the
3927 // device is currently locked).
3928 dismissKeyguard(token, new KeyguardDismissCallback() {
3929 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003930 public void onDismissSucceeded() {
3931 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 }
3933 }, null /* message */);
3934 } else {
3935 // Enter picture in picture immediately otherwise
3936 enterPipRunnable.run();
3937 }
3938 return true;
3939 }
3940 } finally {
3941 Binder.restoreCallingIdentity(origId);
3942 }
3943 }
3944
3945 @Override
3946 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3947 final long origId = Binder.clearCallingIdentity();
3948 try {
3949 synchronized (mGlobalLock) {
3950 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3951 "setPictureInPictureParams", token, params);
3952
3953 // Only update the saved args from the args that are set
3954 r.pictureInPictureArgs.copyOnlySet(params);
3955 if (r.inPinnedWindowingMode()) {
3956 // If the activity is already in picture-in-picture, update the pinned stack now
3957 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3958 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003959 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 if (!stack.isAnimatingBoundsToFullscreen()) {
3961 stack.setPictureInPictureAspectRatio(
3962 r.pictureInPictureArgs.getAspectRatio());
3963 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3964 }
3965 }
3966 logPictureInPictureArgs(params);
3967 }
3968 } finally {
3969 Binder.restoreCallingIdentity(origId);
3970 }
3971 }
3972
3973 @Override
3974 public int getMaxNumPictureInPictureActions(IBinder token) {
3975 // Currently, this is a static constant, but later, we may change this to be dependent on
3976 // the context of the activity
3977 return 3;
3978 }
3979
3980 private void logPictureInPictureArgs(PictureInPictureParams params) {
3981 if (params.hasSetActions()) {
3982 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3983 params.getActions().size());
3984 }
3985 if (params.hasSetAspectRatio()) {
3986 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3987 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3988 MetricsLogger.action(lm);
3989 }
3990 }
3991
3992 /**
3993 * Checks the state of the system and the activity associated with the given {@param token} to
3994 * verify that picture-in-picture is supported for that activity.
3995 *
3996 * @return the activity record for the given {@param token} if all the checks pass.
3997 */
3998 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3999 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 throw new IllegalStateException(caller
4002 + ": Device doesn't support picture-in-picture mode.");
4003 }
4004
4005 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4006 if (r == null) {
4007 throw new IllegalStateException(caller
4008 + ": Can't find activity for token=" + token);
4009 }
4010
4011 if (!r.supportsPictureInPicture()) {
4012 throw new IllegalStateException(caller
4013 + ": Current activity does not support picture-in-picture.");
4014 }
4015
4016 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004017 && !mWindowManager.isValidPictureInPictureAspectRatio(
4018 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 final float minAspectRatio = mContext.getResources().getFloat(
4020 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4021 final float maxAspectRatio = mContext.getResources().getFloat(
4022 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4023 throw new IllegalArgumentException(String.format(caller
4024 + ": Aspect ratio is too extreme (must be between %f and %f).",
4025 minAspectRatio, maxAspectRatio));
4026 }
4027
4028 // Truncate the number of actions if necessary
4029 params.truncateActions(getMaxNumPictureInPictureActions(token));
4030
4031 return r;
4032 }
4033
4034 @Override
4035 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004036 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 synchronized (mGlobalLock) {
4038 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4039 if (r == null) {
4040 throw new IllegalArgumentException("Activity does not exist; token="
4041 + activityToken);
4042 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004043 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 }
4045 }
4046
4047 @Override
4048 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4049 Rect tempDockedTaskInsetBounds,
4050 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004051 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 long ident = Binder.clearCallingIdentity();
4053 try {
4054 synchronized (mGlobalLock) {
4055 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4056 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4057 PRESERVE_WINDOWS);
4058 }
4059 } finally {
4060 Binder.restoreCallingIdentity(ident);
4061 }
4062 }
4063
4064 @Override
4065 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004066 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 final long ident = Binder.clearCallingIdentity();
4068 try {
4069 synchronized (mGlobalLock) {
4070 mStackSupervisor.setSplitScreenResizing(resizing);
4071 }
4072 } finally {
4073 Binder.restoreCallingIdentity(ident);
4074 }
4075 }
4076
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004077 /**
4078 * Check that we have the features required for VR-related API calls, and throw an exception if
4079 * not.
4080 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004081 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004082 if (!mContext.getPackageManager().hasSystemFeature(
4083 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4084 throw new UnsupportedOperationException("VR mode not supported on this device!");
4085 }
4086 }
4087
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 @Override
4089 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004090 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091
4092 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4093
4094 ActivityRecord r;
4095 synchronized (mGlobalLock) {
4096 r = ActivityRecord.isInStackLocked(token);
4097 }
4098
4099 if (r == null) {
4100 throw new IllegalArgumentException();
4101 }
4102
4103 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004104 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004105 VrManagerInternal.NO_ERROR) {
4106 return err;
4107 }
4108
4109 // Clear the binder calling uid since this path may call moveToTask().
4110 final long callingId = Binder.clearCallingIdentity();
4111 try {
4112 synchronized (mGlobalLock) {
4113 r.requestedVrComponent = (enabled) ? packageName : null;
4114
4115 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004116 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004117 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 }
4119 return 0;
4120 }
4121 } finally {
4122 Binder.restoreCallingIdentity(callingId);
4123 }
4124 }
4125
4126 @Override
4127 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4128 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4129 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004130 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004131 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4132 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4133 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004134 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004135 || activity.voiceSession != null) {
4136 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4137 return;
4138 }
4139 if (activity.pendingVoiceInteractionStart) {
4140 Slog.w(TAG, "Pending start of voice interaction already.");
4141 return;
4142 }
4143 activity.pendingVoiceInteractionStart = true;
4144 }
4145 LocalServices.getService(VoiceInteractionManagerInternal.class)
4146 .startLocalVoiceInteraction(callingActivity, options);
4147 }
4148
4149 @Override
4150 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4151 LocalServices.getService(VoiceInteractionManagerInternal.class)
4152 .stopLocalVoiceInteraction(callingActivity);
4153 }
4154
4155 @Override
4156 public boolean supportsLocalVoiceInteraction() {
4157 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4158 .supportsLocalVoiceInteraction();
4159 }
4160
4161 /** Notifies all listeners when the pinned stack animation starts. */
4162 @Override
4163 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004164 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 }
4166
4167 /** Notifies all listeners when the pinned stack animation ends. */
4168 @Override
4169 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004170 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004171 }
4172
4173 @Override
4174 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004175 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 final long ident = Binder.clearCallingIdentity();
4177 try {
4178 synchronized (mGlobalLock) {
4179 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4180 }
4181 } finally {
4182 Binder.restoreCallingIdentity(ident);
4183 }
4184 }
4185
4186 @Override
4187 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189
4190 synchronized (mGlobalLock) {
4191 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004192 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 // Call might come when display is not yet added or has already been removed.
4194 if (DEBUG_CONFIGURATION) {
4195 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4196 + displayId);
4197 }
4198 return false;
4199 }
4200
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004201 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004203 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204 }
4205
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004207 final Message msg = PooledLambda.obtainMessage(
4208 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4209 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 }
4211
4212 final long origId = Binder.clearCallingIdentity();
4213 try {
4214 if (values != null) {
4215 Settings.System.clearConfiguration(values);
4216 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4219 return mTmpUpdateConfigurationResult.changes != 0;
4220 } finally {
4221 Binder.restoreCallingIdentity(origId);
4222 }
4223 }
4224 }
4225
4226 @Override
4227 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004228 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229
4230 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004231 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004232 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 }
4235
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004237 final Message msg = PooledLambda.obtainMessage(
4238 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4239 DEFAULT_DISPLAY);
4240 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 }
4242
4243 final long origId = Binder.clearCallingIdentity();
4244 try {
4245 if (values != null) {
4246 Settings.System.clearConfiguration(values);
4247 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004248 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 UserHandle.USER_NULL, false /* deferResume */,
4250 mTmpUpdateConfigurationResult);
4251 return mTmpUpdateConfigurationResult.changes != 0;
4252 } finally {
4253 Binder.restoreCallingIdentity(origId);
4254 }
4255 }
4256 }
4257
4258 @Override
4259 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4260 CharSequence message) {
4261 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4264 }
4265 final long callingId = Binder.clearCallingIdentity();
4266 try {
4267 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004268 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 }
4270 } finally {
4271 Binder.restoreCallingIdentity(callingId);
4272 }
4273 }
4274
4275 @Override
4276 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004277 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004278 "cancelTaskWindowTransition()");
4279 final long ident = Binder.clearCallingIdentity();
4280 try {
4281 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004282 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004283 MATCH_TASK_IN_STACKS_ONLY);
4284 if (task == null) {
4285 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4286 return;
4287 }
4288 task.cancelWindowTransition();
4289 }
4290 } finally {
4291 Binder.restoreCallingIdentity(ident);
4292 }
4293 }
4294
4295 @Override
4296 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 final long ident = Binder.clearCallingIdentity();
4299 try {
4300 final TaskRecord task;
4301 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004302 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4304 if (task == null) {
4305 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4306 return null;
4307 }
4308 }
4309 // Don't call this while holding the lock as this operation might hit the disk.
4310 return task.getSnapshot(reducedResolution);
4311 } finally {
4312 Binder.restoreCallingIdentity(ident);
4313 }
4314 }
4315
4316 @Override
4317 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4318 synchronized (mGlobalLock) {
4319 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4320 if (r == null) {
4321 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4322 + token);
4323 return;
4324 }
4325 final long origId = Binder.clearCallingIdentity();
4326 try {
4327 r.setDisablePreviewScreenshots(disable);
4328 } finally {
4329 Binder.restoreCallingIdentity(origId);
4330 }
4331 }
4332 }
4333
4334 /** Return the user id of the last resumed activity. */
4335 @Override
4336 public @UserIdInt
4337 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004338 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4340 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004341 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004342 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004344 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 }
4346 }
4347
4348 @Override
4349 public void updateLockTaskFeatures(int userId, int flags) {
4350 final int callingUid = Binder.getCallingUid();
4351 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004352 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004353 "updateLockTaskFeatures()");
4354 }
4355 synchronized (mGlobalLock) {
4356 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4357 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004358 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 }
4360 }
4361
4362 @Override
4363 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4364 synchronized (mGlobalLock) {
4365 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4366 if (r == null) {
4367 return;
4368 }
4369 final long origId = Binder.clearCallingIdentity();
4370 try {
4371 r.setShowWhenLocked(showWhenLocked);
4372 } finally {
4373 Binder.restoreCallingIdentity(origId);
4374 }
4375 }
4376 }
4377
4378 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004379 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4380 synchronized (mGlobalLock) {
4381 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4382 if (r == null) {
4383 return;
4384 }
4385 final long origId = Binder.clearCallingIdentity();
4386 try {
4387 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4388 } finally {
4389 Binder.restoreCallingIdentity(origId);
4390 }
4391 }
4392 }
4393
4394 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4396 synchronized (mGlobalLock) {
4397 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4398 if (r == null) {
4399 return;
4400 }
4401 final long origId = Binder.clearCallingIdentity();
4402 try {
4403 r.setTurnScreenOn(turnScreenOn);
4404 } finally {
4405 Binder.restoreCallingIdentity(origId);
4406 }
4407 }
4408 }
4409
4410 @Override
4411 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 "registerRemoteAnimations");
4414 definition.setCallingPid(Binder.getCallingPid());
4415 synchronized (mGlobalLock) {
4416 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4417 if (r == null) {
4418 return;
4419 }
4420 final long origId = Binder.clearCallingIdentity();
4421 try {
4422 r.registerRemoteAnimations(definition);
4423 } finally {
4424 Binder.restoreCallingIdentity(origId);
4425 }
4426 }
4427 }
4428
4429 @Override
4430 public void registerRemoteAnimationForNextActivityStart(String packageName,
4431 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 "registerRemoteAnimationForNextActivityStart");
4434 adapter.setCallingPid(Binder.getCallingPid());
4435 synchronized (mGlobalLock) {
4436 final long origId = Binder.clearCallingIdentity();
4437 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004438 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 packageName, adapter);
4440 } finally {
4441 Binder.restoreCallingIdentity(origId);
4442 }
4443 }
4444 }
4445
Evan Rosky966759f2019-01-15 10:33:58 -08004446 @Override
4447 public void registerRemoteAnimationsForDisplay(int displayId,
4448 RemoteAnimationDefinition definition) {
4449 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4450 "registerRemoteAnimations");
4451 definition.setCallingPid(Binder.getCallingPid());
4452 synchronized (mGlobalLock) {
4453 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4454 if (display == null) {
4455 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4456 return;
4457 }
4458 final long origId = Binder.clearCallingIdentity();
4459 try {
4460 display.mDisplayContent.registerRemoteAnimations(definition);
4461 } finally {
4462 Binder.restoreCallingIdentity(origId);
4463 }
4464 }
4465 }
4466
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4468 @Override
4469 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4470 synchronized (mGlobalLock) {
4471 final long origId = Binder.clearCallingIdentity();
4472 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004473 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 } finally {
4475 Binder.restoreCallingIdentity(origId);
4476 }
4477 }
4478 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004479
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004480 @Override
4481 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004482 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004483 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004484 final int pid = Binder.getCallingPid();
4485 final WindowProcessController wpc = mPidMap.get(pid);
4486 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004487 }
4488 }
4489
4490 @Override
4491 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004492 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004493 != PERMISSION_GRANTED) {
4494 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4495 + Binder.getCallingPid()
4496 + ", uid=" + Binder.getCallingUid()
4497 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4498 Slog.w(TAG, msg);
4499 throw new SecurityException(msg);
4500 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004501 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004502 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004503 final int pid = Binder.getCallingPid();
4504 final WindowProcessController proc = mPidMap.get(pid);
4505 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004506 }
4507 }
4508
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004509 @Override
4510 public void stopAppSwitches() {
4511 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4512 synchronized (mGlobalLock) {
4513 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4514 mDidAppSwitch = false;
4515 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4516 }
4517 }
4518
4519 @Override
4520 public void resumeAppSwitches() {
4521 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4522 synchronized (mGlobalLock) {
4523 // Note that we don't execute any pending app switches... we will
4524 // let those wait until either the timeout, or the next start
4525 // activity request.
4526 mAppSwitchesAllowedTime = 0;
4527 }
4528 }
4529
4530 void onStartActivitySetDidAppSwitch() {
4531 if (mDidAppSwitch) {
4532 // This is the second allowed switch since we stopped switches, so now just generally
4533 // allow switches. Use case:
4534 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4535 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4536 // anyone to switch again).
4537 mAppSwitchesAllowedTime = 0;
4538 } else {
4539 mDidAppSwitch = true;
4540 }
4541 }
4542
4543 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004544 boolean shouldDisableNonVrUiLocked() {
4545 return mVrController.shouldDisableNonVrUiLocked();
4546 }
4547
Wale Ogunwale53783742018-09-16 10:21:51 -07004548 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004549 // VR apps are expected to run in a main display. If an app is turning on VR for
4550 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4551 // fullscreen stack before enabling VR Mode.
4552 // TODO: The goal of this code is to keep the VR app on the main display. When the
4553 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4554 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4555 // option would be a better choice here.
4556 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4557 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4558 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004559 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004560 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004561 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004562 }
4563 mH.post(() -> {
4564 if (!mVrController.onVrModeChanged(r)) {
4565 return;
4566 }
4567 synchronized (mGlobalLock) {
4568 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4569 mWindowManager.disableNonVrUi(disableNonVrUi);
4570 if (disableNonVrUi) {
4571 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4572 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004573 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004574 }
4575 }
4576 });
4577 }
4578
Wale Ogunwale53783742018-09-16 10:21:51 -07004579 @Override
4580 public int getPackageScreenCompatMode(String packageName) {
4581 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4582 synchronized (mGlobalLock) {
4583 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4584 }
4585 }
4586
4587 @Override
4588 public void setPackageScreenCompatMode(String packageName, int mode) {
4589 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4590 "setPackageScreenCompatMode");
4591 synchronized (mGlobalLock) {
4592 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4593 }
4594 }
4595
4596 @Override
4597 public boolean getPackageAskScreenCompat(String packageName) {
4598 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4599 synchronized (mGlobalLock) {
4600 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4601 }
4602 }
4603
4604 @Override
4605 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4606 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4607 "setPackageAskScreenCompat");
4608 synchronized (mGlobalLock) {
4609 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4610 }
4611 }
4612
Wale Ogunwale64258362018-10-16 15:13:37 -07004613 public static String relaunchReasonToString(int relaunchReason) {
4614 switch (relaunchReason) {
4615 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4616 return "window_resize";
4617 case RELAUNCH_REASON_FREE_RESIZE:
4618 return "free_resize";
4619 default:
4620 return null;
4621 }
4622 }
4623
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004624 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004625 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004626 }
4627
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004628 /** Pokes the task persister. */
4629 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4630 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4631 }
4632
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004633 boolean isKeyguardLocked() {
4634 return mKeyguardController.isKeyguardLocked();
4635 }
4636
Garfield Tan01548632018-11-27 10:15:48 -08004637 /**
4638 * Clears launch params for the given package.
4639 * @param packageNames the names of the packages of which the launch params are to be cleared
4640 */
4641 @Override
4642 public void clearLaunchParamsForPackages(List<String> packageNames) {
4643 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4644 "clearLaunchParamsForPackages");
4645 synchronized (mGlobalLock) {
4646 for (int i = 0; i < packageNames.size(); ++i) {
4647 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4648 }
4649 }
4650 }
4651
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004652 /**
4653 * Makes the display with the given id a single task instance display. I.e the display can only
4654 * contain one task.
4655 */
4656 @Override
4657 public void setDisplayToSingleTaskInstance(int displayId) {
4658 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4659 "setDisplayToSingleTaskInstance");
4660 final long origId = Binder.clearCallingIdentity();
4661 try {
4662 final ActivityDisplay display =
4663 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4664 if (display != null) {
4665 display.setDisplayToSingleTaskInstance();
4666 }
4667 } finally {
4668 Binder.restoreCallingIdentity(origId);
4669 }
4670 }
4671
Wale Ogunwale31913b52018-10-13 08:29:31 -07004672 void dumpLastANRLocked(PrintWriter pw) {
4673 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4674 if (mLastANRState == null) {
4675 pw.println(" <no ANR has occurred since boot>");
4676 } else {
4677 pw.println(mLastANRState);
4678 }
4679 }
4680
4681 void dumpLastANRTracesLocked(PrintWriter pw) {
4682 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4683
4684 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4685 if (ArrayUtils.isEmpty(files)) {
4686 pw.println(" <no ANR has occurred since boot>");
4687 return;
4688 }
4689 // Find the latest file.
4690 File latest = null;
4691 for (File f : files) {
4692 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4693 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004694 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004695 }
4696 pw.print("File: ");
4697 pw.print(latest.getName());
4698 pw.println();
4699 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4700 String line;
4701 while ((line = in.readLine()) != null) {
4702 pw.println(line);
4703 }
4704 } catch (IOException e) {
4705 pw.print("Unable to read: ");
4706 pw.print(e);
4707 pw.println();
4708 }
4709 }
4710
4711 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4712 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4713 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4714 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4715 }
4716
4717 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4718 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4719 pw.println(header);
4720
Wale Ogunwaled32da472018-11-16 07:19:28 -08004721 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004722 dumpPackage);
4723 boolean needSep = printedAnything;
4724
4725 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004726 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004727 " ResumedActivity: ");
4728 if (printed) {
4729 printedAnything = true;
4730 needSep = false;
4731 }
4732
4733 if (dumpPackage == null) {
4734 if (needSep) {
4735 pw.println();
4736 }
4737 printedAnything = true;
4738 mStackSupervisor.dump(pw, " ");
4739 }
4740
4741 if (!printedAnything) {
4742 pw.println(" (nothing)");
4743 }
4744 }
4745
4746 void dumpActivityContainersLocked(PrintWriter pw) {
4747 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004748 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004749 pw.println(" ");
4750 }
4751
4752 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4753 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4754 getActivityStartController().dump(pw, "", dumpPackage);
4755 }
4756
4757 /**
4758 * There are three things that cmd can be:
4759 * - a flattened component name that matches an existing activity
4760 * - the cmd arg isn't the flattened component name of an existing activity:
4761 * dump all activity whose component contains the cmd as a substring
4762 * - A hex number of the ActivityRecord object instance.
4763 *
4764 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4765 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4766 */
4767 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4768 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4769 ArrayList<ActivityRecord> activities;
4770
4771 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004772 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004773 dumpFocusedStackOnly);
4774 }
4775
4776 if (activities.size() <= 0) {
4777 return false;
4778 }
4779
4780 String[] newArgs = new String[args.length - opti];
4781 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4782
4783 TaskRecord lastTask = null;
4784 boolean needSep = false;
4785 for (int i = activities.size() - 1; i >= 0; i--) {
4786 ActivityRecord r = activities.get(i);
4787 if (needSep) {
4788 pw.println();
4789 }
4790 needSep = true;
4791 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004792 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004793 if (lastTask != task) {
4794 lastTask = task;
4795 pw.print("TASK "); pw.print(lastTask.affinity);
4796 pw.print(" id="); pw.print(lastTask.taskId);
4797 pw.print(" userId="); pw.println(lastTask.userId);
4798 if (dumpAll) {
4799 lastTask.dump(pw, " ");
4800 }
4801 }
4802 }
4803 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4804 }
4805 return true;
4806 }
4807
4808 /**
4809 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4810 * there is a thread associated with the activity.
4811 */
4812 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4813 final ActivityRecord r, String[] args, boolean dumpAll) {
4814 String innerPrefix = prefix + " ";
4815 synchronized (mGlobalLock) {
4816 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4817 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4818 pw.print(" pid=");
4819 if (r.hasProcess()) pw.println(r.app.getPid());
4820 else pw.println("(not running)");
4821 if (dumpAll) {
4822 r.dump(pw, innerPrefix);
4823 }
4824 }
4825 if (r.attachedToProcess()) {
4826 // flush anything that is already in the PrintWriter since the thread is going
4827 // to write to the file descriptor directly
4828 pw.flush();
4829 try {
4830 TransferPipe tp = new TransferPipe();
4831 try {
4832 r.app.getThread().dumpActivity(tp.getWriteFd(),
4833 r.appToken, innerPrefix, args);
4834 tp.go(fd);
4835 } finally {
4836 tp.kill();
4837 }
4838 } catch (IOException e) {
4839 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4840 } catch (RemoteException e) {
4841 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4842 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004843 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004844 }
4845
sanryhuang498e77e2018-12-06 14:57:01 +08004846 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4847 boolean testPssMode) {
4848 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4849 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4850 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004851 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004852 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4853 st.toString());
4854 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004855 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4856 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4857 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004858 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4859 testPssMode);
4860 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004861 }
4862
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004863 int getCurrentUserId() {
4864 return mAmInternal.getCurrentUserId();
4865 }
4866
4867 private void enforceNotIsolatedCaller(String caller) {
4868 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4869 throw new SecurityException("Isolated process not allowed to call " + caller);
4870 }
4871 }
4872
Wale Ogunwalef6733932018-06-27 05:14:34 -07004873 public Configuration getConfiguration() {
4874 Configuration ci;
4875 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004876 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004877 ci.userSetLocale = false;
4878 }
4879 return ci;
4880 }
4881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004882 /**
4883 * Current global configuration information. Contains general settings for the entire system,
4884 * also corresponds to the merged configuration of the default display.
4885 */
4886 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004887 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004888 }
4889
4890 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4891 boolean initLocale) {
4892 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4893 }
4894
4895 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4896 boolean initLocale, boolean deferResume) {
4897 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4898 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4899 UserHandle.USER_NULL, deferResume);
4900 }
4901
Wale Ogunwale59507092018-10-29 09:00:30 -07004902 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004903 final long origId = Binder.clearCallingIdentity();
4904 try {
4905 synchronized (mGlobalLock) {
4906 updateConfigurationLocked(values, null, false, true, userId,
4907 false /* deferResume */);
4908 }
4909 } finally {
4910 Binder.restoreCallingIdentity(origId);
4911 }
4912 }
4913
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004914 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4915 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4916 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4917 deferResume, null /* result */);
4918 }
4919
4920 /**
4921 * Do either or both things: (1) change the current configuration, and (2)
4922 * make sure the given activity is running with the (now) current
4923 * configuration. Returns true if the activity has been left running, or
4924 * false if <var>starting</var> is being destroyed to match the new
4925 * configuration.
4926 *
4927 * @param userId is only used when persistent parameter is set to true to persist configuration
4928 * for that particular user
4929 */
4930 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4931 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4932 ActivityTaskManagerService.UpdateConfigurationResult result) {
4933 int changes = 0;
4934 boolean kept = true;
4935
4936 if (mWindowManager != null) {
4937 mWindowManager.deferSurfaceLayout();
4938 }
4939 try {
4940 if (values != null) {
4941 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4942 deferResume);
4943 }
4944
4945 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4946 } finally {
4947 if (mWindowManager != null) {
4948 mWindowManager.continueSurfaceLayout();
4949 }
4950 }
4951
4952 if (result != null) {
4953 result.changes = changes;
4954 result.activityRelaunched = !kept;
4955 }
4956 return kept;
4957 }
4958
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004959 /** Update default (global) configuration and notify listeners about changes. */
4960 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4961 boolean persistent, int userId, boolean deferResume) {
4962 mTempConfig.setTo(getGlobalConfiguration());
4963 final int changes = mTempConfig.updateFrom(values);
4964 if (changes == 0) {
4965 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4966 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4967 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4968 // (even if there are no actual changes) to unfreeze the window.
4969 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4970 return 0;
4971 }
4972
4973 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4974 "Updating global configuration to: " + values);
4975
4976 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4977 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4978 values.colorMode,
4979 values.densityDpi,
4980 values.fontScale,
4981 values.hardKeyboardHidden,
4982 values.keyboard,
4983 values.keyboardHidden,
4984 values.mcc,
4985 values.mnc,
4986 values.navigation,
4987 values.navigationHidden,
4988 values.orientation,
4989 values.screenHeightDp,
4990 values.screenLayout,
4991 values.screenWidthDp,
4992 values.smallestScreenWidthDp,
4993 values.touchscreen,
4994 values.uiMode);
4995
4996
4997 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4998 final LocaleList locales = values.getLocales();
4999 int bestLocaleIndex = 0;
5000 if (locales.size() > 1) {
5001 if (mSupportedSystemLocales == null) {
5002 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5003 }
5004 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5005 }
5006 SystemProperties.set("persist.sys.locale",
5007 locales.get(bestLocaleIndex).toLanguageTag());
5008 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005009
5010 final Message m = PooledLambda.obtainMessage(
5011 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5012 locales.get(bestLocaleIndex));
5013 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005014 }
5015
Yunfan Chen75157d72018-07-27 14:47:21 +09005016 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005017
5018 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005019 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005020
5021 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5022 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005023 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005024
5025 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005026 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005027
5028 AttributeCache ac = AttributeCache.instance();
5029 if (ac != null) {
5030 ac.updateConfiguration(mTempConfig);
5031 }
5032
5033 // Make sure all resources in our process are updated right now, so that anyone who is going
5034 // to retrieve resource values after we return will be sure to get the new ones. This is
5035 // especially important during boot, where the first config change needs to guarantee all
5036 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005037 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005038
5039 // We need another copy of global config because we're scheduling some calls instead of
5040 // running them in place. We need to be sure that object we send will be handled unchanged.
5041 final Configuration configCopy = new Configuration(mTempConfig);
5042 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005043 final Message msg = PooledLambda.obtainMessage(
5044 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5045 this, userId, configCopy);
5046 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005047 }
5048
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005049 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005050 final int pid = mPidMap.keyAt(i);
5051 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005052 if (DEBUG_CONFIGURATION) {
5053 Slog.v(TAG_CONFIGURATION, "Update process config of "
5054 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005055 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005056 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005057 }
5058
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005059 final Message msg = PooledLambda.obtainMessage(
5060 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5061 mAmInternal, changes, initLocale);
5062 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005063
5064 // Override configuration of the default display duplicates global config, so we need to
5065 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005066 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005067 DEFAULT_DISPLAY);
5068
5069 return changes;
5070 }
5071
5072 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5073 boolean deferResume, int displayId) {
5074 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5075 displayId, null /* result */);
5076 }
5077
5078 /**
5079 * Updates override configuration specific for the selected display. If no config is provided,
5080 * new one will be computed in WM based on current display info.
5081 */
5082 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5083 ActivityRecord starting, boolean deferResume, int displayId,
5084 ActivityTaskManagerService.UpdateConfigurationResult result) {
5085 int changes = 0;
5086 boolean kept = true;
5087
5088 if (mWindowManager != null) {
5089 mWindowManager.deferSurfaceLayout();
5090 }
5091 try {
5092 if (values != null) {
5093 if (displayId == DEFAULT_DISPLAY) {
5094 // Override configuration of the default display duplicates global config, so
5095 // we're calling global config update instead for default display. It will also
5096 // apply the correct override config.
5097 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5098 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5099 } else {
5100 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5101 }
5102 }
5103
5104 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5105 } finally {
5106 if (mWindowManager != null) {
5107 mWindowManager.continueSurfaceLayout();
5108 }
5109 }
5110
5111 if (result != null) {
5112 result.changes = changes;
5113 result.activityRelaunched = !kept;
5114 }
5115 return kept;
5116 }
5117
5118 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5119 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005120 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005121 final int changes = mTempConfig.updateFrom(values);
5122 if (changes != 0) {
5123 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5124 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005125 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005126
5127 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5128 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005129 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130
Wale Ogunwale5c918702018-10-18 11:06:33 -07005131 // Post message to start process to avoid possible deadlock of calling into AMS with
5132 // the ATMS lock held.
5133 final Message msg = PooledLambda.obtainMessage(
5134 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5135 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5136 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 }
5138 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 return changes;
5140 }
5141
Wale Ogunwalef6733932018-06-27 05:14:34 -07005142 private void updateEventDispatchingLocked(boolean booted) {
5143 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5144 }
5145
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005146 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5147 final ContentResolver resolver = mContext.getContentResolver();
5148 Settings.System.putConfigurationForUser(resolver, config, userId);
5149 }
5150
5151 private void sendLocaleToMountDaemonMsg(Locale l) {
5152 try {
5153 IBinder service = ServiceManager.getService("mount");
5154 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5155 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5156 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5157 } catch (RemoteException e) {
5158 Log.e(TAG, "Error storing locale for decryption UI", e);
5159 }
5160 }
5161
Alison Cichowlas3e340502018-08-07 17:15:01 -04005162 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5163 mStartActivitySources.remove(permissionToken);
5164 mExpiredStartAsCallerTokens.add(permissionToken);
5165 }
5166
5167 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5168 mExpiredStartAsCallerTokens.remove(permissionToken);
5169 }
5170
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005171 boolean isActivityStartsLoggingEnabled() {
5172 return mAmInternal.isActivityStartsLoggingEnabled();
5173 }
5174
Michal Karpinski8596ded2018-11-14 14:43:48 +00005175 boolean isBackgroundActivityStartsEnabled() {
5176 return mAmInternal.isBackgroundActivityStartsEnabled();
5177 }
5178
Wale Ogunwalef6733932018-06-27 05:14:34 -07005179 void enableScreenAfterBoot(boolean booted) {
5180 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5181 SystemClock.uptimeMillis());
5182 mWindowManager.enableScreenAfterBoot();
5183
5184 synchronized (mGlobalLock) {
5185 updateEventDispatchingLocked(booted);
5186 }
5187 }
5188
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005189 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5190 if (r == null || !r.hasProcess()) {
5191 return KEY_DISPATCHING_TIMEOUT_MS;
5192 }
5193 return getInputDispatchingTimeoutLocked(r.app);
5194 }
5195
5196 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005197 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005198 }
5199
Wale Ogunwalef6733932018-06-27 05:14:34 -07005200 /**
5201 * Decide based on the configuration whether we should show the ANR,
5202 * crash, etc dialogs. The idea is that if there is no affordance to
5203 * press the on-screen buttons, or the user experience would be more
5204 * greatly impacted than the crash itself, we shouldn't show the dialog.
5205 *
5206 * A thought: SystemUI might also want to get told about this, the Power
5207 * dialog / global actions also might want different behaviors.
5208 */
5209 private void updateShouldShowDialogsLocked(Configuration config) {
5210 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5211 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5212 && config.navigation == Configuration.NAVIGATION_NONAV);
5213 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5214 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5215 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5216 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5217 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5218 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5219 HIDE_ERROR_DIALOGS, 0) != 0;
5220 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5221 }
5222
5223 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5224 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5225 FONT_SCALE, 1.0f, userId);
5226
5227 synchronized (this) {
5228 if (getGlobalConfiguration().fontScale == scaleFactor) {
5229 return;
5230 }
5231
5232 final Configuration configuration
5233 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5234 configuration.fontScale = scaleFactor;
5235 updatePersistentConfiguration(configuration, userId);
5236 }
5237 }
5238
5239 // Actually is sleeping or shutting down or whatever else in the future
5240 // is an inactive state.
5241 boolean isSleepingOrShuttingDownLocked() {
5242 return isSleepingLocked() || mShuttingDown;
5243 }
5244
5245 boolean isSleepingLocked() {
5246 return mSleeping;
5247 }
5248
Riddle Hsu16567132018-08-16 21:37:47 +08005249 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005250 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005251 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005252 if (task.isActivityTypeStandard()) {
5253 if (mCurAppTimeTracker != r.appTimeTracker) {
5254 // We are switching app tracking. Complete the current one.
5255 if (mCurAppTimeTracker != null) {
5256 mCurAppTimeTracker.stop();
5257 mH.obtainMessage(
5258 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005259 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005260 mCurAppTimeTracker = null;
5261 }
5262 if (r.appTimeTracker != null) {
5263 mCurAppTimeTracker = r.appTimeTracker;
5264 startTimeTrackingFocusedActivityLocked();
5265 }
5266 } else {
5267 startTimeTrackingFocusedActivityLocked();
5268 }
5269 } else {
5270 r.appTimeTracker = null;
5271 }
5272 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5273 // TODO: Probably not, because we don't want to resume voice on switching
5274 // back to this activity
5275 if (task.voiceInteractor != null) {
5276 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5277 } else {
5278 finishRunningVoiceLocked();
5279
5280 if (mLastResumedActivity != null) {
5281 final IVoiceInteractionSession session;
5282
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005283 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005284 if (lastResumedActivityTask != null
5285 && lastResumedActivityTask.voiceSession != null) {
5286 session = lastResumedActivityTask.voiceSession;
5287 } else {
5288 session = mLastResumedActivity.voiceSession;
5289 }
5290
5291 if (session != null) {
5292 // We had been in a voice interaction session, but now focused has
5293 // move to something different. Just finish the session, we can't
5294 // return to it and retain the proper state and synchronization with
5295 // the voice interaction service.
5296 finishVoiceTask(session);
5297 }
5298 }
5299 }
5300
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005301 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5302 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005303 }
5304 updateResumedAppTrace(r);
5305 mLastResumedActivity = r;
5306
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005307 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308
5309 applyUpdateLockStateLocked(r);
5310 applyUpdateVrModeLocked(r);
5311
5312 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005313 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005314 r == null ? "NULL" : r.shortComponentName,
5315 reason);
5316 }
5317
5318 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5319 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005320 final ActivityTaskManagerInternal.SleepToken token =
5321 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005322 updateSleepIfNeededLocked();
5323 return token;
5324 }
5325 }
5326
5327 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005328 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005329 final boolean wasSleeping = mSleeping;
5330 boolean updateOomAdj = false;
5331
5332 if (!shouldSleep) {
5333 // If wasSleeping is true, we need to wake up activity manager state from when
5334 // we started sleeping. In either case, we need to apply the sleep tokens, which
5335 // will wake up stacks or put them to sleep as appropriate.
5336 if (wasSleeping) {
5337 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005338 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5339 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005340 startTimeTrackingFocusedActivityLocked();
5341 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5342 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5343 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005344 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005345 if (wasSleeping) {
5346 updateOomAdj = true;
5347 }
5348 } else if (!mSleeping && shouldSleep) {
5349 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005350 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5351 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005352 if (mCurAppTimeTracker != null) {
5353 mCurAppTimeTracker.stop();
5354 }
5355 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5356 mStackSupervisor.goingToSleepLocked();
5357 updateResumedAppTrace(null /* resumed */);
5358 updateOomAdj = true;
5359 }
5360 if (updateOomAdj) {
5361 mH.post(mAmInternal::updateOomAdj);
5362 }
5363 }
5364
5365 void updateOomAdj() {
5366 mH.post(mAmInternal::updateOomAdj);
5367 }
5368
Wale Ogunwale53783742018-09-16 10:21:51 -07005369 void updateCpuStats() {
5370 mH.post(mAmInternal::updateCpuStats);
5371 }
5372
Hui Yu03d12402018-12-06 18:00:37 -08005373 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5374 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005375 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5376 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005377 mH.sendMessage(m);
5378 }
5379
Hui Yu03d12402018-12-06 18:00:37 -08005380 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005381 ComponentName taskRoot = null;
5382 final TaskRecord task = activity.getTaskRecord();
5383 if (task != null) {
5384 final ActivityRecord rootActivity = task.getRootActivity();
5385 if (rootActivity != null) {
5386 taskRoot = rootActivity.mActivityComponent;
5387 }
5388 }
5389
Hui Yu03d12402018-12-06 18:00:37 -08005390 final Message m = PooledLambda.obtainMessage(
5391 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005392 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005393 mH.sendMessage(m);
5394 }
5395
Wale Ogunwale53783742018-09-16 10:21:51 -07005396 void setBooting(boolean booting) {
5397 mAmInternal.setBooting(booting);
5398 }
5399
5400 boolean isBooting() {
5401 return mAmInternal.isBooting();
5402 }
5403
5404 void setBooted(boolean booted) {
5405 mAmInternal.setBooted(booted);
5406 }
5407
5408 boolean isBooted() {
5409 return mAmInternal.isBooted();
5410 }
5411
5412 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5413 mH.post(() -> {
5414 if (finishBooting) {
5415 mAmInternal.finishBooting();
5416 }
5417 if (enableScreen) {
5418 mInternal.enableScreenAfterBoot(isBooted());
5419 }
5420 });
5421 }
5422
5423 void setHeavyWeightProcess(ActivityRecord root) {
5424 mHeavyWeightProcess = root.app;
5425 final Message m = PooledLambda.obtainMessage(
5426 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005427 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005428 mH.sendMessage(m);
5429 }
5430
5431 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5432 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5433 return;
5434 }
5435
5436 mHeavyWeightProcess = null;
5437 final Message m = PooledLambda.obtainMessage(
5438 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5439 proc.mUserId);
5440 mH.sendMessage(m);
5441 }
5442
5443 private void cancelHeavyWeightProcessNotification(int userId) {
5444 final INotificationManager inm = NotificationManager.getService();
5445 if (inm == null) {
5446 return;
5447 }
5448 try {
5449 inm.cancelNotificationWithTag("android", null,
5450 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5451 } catch (RuntimeException e) {
5452 Slog.w(TAG, "Error canceling notification for service", e);
5453 } catch (RemoteException e) {
5454 }
5455
5456 }
5457
5458 private void postHeavyWeightProcessNotification(
5459 WindowProcessController proc, Intent intent, int userId) {
5460 if (proc == null) {
5461 return;
5462 }
5463
5464 final INotificationManager inm = NotificationManager.getService();
5465 if (inm == null) {
5466 return;
5467 }
5468
5469 try {
5470 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5471 String text = mContext.getString(R.string.heavy_weight_notification,
5472 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5473 Notification notification =
5474 new Notification.Builder(context,
5475 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5476 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5477 .setWhen(0)
5478 .setOngoing(true)
5479 .setTicker(text)
5480 .setColor(mContext.getColor(
5481 com.android.internal.R.color.system_notification_accent_color))
5482 .setContentTitle(text)
5483 .setContentText(
5484 mContext.getText(R.string.heavy_weight_notification_detail))
5485 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5486 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5487 new UserHandle(userId)))
5488 .build();
5489 try {
5490 inm.enqueueNotificationWithTag("android", "android", null,
5491 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5492 } catch (RuntimeException e) {
5493 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5494 } catch (RemoteException e) {
5495 }
5496 } catch (PackageManager.NameNotFoundException e) {
5497 Slog.w(TAG, "Unable to create context for heavy notification", e);
5498 }
5499
5500 }
5501
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005502 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5503 IBinder token, String resultWho, int requestCode, Intent[] intents,
5504 String[] resolvedTypes, int flags, Bundle bOptions) {
5505
5506 ActivityRecord activity = null;
5507 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5508 activity = ActivityRecord.isInStackLocked(token);
5509 if (activity == null) {
5510 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5511 return null;
5512 }
5513 if (activity.finishing) {
5514 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5515 return null;
5516 }
5517 }
5518
5519 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5520 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5521 bOptions);
5522 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5523 if (noCreate) {
5524 return rec;
5525 }
5526 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5527 if (activity.pendingResults == null) {
5528 activity.pendingResults = new HashSet<>();
5529 }
5530 activity.pendingResults.add(rec.ref);
5531 }
5532 return rec;
5533 }
5534
Andrii Kulian52d255c2018-07-13 11:32:19 -07005535 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005537 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5539 mCurAppTimeTracker.start(resumedActivity.packageName);
5540 }
5541 }
5542
5543 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5544 if (mTracedResumedActivity != null) {
5545 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5546 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5547 }
5548 if (resumed != null) {
5549 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5550 constructResumedTraceName(resumed.packageName), 0);
5551 }
5552 mTracedResumedActivity = resumed;
5553 }
5554
5555 private String constructResumedTraceName(String packageName) {
5556 return "focused app: " + packageName;
5557 }
5558
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005559 /** Applies latest configuration and/or visibility updates if needed. */
5560 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5561 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005562 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005563 // mainStack is null during startup.
5564 if (mainStack != null) {
5565 if (changes != 0 && starting == null) {
5566 // If the configuration changed, and the caller is not already
5567 // in the process of starting an activity, then find the top
5568 // activity to check if its configuration needs to change.
5569 starting = mainStack.topRunningActivityLocked();
5570 }
5571
5572 if (starting != null) {
5573 kept = starting.ensureActivityConfiguration(changes,
5574 false /* preserveWindow */);
5575 // And we need to make sure at this point that all other activities
5576 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005577 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005578 !PRESERVE_WINDOWS);
5579 }
5580 }
5581
5582 return kept;
5583 }
5584
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005585 void scheduleAppGcsLocked() {
5586 mH.post(() -> mAmInternal.scheduleAppGcs());
5587 }
5588
Wale Ogunwale53783742018-09-16 10:21:51 -07005589 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5590 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5591 }
5592
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005593 /**
5594 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5595 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5596 * on demand.
5597 */
5598 IPackageManager getPackageManager() {
5599 return AppGlobals.getPackageManager();
5600 }
5601
5602 PackageManagerInternal getPackageManagerInternalLocked() {
5603 if (mPmInternal == null) {
5604 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5605 }
5606 return mPmInternal;
5607 }
5608
Wale Ogunwale008163e2018-07-23 23:11:08 -07005609 AppWarnings getAppWarningsLocked() {
5610 return mAppWarnings;
5611 }
5612
Wale Ogunwale214f3482018-10-04 11:00:47 -07005613 Intent getHomeIntent() {
5614 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5615 intent.setComponent(mTopComponent);
5616 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5617 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5618 intent.addCategory(Intent.CATEGORY_HOME);
5619 }
5620 return intent;
5621 }
5622
Chilun2ef71f72018-11-16 17:57:15 +08005623 /**
5624 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5625 * activities.
5626 *
5627 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5628 * component defined in config_secondaryHomeComponent.
5629 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5630 */
5631 Intent getSecondaryHomeIntent(String preferredPackage) {
5632 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5633 if (preferredPackage == null) {
5634 // Using the component stored in config if no package name.
5635 final String secondaryHomeComponent = mContext.getResources().getString(
5636 com.android.internal.R.string.config_secondaryHomeComponent);
5637 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5638 } else {
5639 intent.setPackage(preferredPackage);
5640 }
5641 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5642 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5643 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5644 }
5645 return intent;
5646 }
5647
Wale Ogunwale214f3482018-10-04 11:00:47 -07005648 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5649 if (info == null) return null;
5650 ApplicationInfo newInfo = new ApplicationInfo(info);
5651 newInfo.initForUser(userId);
5652 return newInfo;
5653 }
5654
Wale Ogunwale9c103022018-10-18 07:44:54 -07005655 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005656 if (uid == SYSTEM_UID) {
5657 // The system gets to run in any process. If there are multiple processes with the same
5658 // uid, just pick the first (this should never happen).
5659 final SparseArray<WindowProcessController> procs =
5660 mProcessNames.getMap().get(processName);
5661 if (procs == null) return null;
5662 final int procCount = procs.size();
5663 for (int i = 0; i < procCount; i++) {
5664 final int procUid = procs.keyAt(i);
5665 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5666 // Don't use an app process or different user process for system component.
5667 continue;
5668 }
5669 return procs.valueAt(i);
5670 }
5671 }
5672
5673 return mProcessNames.get(processName, uid);
5674 }
5675
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005676 WindowProcessController getProcessController(IApplicationThread thread) {
5677 if (thread == null) {
5678 return null;
5679 }
5680
5681 final IBinder threadBinder = thread.asBinder();
5682 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5683 for (int i = pmap.size()-1; i >= 0; i--) {
5684 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5685 for (int j = procs.size() - 1; j >= 0; j--) {
5686 final WindowProcessController proc = procs.valueAt(j);
5687 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5688 return proc;
5689 }
5690 }
5691 }
5692
5693 return null;
5694 }
5695
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005696 WindowProcessController getProcessController(int pid, int uid) {
5697 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5698 for (int i = pmap.size()-1; i >= 0; i--) {
5699 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5700 for (int j = procs.size() - 1; j >= 0; j--) {
5701 final WindowProcessController proc = procs.valueAt(j);
5702 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5703 return proc;
5704 }
5705 }
5706 }
5707 return null;
5708 }
5709
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005710 int getUidStateLocked(int uid) {
5711 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5712 }
5713
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005714 boolean isUidForeground(int uid) {
5715 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5716 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5717 }
5718
Michal Karpinski4026cae2019-02-12 11:51:47 +00005719 boolean isDeviceOwner(String packageName) {
5720 if (packageName == null) {
5721 return false;
5722 }
5723 return packageName.equals(mDeviceOwnerPackageName);
5724 }
5725
5726 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5727 mDeviceOwnerPackageName = deviceOwnerPkg;
5728 }
5729
Wale Ogunwale9de19442018-10-18 19:05:03 -07005730 /**
5731 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5732 * the whitelist
5733 */
5734 String getPendingTempWhitelistTagForUidLocked(int uid) {
5735 return mPendingTempWhitelist.get(uid);
5736 }
5737
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005738 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5739 if (true || Build.IS_USER) {
5740 return;
5741 }
5742
5743 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5744 StrictMode.allowThreadDiskWrites();
5745 try {
5746 File tracesDir = new File("/data/anr");
5747 File tracesFile = null;
5748 try {
5749 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5750
5751 StringBuilder sb = new StringBuilder();
5752 Time tobj = new Time();
5753 tobj.set(System.currentTimeMillis());
5754 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5755 sb.append(": ");
5756 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5757 sb.append(" since ");
5758 sb.append(msg);
5759 FileOutputStream fos = new FileOutputStream(tracesFile);
5760 fos.write(sb.toString().getBytes());
5761 if (app == null) {
5762 fos.write("\n*** No application process!".getBytes());
5763 }
5764 fos.close();
5765 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5766 } catch (IOException e) {
5767 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5768 return;
5769 }
5770
5771 if (app != null && app.getPid() > 0) {
5772 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5773 firstPids.add(app.getPid());
5774 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5775 }
5776
5777 File lastTracesFile = null;
5778 File curTracesFile = null;
5779 for (int i=9; i>=0; i--) {
5780 String name = String.format(Locale.US, "slow%02d.txt", i);
5781 curTracesFile = new File(tracesDir, name);
5782 if (curTracesFile.exists()) {
5783 if (lastTracesFile != null) {
5784 curTracesFile.renameTo(lastTracesFile);
5785 } else {
5786 curTracesFile.delete();
5787 }
5788 }
5789 lastTracesFile = curTracesFile;
5790 }
5791 tracesFile.renameTo(curTracesFile);
5792 } finally {
5793 StrictMode.setThreadPolicy(oldPolicy);
5794 }
5795 }
5796
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005797 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005798 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005799
5800
Wale Ogunwale98875612018-10-12 07:53:02 -07005801 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5802 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005803
Riddle Hsud93a6c42018-11-29 21:50:06 +08005804 H(Looper looper) {
5805 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005806 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005807
5808 @Override
5809 public void handleMessage(Message msg) {
5810 switch (msg.what) {
5811 case REPORT_TIME_TRACKER_MSG: {
5812 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5813 tracker.deliverResult(mContext);
5814 } break;
5815 }
5816 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005817 }
5818
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005819 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005820 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005821
5822 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005823 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005824 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005825
5826 @Override
5827 public void handleMessage(Message msg) {
5828 switch (msg.what) {
5829 case DISMISS_DIALOG_UI_MSG: {
5830 final Dialog d = (Dialog) msg.obj;
5831 d.dismiss();
5832 break;
5833 }
5834 }
5835 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005836 }
5837
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005838 final class LocalService extends ActivityTaskManagerInternal {
5839 @Override
5840 public SleepToken acquireSleepToken(String tag, int displayId) {
5841 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005842 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005843 }
5844
5845 @Override
5846 public ComponentName getHomeActivityForUser(int userId) {
5847 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005848 final ActivityRecord homeActivity =
5849 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005850 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005851 }
5852 }
5853
5854 @Override
5855 public void onLocalVoiceInteractionStarted(IBinder activity,
5856 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5857 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005858 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005859 }
5860 }
5861
5862 @Override
5863 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5864 synchronized (mGlobalLock) {
5865 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5866 reasons, timestamp);
5867 }
5868 }
5869
5870 @Override
5871 public void notifyAppTransitionFinished() {
5872 synchronized (mGlobalLock) {
5873 mStackSupervisor.notifyAppTransitionDone();
5874 }
5875 }
5876
5877 @Override
5878 public void notifyAppTransitionCancelled() {
5879 synchronized (mGlobalLock) {
5880 mStackSupervisor.notifyAppTransitionDone();
5881 }
5882 }
5883
5884 @Override
5885 public List<IBinder> getTopVisibleActivities() {
5886 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005887 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005888 }
5889 }
5890
5891 @Override
5892 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5893 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005894 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005895 }
5896 }
5897
5898 @Override
5899 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5900 Bundle bOptions) {
5901 Preconditions.checkNotNull(intents, "intents");
5902 final String[] resolvedTypes = new String[intents.length];
5903
5904 // UID of the package on user userId.
5905 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5906 // packageUid may not be initialized.
5907 int packageUid = 0;
5908 final long ident = Binder.clearCallingIdentity();
5909
5910 try {
5911 for (int i = 0; i < intents.length; i++) {
5912 resolvedTypes[i] =
5913 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5914 }
5915
5916 packageUid = AppGlobals.getPackageManager().getPackageUid(
5917 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5918 } catch (RemoteException e) {
5919 // Shouldn't happen.
5920 } finally {
5921 Binder.restoreCallingIdentity(ident);
5922 }
5923
5924 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005925 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005926 packageUid, packageName,
5927 intents, resolvedTypes, null /* resultTo */,
5928 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005929 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5930 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005931 }
5932 }
5933
5934 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005935 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5936 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5937 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5938 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005939 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005940 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005941 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5942 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5943 userId, validateIncomingUser, originatingPendingIntent,
5944 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005945 }
5946 }
5947
5948 @Override
5949 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5950 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5951 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5952 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005953 PendingIntentRecord originatingPendingIntent,
5954 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005955 synchronized (mGlobalLock) {
5956 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5957 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5958 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005959 validateIncomingUser, originatingPendingIntent,
5960 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005961 }
5962 }
5963
5964 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5966 Intent intent, Bundle options, int userId) {
5967 return ActivityTaskManagerService.this.startActivityAsUser(
5968 caller, callerPacakge, intent,
5969 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5970 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5971 false /*validateIncomingUser*/);
5972 }
5973
5974 @Override
lumark588a3e82018-07-20 18:53:54 +08005975 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005976 synchronized (mGlobalLock) {
5977
5978 // We might change the visibilities here, so prepare an empty app transition which
5979 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005980 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005981 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005982 if (activityDisplay == null) {
5983 return;
5984 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005985 final DisplayContent dc = activityDisplay.mDisplayContent;
5986 final boolean wasTransitionSet =
5987 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005988 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005989 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005990 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005991 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005992
5993 // If there was a transition set already we don't want to interfere with it as we
5994 // might be starting it too early.
5995 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005996 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005997 }
5998 }
5999 if (callback != null) {
6000 callback.run();
6001 }
6002 }
6003
6004 @Override
6005 public void notifyKeyguardTrustedChanged() {
6006 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006007 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006008 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006009 }
6010 }
6011 }
6012
6013 /**
6014 * Called after virtual display Id is updated by
6015 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6016 * {@param vrVr2dDisplayId}.
6017 */
6018 @Override
6019 public void setVr2dDisplayId(int vr2dDisplayId) {
6020 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6021 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006022 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006023 }
6024 }
6025
6026 @Override
6027 public void setFocusedActivity(IBinder token) {
6028 synchronized (mGlobalLock) {
6029 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6030 if (r == null) {
6031 throw new IllegalArgumentException(
6032 "setFocusedActivity: No activity record matching token=" + token);
6033 }
Louis Chang19443452018-10-09 12:10:21 +08006034 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006035 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006036 }
6037 }
6038 }
6039
6040 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006041 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006042 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006043 }
6044
6045 @Override
6046 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006047 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006048 }
6049
6050 @Override
6051 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006052 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 }
6054
6055 @Override
6056 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6057 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6058 }
6059
6060 @Override
6061 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006062 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006063 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006064
6065 @Override
6066 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6067 synchronized (mGlobalLock) {
6068 mActiveVoiceInteractionServiceComponent = component;
6069 }
6070 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006071
6072 @Override
6073 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6074 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6075 return;
6076 }
6077 synchronized (mGlobalLock) {
6078 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6079 if (types == null) {
6080 if (uid < 0) {
6081 return;
6082 }
6083 types = new ArrayMap<>();
6084 mAllowAppSwitchUids.put(userId, types);
6085 }
6086 if (uid < 0) {
6087 types.remove(type);
6088 } else {
6089 types.put(type, uid);
6090 }
6091 }
6092 }
6093
6094 @Override
6095 public void onUserStopped(int userId) {
6096 synchronized (mGlobalLock) {
6097 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6098 mAllowAppSwitchUids.remove(userId);
6099 }
6100 }
6101
6102 @Override
6103 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6104 synchronized (mGlobalLock) {
6105 return ActivityTaskManagerService.this.isGetTasksAllowed(
6106 caller, callingPid, callingUid);
6107 }
6108 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006109
6110 @Override
6111 public void onProcessAdded(WindowProcessController proc) {
6112 synchronized (mGlobalLock) {
6113 mProcessNames.put(proc.mName, proc.mUid, proc);
6114 }
6115 }
6116
6117 @Override
6118 public void onProcessRemoved(String name, int uid) {
6119 synchronized (mGlobalLock) {
6120 mProcessNames.remove(name, uid);
6121 }
6122 }
6123
6124 @Override
6125 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6126 synchronized (mGlobalLock) {
6127 if (proc == mHomeProcess) {
6128 mHomeProcess = null;
6129 }
6130 if (proc == mPreviousProcess) {
6131 mPreviousProcess = null;
6132 }
6133 }
6134 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006135
6136 @Override
6137 public int getTopProcessState() {
6138 synchronized (mGlobalLock) {
6139 return mTopProcessState;
6140 }
6141 }
6142
6143 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006144 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6145 synchronized (mGlobalLock) {
6146 return proc == mHeavyWeightProcess;
6147 }
6148 }
6149
6150 @Override
6151 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6152 synchronized (mGlobalLock) {
6153 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6154 }
6155 }
6156
6157 @Override
6158 public void finishHeavyWeightApp() {
6159 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006160 if (mHeavyWeightProcess != null) {
6161 mHeavyWeightProcess.finishActivities();
6162 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006163 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6164 mHeavyWeightProcess);
6165 }
6166 }
6167
6168 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006169 public boolean isSleeping() {
6170 synchronized (mGlobalLock) {
6171 return isSleepingLocked();
6172 }
6173 }
6174
6175 @Override
6176 public boolean isShuttingDown() {
6177 synchronized (mGlobalLock) {
6178 return mShuttingDown;
6179 }
6180 }
6181
6182 @Override
6183 public boolean shuttingDown(boolean booted, int timeout) {
6184 synchronized (mGlobalLock) {
6185 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006186 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006187 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006188 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006189 return mStackSupervisor.shutdownLocked(timeout);
6190 }
6191 }
6192
6193 @Override
6194 public void enableScreenAfterBoot(boolean booted) {
6195 synchronized (mGlobalLock) {
6196 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6197 SystemClock.uptimeMillis());
6198 mWindowManager.enableScreenAfterBoot();
6199 updateEventDispatchingLocked(booted);
6200 }
6201 }
6202
6203 @Override
6204 public boolean showStrictModeViolationDialog() {
6205 synchronized (mGlobalLock) {
6206 return mShowDialogs && !mSleeping && !mShuttingDown;
6207 }
6208 }
6209
6210 @Override
6211 public void showSystemReadyErrorDialogsIfNeeded() {
6212 synchronized (mGlobalLock) {
6213 try {
6214 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6215 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6216 + " data partition or your device will be unstable.");
6217 mUiHandler.post(() -> {
6218 if (mShowDialogs) {
6219 AlertDialog d = new BaseErrorDialog(mUiContext);
6220 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6221 d.setCancelable(false);
6222 d.setTitle(mUiContext.getText(R.string.android_system_label));
6223 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6224 d.setButton(DialogInterface.BUTTON_POSITIVE,
6225 mUiContext.getText(R.string.ok),
6226 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6227 d.show();
6228 }
6229 });
6230 }
6231 } catch (RemoteException e) {
6232 }
6233
6234 if (!Build.isBuildConsistent()) {
6235 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6236 mUiHandler.post(() -> {
6237 if (mShowDialogs) {
6238 AlertDialog d = new BaseErrorDialog(mUiContext);
6239 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6240 d.setCancelable(false);
6241 d.setTitle(mUiContext.getText(R.string.android_system_label));
6242 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6243 d.setButton(DialogInterface.BUTTON_POSITIVE,
6244 mUiContext.getText(R.string.ok),
6245 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6246 d.show();
6247 }
6248 });
6249 }
6250 }
6251 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006252
6253 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006254 public void onProcessMapped(int pid, WindowProcessController proc) {
6255 synchronized (mGlobalLock) {
6256 mPidMap.put(pid, proc);
6257 }
6258 }
6259
6260 @Override
6261 public void onProcessUnMapped(int pid) {
6262 synchronized (mGlobalLock) {
6263 mPidMap.remove(pid);
6264 }
6265 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006266
6267 @Override
6268 public void onPackageDataCleared(String name) {
6269 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006270 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006271 mAppWarnings.onPackageDataCleared(name);
6272 }
6273 }
6274
6275 @Override
6276 public void onPackageUninstalled(String name) {
6277 synchronized (mGlobalLock) {
6278 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006279 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006280 }
6281 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006282
6283 @Override
6284 public void onPackageAdded(String name, boolean replacing) {
6285 synchronized (mGlobalLock) {
6286 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6287 }
6288 }
6289
6290 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006291 public void onPackageReplaced(ApplicationInfo aInfo) {
6292 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006293 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006294 }
6295 }
6296
6297 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006298 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6299 synchronized (mGlobalLock) {
6300 return compatibilityInfoForPackageLocked(ai);
6301 }
6302 }
6303
Yunfan Chen75157d72018-07-27 14:47:21 +09006304 /**
6305 * Set the corresponding display information for the process global configuration. To be
6306 * called when we need to show IME on a different display.
6307 *
6308 * @param pid The process id associated with the IME window.
6309 * @param displayId The ID of the display showing the IME.
6310 */
6311 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006312 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006313 if (pid == MY_PID || pid < 0) {
6314 if (DEBUG_CONFIGURATION) {
6315 Slog.w(TAG,
6316 "Trying to update display configuration for system/invalid process.");
6317 }
6318 return;
6319 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006320 synchronized (mGlobalLock) {
6321 final ActivityDisplay activityDisplay =
6322 mRootActivityContainer.getActivityDisplay(displayId);
6323 if (activityDisplay == null) {
6324 // Call might come when display is not yet added or has been removed.
6325 if (DEBUG_CONFIGURATION) {
6326 Slog.w(TAG, "Trying to update display configuration for non-existing "
6327 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006328 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006329 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006330 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006331 final WindowProcessController process = mPidMap.get(pid);
6332 if (process == null) {
6333 if (DEBUG_CONFIGURATION) {
6334 Slog.w(TAG, "Trying to update display configuration for invalid "
6335 + "process, pid=" + pid);
6336 }
6337 return;
6338 }
6339 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6340 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006341 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006342
6343 @Override
6344 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6345 int requestCode, int resultCode, Intent data) {
6346 synchronized (mGlobalLock) {
6347 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006348 if (r != null && r.getActivityStack() != null) {
6349 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6350 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006351 }
6352 }
6353 }
6354
6355 @Override
6356 public void clearPendingResultForActivity(IBinder activityToken,
6357 WeakReference<PendingIntentRecord> pir) {
6358 synchronized (mGlobalLock) {
6359 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6360 if (r != null && r.pendingResults != null) {
6361 r.pendingResults.remove(pir);
6362 }
6363 }
6364 }
6365
6366 @Override
6367 public IIntentSender getIntentSender(int type, String packageName,
6368 int callingUid, int userId, IBinder token, String resultWho,
6369 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6370 Bundle bOptions) {
6371 synchronized (mGlobalLock) {
6372 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6373 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6374 }
6375 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006376
6377 @Override
6378 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6379 synchronized (mGlobalLock) {
6380 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6381 if (r == null) {
6382 return null;
6383 }
6384 if (r.mServiceConnectionsHolder == null) {
6385 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6386 ActivityTaskManagerService.this, r);
6387 }
6388
6389 return r.mServiceConnectionsHolder;
6390 }
6391 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006392
6393 @Override
6394 public Intent getHomeIntent() {
6395 synchronized (mGlobalLock) {
6396 return ActivityTaskManagerService.this.getHomeIntent();
6397 }
6398 }
6399
6400 @Override
6401 public boolean startHomeActivity(int userId, String reason) {
6402 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006403 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006404 }
6405 }
6406
6407 @Override
6408 public boolean startHomeOnAllDisplays(int userId, String reason) {
6409 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006410 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006411 }
6412 }
6413
6414 @Override
6415 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6416 synchronized (mGlobalLock) {
6417 if (mFactoryTest == FACTORY_TEST_OFF) {
6418 return false;
6419 }
6420 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6421 && wpc.mName.equals(mTopComponent.getPackageName())) {
6422 return true;
6423 }
6424 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6425 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6426 }
6427 }
6428
6429 @Override
6430 public void updateTopComponentForFactoryTest() {
6431 synchronized (mGlobalLock) {
6432 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6433 return;
6434 }
6435 final ResolveInfo ri = mContext.getPackageManager()
6436 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6437 final CharSequence errorMsg;
6438 if (ri != null) {
6439 final ActivityInfo ai = ri.activityInfo;
6440 final ApplicationInfo app = ai.applicationInfo;
6441 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6442 mTopAction = Intent.ACTION_FACTORY_TEST;
6443 mTopData = null;
6444 mTopComponent = new ComponentName(app.packageName, ai.name);
6445 errorMsg = null;
6446 } else {
6447 errorMsg = mContext.getResources().getText(
6448 com.android.internal.R.string.factorytest_not_system);
6449 }
6450 } else {
6451 errorMsg = mContext.getResources().getText(
6452 com.android.internal.R.string.factorytest_no_action);
6453 }
6454 if (errorMsg == null) {
6455 return;
6456 }
6457
6458 mTopAction = null;
6459 mTopData = null;
6460 mTopComponent = null;
6461 mUiHandler.post(() -> {
6462 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6463 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006464 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006465 });
6466 }
6467 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006468
6469 @Override
6470 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6471 Runnable finishInstrumentationCallback) {
6472 synchronized (mGlobalLock) {
6473 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006474 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006475
6476 wpc.clearRecentTasks();
6477 wpc.clearActivities();
6478
6479 if (wpc.isInstrumenting()) {
6480 finishInstrumentationCallback.run();
6481 }
6482
Jorim Jaggid0752812018-10-16 16:07:20 +02006483 if (!restarting && hasVisibleActivities) {
6484 mWindowManager.deferSurfaceLayout();
6485 try {
6486 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6487 // If there was nothing to resume, and we are not already restarting
6488 // this process, but there is a visible activity that is hosted by the
6489 // process...then make sure all visible activities are running, taking
6490 // care of restarting this process.
6491 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6492 !PRESERVE_WINDOWS);
6493 }
6494 } finally {
6495 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006496 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006497 }
6498 }
6499 }
6500
6501 @Override
6502 public void closeSystemDialogs(String reason) {
6503 enforceNotIsolatedCaller("closeSystemDialogs");
6504
6505 final int pid = Binder.getCallingPid();
6506 final int uid = Binder.getCallingUid();
6507 final long origId = Binder.clearCallingIdentity();
6508 try {
6509 synchronized (mGlobalLock) {
6510 // Only allow this from foreground processes, so that background
6511 // applications can't abuse it to prevent system UI from being shown.
6512 if (uid >= FIRST_APPLICATION_UID) {
6513 final WindowProcessController proc = mPidMap.get(pid);
6514 if (!proc.isPerceptible()) {
6515 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6516 + " from background process " + proc);
6517 return;
6518 }
6519 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006520 mWindowManager.closeSystemDialogs(reason);
6521
Wale Ogunwaled32da472018-11-16 07:19:28 -08006522 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006523 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006524 // Call into AM outside the synchronized block.
6525 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006526 } finally {
6527 Binder.restoreCallingIdentity(origId);
6528 }
6529 }
6530
6531 @Override
6532 public void cleanupDisabledPackageComponents(
6533 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6534 synchronized (mGlobalLock) {
6535 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006536 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006537 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006538 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006539 mStackSupervisor.scheduleIdleLocked();
6540 }
6541
6542 // Clean-up disabled tasks
6543 getRecentTasks().cleanupDisabledPackageTasksLocked(
6544 packageName, disabledClasses, userId);
6545 }
6546 }
6547
6548 @Override
6549 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6550 int userId) {
6551 synchronized (mGlobalLock) {
6552
6553 boolean didSomething =
6554 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006555 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006556 null, doit, evenPersistent, userId);
6557 return didSomething;
6558 }
6559 }
6560
6561 @Override
6562 public void resumeTopActivities(boolean scheduleIdle) {
6563 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006564 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006565 if (scheduleIdle) {
6566 mStackSupervisor.scheduleIdleLocked();
6567 }
6568 }
6569 }
6570
6571 @Override
6572 public void preBindApplication(WindowProcessController wpc) {
6573 synchronized (mGlobalLock) {
6574 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6575 }
6576 }
6577
6578 @Override
6579 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6580 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006581 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006582 }
6583 }
6584
6585 @Override
6586 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6587 try {
6588 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6589 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6590 }
6591 } catch (RemoteException ex) {
6592 throw new SecurityException("Fail to check is caller a privileged app", ex);
6593 }
6594
6595 synchronized (mGlobalLock) {
6596 final long ident = Binder.clearCallingIdentity();
6597 try {
6598 if (mAmInternal.shouldConfirmCredentials(userId)) {
6599 if (mKeyguardController.isKeyguardLocked()) {
6600 // Showing launcher to avoid user entering credential twice.
6601 startHomeActivity(currentUserId, "notifyLockedProfile");
6602 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006603 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006604 }
6605 } finally {
6606 Binder.restoreCallingIdentity(ident);
6607 }
6608 }
6609 }
6610
6611 @Override
6612 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6613 mAmInternal.enforceCallingPermission(
6614 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6615
6616 synchronized (mGlobalLock) {
6617 final long ident = Binder.clearCallingIdentity();
6618 try {
6619 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6620 FLAG_ACTIVITY_TASK_ON_HOME);
6621 ActivityOptions activityOptions = options != null
6622 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006623 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006624 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006625 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006626 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006627 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006628 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6629 UserHandle.CURRENT);
6630 } finally {
6631 Binder.restoreCallingIdentity(ident);
6632 }
6633 }
6634 }
6635
6636 @Override
6637 public void writeActivitiesToProto(ProtoOutputStream proto) {
6638 synchronized (mGlobalLock) {
6639 // The output proto of "activity --proto activities"
6640 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006641 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006642 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6643 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006644 }
6645 }
6646
6647 @Override
6648 public void saveANRState(String reason) {
6649 synchronized (mGlobalLock) {
6650 final StringWriter sw = new StringWriter();
6651 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6652 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6653 if (reason != null) {
6654 pw.println(" Reason: " + reason);
6655 }
6656 pw.println();
6657 getActivityStartController().dump(pw, " ", null);
6658 pw.println();
6659 pw.println("-------------------------------------------------------------------------------");
6660 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6661 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6662 "" /* header */);
6663 pw.println();
6664 pw.close();
6665
6666 mLastANRState = sw.toString();
6667 }
6668 }
6669
6670 @Override
6671 public void clearSavedANRState() {
6672 synchronized (mGlobalLock) {
6673 mLastANRState = null;
6674 }
6675 }
6676
6677 @Override
6678 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6679 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6680 synchronized (mGlobalLock) {
6681 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6682 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6683 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6684 dumpLastANRLocked(pw);
6685 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6686 dumpLastANRTracesLocked(pw);
6687 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6688 dumpActivityStarterLocked(pw, dumpPackage);
6689 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6690 dumpActivityContainersLocked(pw);
6691 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6692 if (getRecentTasks() != null) {
6693 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6694 }
6695 }
6696 }
6697 }
6698
6699 @Override
6700 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6701 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6702 int wakefulness) {
6703 synchronized (mGlobalLock) {
6704 if (mHomeProcess != null && (dumpPackage == null
6705 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6706 if (needSep) {
6707 pw.println();
6708 needSep = false;
6709 }
6710 pw.println(" mHomeProcess: " + mHomeProcess);
6711 }
6712 if (mPreviousProcess != null && (dumpPackage == null
6713 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6714 if (needSep) {
6715 pw.println();
6716 needSep = false;
6717 }
6718 pw.println(" mPreviousProcess: " + mPreviousProcess);
6719 }
6720 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6721 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6722 StringBuilder sb = new StringBuilder(128);
6723 sb.append(" mPreviousProcessVisibleTime: ");
6724 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6725 pw.println(sb);
6726 }
6727 if (mHeavyWeightProcess != null && (dumpPackage == null
6728 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6729 if (needSep) {
6730 pw.println();
6731 needSep = false;
6732 }
6733 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6734 }
6735 if (dumpPackage == null) {
6736 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006737 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006738 }
6739 if (dumpAll) {
6740 if (dumpPackage == null) {
6741 pw.println(" mConfigWillChange: "
6742 + getTopDisplayFocusedStack().mConfigWillChange);
6743 }
6744 if (mCompatModePackages.getPackages().size() > 0) {
6745 boolean printed = false;
6746 for (Map.Entry<String, Integer> entry
6747 : mCompatModePackages.getPackages().entrySet()) {
6748 String pkg = entry.getKey();
6749 int mode = entry.getValue();
6750 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6751 continue;
6752 }
6753 if (!printed) {
6754 pw.println(" mScreenCompatPackages:");
6755 printed = true;
6756 }
6757 pw.println(" " + pkg + ": " + mode);
6758 }
6759 }
6760 }
6761
6762 if (dumpPackage == null) {
6763 pw.println(" mWakefulness="
6764 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006765 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766 if (mRunningVoice != null) {
6767 pw.println(" mRunningVoice=" + mRunningVoice);
6768 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6769 }
6770 pw.println(" mSleeping=" + mSleeping);
6771 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6772 pw.println(" mVrController=" + mVrController);
6773 }
6774 if (mCurAppTimeTracker != null) {
6775 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6776 }
6777 if (mAllowAppSwitchUids.size() > 0) {
6778 boolean printed = false;
6779 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6780 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6781 for (int j = 0; j < types.size(); j++) {
6782 if (dumpPackage == null ||
6783 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6784 if (needSep) {
6785 pw.println();
6786 needSep = false;
6787 }
6788 if (!printed) {
6789 pw.println(" mAllowAppSwitchUids:");
6790 printed = true;
6791 }
6792 pw.print(" User ");
6793 pw.print(mAllowAppSwitchUids.keyAt(i));
6794 pw.print(": Type ");
6795 pw.print(types.keyAt(j));
6796 pw.print(" = ");
6797 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6798 pw.println();
6799 }
6800 }
6801 }
6802 }
6803 if (dumpPackage == null) {
6804 if (mController != null) {
6805 pw.println(" mController=" + mController
6806 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6807 }
6808 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6809 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6810 }
6811
6812 return needSep;
6813 }
6814 }
6815
6816 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006817 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6818 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 synchronized (mGlobalLock) {
6820 if (dumpPackage == null) {
6821 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6822 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006823 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6824 if (mRunningVoice != null) {
6825 final long vrToken = proto.start(
6826 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6827 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6828 mRunningVoice.toString());
6829 mVoiceWakeLock.writeToProto(
6830 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6831 proto.end(vrToken);
6832 }
6833 mVrController.writeToProto(proto,
6834 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835 if (mController != null) {
6836 final long token = proto.start(CONTROLLER);
6837 proto.write(CONTROLLER, mController.toString());
6838 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6839 proto.end(token);
6840 }
6841 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6842 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6843 }
6844
6845 if (mHomeProcess != null && (dumpPackage == null
6846 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006847 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 }
6849
6850 if (mPreviousProcess != null && (dumpPackage == null
6851 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006852 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6854 }
6855
6856 if (mHeavyWeightProcess != null && (dumpPackage == null
6857 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006858 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 }
6860
6861 for (Map.Entry<String, Integer> entry
6862 : mCompatModePackages.getPackages().entrySet()) {
6863 String pkg = entry.getKey();
6864 int mode = entry.getValue();
6865 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6866 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6867 proto.write(PACKAGE, pkg);
6868 proto.write(MODE, mode);
6869 proto.end(compatToken);
6870 }
6871 }
6872
6873 if (mCurAppTimeTracker != null) {
6874 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6875 }
6876
6877 }
6878 }
6879
6880 @Override
6881 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6882 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6883 boolean dumpFocusedStackOnly) {
6884 synchronized (mGlobalLock) {
6885 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6886 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6887 }
6888 }
6889
6890 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006891 public void dumpForOom(PrintWriter pw) {
6892 synchronized (mGlobalLock) {
6893 pw.println(" mHomeProcess: " + mHomeProcess);
6894 pw.println(" mPreviousProcess: " + mPreviousProcess);
6895 if (mHeavyWeightProcess != null) {
6896 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6897 }
6898 }
6899 }
6900
6901 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 public boolean canGcNow() {
6903 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006904 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 }
6906 }
6907
6908 @Override
6909 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006910 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 return top != null ? top.app : null;
6913 }
6914 }
6915
6916 @Override
6917 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006918 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006919 if (mRootActivityContainer != null) {
6920 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006921 }
6922 }
6923 }
6924
6925 @Override
6926 public void scheduleDestroyAllActivities(String reason) {
6927 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006928 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 }
6930 }
6931
6932 @Override
6933 public void removeUser(int userId) {
6934 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006935 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 }
6937 }
6938
6939 @Override
6940 public boolean switchUser(int userId, UserState userState) {
6941 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006942 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006943 }
6944 }
6945
6946 @Override
6947 public void onHandleAppCrash(WindowProcessController wpc) {
6948 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006949 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006950 }
6951 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006952
6953 @Override
6954 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6955 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006956 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006957 }
6958 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006959
6960 @Override
6961 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006962 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006963 mActiveUids.put(uid, procState);
6964 }
6965 }
6966
6967 @Override
6968 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006969 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006970 mActiveUids.remove(uid);
6971 }
6972 }
6973
6974 @Override
6975 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006976 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006977 mActiveUids.clear();
6978 }
6979 }
6980
6981 @Override
6982 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006983 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006984 if (mActiveUids.get(uid) != null) {
6985 mActiveUids.put(uid, procState);
6986 }
6987 }
6988 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006989
6990 @Override
6991 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006992 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006993 mPendingTempWhitelist.put(uid, tag);
6994 }
6995 }
6996
6997 @Override
6998 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006999 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007000 mPendingTempWhitelist.remove(uid);
7001 }
7002 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007003
7004 @Override
7005 public boolean handleAppCrashInActivityController(String processName, int pid,
7006 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7007 Runnable killCrashingAppCallback) {
7008 synchronized (mGlobalLock) {
7009 if (mController == null) {
7010 return false;
7011 }
7012
7013 try {
7014 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7015 stackTrace)) {
7016 killCrashingAppCallback.run();
7017 return true;
7018 }
7019 } catch (RemoteException e) {
7020 mController = null;
7021 Watchdog.getInstance().setActivityController(null);
7022 }
7023 return false;
7024 }
7025 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007026
7027 @Override
7028 public void removeRecentTasksByPackageName(String packageName, int userId) {
7029 synchronized (mGlobalLock) {
7030 mRecentTasks.removeTasksByPackageName(packageName, userId);
7031 }
7032 }
7033
7034 @Override
7035 public void cleanupRecentTasksForUser(int userId) {
7036 synchronized (mGlobalLock) {
7037 mRecentTasks.cleanupLocked(userId);
7038 }
7039 }
7040
7041 @Override
7042 public void loadRecentTasksForUser(int userId) {
7043 synchronized (mGlobalLock) {
7044 mRecentTasks.loadUserRecentsLocked(userId);
7045 }
7046 }
7047
7048 @Override
7049 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7050 synchronized (mGlobalLock) {
7051 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7052 }
7053 }
7054
7055 @Override
7056 public void flushRecentTasks() {
7057 mRecentTasks.flush();
7058 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007059
7060 @Override
7061 public WindowProcessController getHomeProcess() {
7062 synchronized (mGlobalLock) {
7063 return mHomeProcess;
7064 }
7065 }
7066
7067 @Override
7068 public WindowProcessController getPreviousProcess() {
7069 synchronized (mGlobalLock) {
7070 return mPreviousProcess;
7071 }
7072 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007073
7074 @Override
7075 public void clearLockedTasks(String reason) {
7076 synchronized (mGlobalLock) {
7077 getLockTaskController().clearLockedTasks(reason);
7078 }
7079 }
7080
7081 @Override
7082 public void updateUserConfiguration() {
7083 synchronized (mGlobalLock) {
7084 final Configuration configuration = new Configuration(getGlobalConfiguration());
7085 final int currentUserId = mAmInternal.getCurrentUserId();
7086 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7087 configuration, currentUserId, Settings.System.canWrite(mContext));
7088 updateConfigurationLocked(configuration, null /* starting */,
7089 false /* initLocale */, false /* persistent */, currentUserId,
7090 false /* deferResume */);
7091 }
7092 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007093
7094 @Override
7095 public boolean canShowErrorDialogs() {
7096 synchronized (mGlobalLock) {
7097 return mShowDialogs && !mSleeping && !mShuttingDown
7098 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7099 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7100 mAmInternal.getCurrentUserId())
7101 && !(UserManager.isDeviceInDemoMode(mContext)
7102 && mAmInternal.getCurrentUser().isDemo());
7103 }
7104 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007105
7106 @Override
7107 public void setProfileApp(String profileApp) {
7108 synchronized (mGlobalLock) {
7109 mProfileApp = profileApp;
7110 }
7111 }
7112
7113 @Override
7114 public void setProfileProc(WindowProcessController wpc) {
7115 synchronized (mGlobalLock) {
7116 mProfileProc = wpc;
7117 }
7118 }
7119
7120 @Override
7121 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7122 synchronized (mGlobalLock) {
7123 mProfilerInfo = profilerInfo;
7124 }
7125 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007126
7127 @Override
7128 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7129 synchronized (mGlobalLock) {
7130 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7131 }
7132 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007133
7134 @Override
7135 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7136 synchronized (mGlobalLock) {
7137 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7138 }
7139 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007140
7141 @Override
7142 public boolean isUidForeground(int uid) {
7143 synchronized (mGlobalLock) {
7144 return ActivityTaskManagerService.this.isUidForeground(uid);
7145 }
7146 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007147
7148 @Override
7149 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7150 synchronized (mGlobalLock) {
7151 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7152 }
7153 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007154 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007155}