blob: 875fc4eab273bf84836a5b40bbe6b3ac2c3754ec [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;
Michal Karpinski302dcec2019-02-01 11:48:25 +0000154import android.app.admin.DevicePolicyManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.server.LocalServices;
249import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700250import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800251import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700253import com.android.server.am.ActivityManagerService;
254import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
255import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
256import com.android.server.am.AppTimeTracker;
257import com.android.server.am.BaseErrorDialog;
258import com.android.server.am.EventLogTags;
259import com.android.server.am.PendingIntentController;
260import com.android.server.am.PendingIntentRecord;
261import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900262import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700263import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700264import com.android.server.pm.UserManagerService;
265import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267
Wale Ogunwale31913b52018-10-13 08:29:31 -0700268import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700271import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700274import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700275import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700276import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700278import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700279import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400281import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700284import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Map;
286import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287
288/**
289 * System service for managing activities and their containers (task, stacks, displays,... ).
290 *
291 * {@hide}
292 */
293public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700294 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700296 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
297 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
298 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
299 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
300 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700301 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700303 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700304 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 /** Used to indicate that an app transition should be animated. */
309 static final boolean ANIMATE = true;
310
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700311 /** Hardware-reported OpenGLES version. */
312 final int GL_ES_VERSION;
313
Wale Ogunwale31913b52018-10-13 08:29:31 -0700314 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
315 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
316 public static final String DUMP_LASTANR_CMD = "lastanr" ;
317 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
318 public static final String DUMP_STARTER_CMD = "starter" ;
319 public static final String DUMP_CONTAINERS_CMD = "containers" ;
320 public static final String DUMP_RECENTS_CMD = "recents" ;
321 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
322
Wale Ogunwale64258362018-10-16 15:13:37 -0700323 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
324 public static final int RELAUNCH_REASON_NONE = 0;
325 /** This activity is being relaunched due to windowing mode change. */
326 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
327 /** This activity is being relaunched due to a free-resize operation. */
328 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
329
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700330 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700331
Wale Ogunwalef6733932018-06-27 05:14:34 -0700332 /**
333 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
334 * change at runtime. Use mContext for non-UI purposes.
335 */
336 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700337 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700338 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700341 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700342 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800343 @VisibleForTesting
344 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 PowerManagerInternal mPowerManagerInternal;
346 private UsageStatsManagerInternal mUsageStatsInternal;
347
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700348 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 IntentFirewall mIntentFirewall;
350
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700351 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800352 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800353 /**
354 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
355 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
356 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
357 *
358 * @see WindowManagerThreadPriorityBooster
359 */
360 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700361 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800362 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700363 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700364 private UserManagerService mUserManager;
365 private AppOpsService mAppOpsService;
Michal Karpinski302dcec2019-02-01 11:48:25 +0000366 private DevicePolicyManager mDpm;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700367 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700368 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
369 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700370 /** All processes currently running that might have a window organized by name. */
371 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700372 /** All processes we currently have running mapped by pid */
373 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700374 /** This is the process holding what we currently consider to be the "home" activity. */
375 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700376 /** The currently running heavy-weight process, if any. */
377 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700378 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /**
380 * This is the process holding the activity the user last visited that is in a different process
381 * from the one they are currently in.
382 */
383 WindowProcessController mPreviousProcess;
384 /** The time at which the previous process was last visible. */
385 long mPreviousProcessVisibleTime;
386
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700387 /** List of intents that were used to start the most recent tasks. */
388 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700389 /** State of external calls telling us if the device is awake or asleep. */
390 private boolean mKeyguardShown = false;
391
392 // Wrapper around VoiceInteractionServiceManager
393 private AssistUtils mAssistUtils;
394
395 // VoiceInteraction session ID that changes for each new request except when
396 // being called for multi-window assist in a single session.
397 private int mViSessionId = 1000;
398
399 // How long to wait in getAssistContextExtras for the activity and foreground services
400 // to respond with the result.
401 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
402
403 // How long top wait when going through the modern assist (which doesn't need to block
404 // on getting this result before starting to launch its UI).
405 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
406
407 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
408 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
409
Alison Cichowlas3e340502018-08-07 17:15:01 -0400410 // Permission tokens are used to temporarily granted a trusted app the ability to call
411 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
412 // showing any appropriate error messages to the user.
413 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
414 10 * MINUTE_IN_MILLIS;
415
416 // How long before the service actually expires a token. This is slightly longer than
417 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
418 // expiration exception.
419 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
420 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
421
422 // How long the service will remember expired tokens, for the purpose of providing error
423 // messaging when a client uses an expired token.
424 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
425 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
426
427 // Activity tokens of system activities that are delegating their call to
428 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
429 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
430
431 // Permission tokens that have expired, but we remember for error reporting.
432 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
433
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700434 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
435
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700436 // Keeps track of the active voice interaction service component, notified from
437 // VoiceInteractionManagerService
438 ComponentName mActiveVoiceInteractionServiceComponent;
439
Wale Ogunwalee2172292018-10-25 10:11:10 -0700440 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700441 KeyguardController mKeyguardController;
442 private final ClientLifecycleManager mLifecycleManager;
443 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700444 /** The controller for all operations related to locktask. */
445 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700446 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 boolean mSuppressResizeConfigChanges;
449
450 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
451 new UpdateConfigurationResult();
452
453 static final class UpdateConfigurationResult {
454 // Configuration changes that were updated.
455 int changes;
456 // If the activity was relaunched to match the new configuration.
457 boolean activityRelaunched;
458
459 void reset() {
460 changes = 0;
461 activityRelaunched = false;
462 }
463 }
464
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700465 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700466 private int mConfigurationSeq;
467 // To cache the list of supported system locales
468 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700469
470 /**
471 * Temp object used when global and/or display override configuration is updated. It is also
472 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
473 * anyone...
474 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700475 private Configuration mTempConfig = new Configuration();
476
Wale Ogunwalef6733932018-06-27 05:14:34 -0700477 /** Temporary to avoid allocations. */
478 final StringBuilder mStringBuilder = new StringBuilder(256);
479
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 // Amount of time after a call to stopAppSwitches() during which we will
481 // prevent further untrusted switches from happening.
482 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
483
484 /**
485 * The time at which we will allow normal application switches again,
486 * after a call to {@link #stopAppSwitches()}.
487 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700488 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 /**
490 * This is set to true after the first switch after mAppSwitchesAllowedTime
491 * is set; any switches after that will clear the time.
492 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494
495 IActivityController mController = null;
496 boolean mControllerIsAMonkey = false;
497
Wale Ogunwale214f3482018-10-04 11:00:47 -0700498 final int mFactoryTest;
499
500 /** Used to control how we initialize the service. */
501 ComponentName mTopComponent;
502 String mTopAction = Intent.ACTION_MAIN;
503 String mTopData;
504
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800505 /** Profiling app information. */
506 String mProfileApp = null;
507 WindowProcessController mProfileProc = null;
508 ProfilerInfo mProfilerInfo = null;
509
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700511 * Dump of the activity state at the time of the last ANR. Cleared after
512 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
513 */
514 String mLastANRState;
515
516 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 * Used to retain an update lock when the foreground activity is in
518 * immersive mode.
519 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700520 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521
522 /**
523 * Packages that are being allowed to perform unrestricted app switches. Mapping is
524 * User -> Type -> uid.
525 */
526 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
527
528 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700529 private int mThumbnailWidth;
530 private int mThumbnailHeight;
531 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532
533 /**
534 * Flag that indicates if multi-window is enabled.
535 *
536 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
537 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
538 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
539 * At least one of the forms of multi-window must be enabled in order for this flag to be
540 * initialized to 'true'.
541 *
542 * @see #mSupportsSplitScreenMultiWindow
543 * @see #mSupportsFreeformWindowManagement
544 * @see #mSupportsPictureInPicture
545 * @see #mSupportsMultiDisplay
546 */
547 boolean mSupportsMultiWindow;
548 boolean mSupportsSplitScreenMultiWindow;
549 boolean mSupportsFreeformWindowManagement;
550 boolean mSupportsPictureInPicture;
551 boolean mSupportsMultiDisplay;
552 boolean mForceResizableActivities;
553
554 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
555
556 // VR Vr2d Display Id.
557 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700558
Wale Ogunwalef6733932018-06-27 05:14:34 -0700559 /**
560 * Set while we are wanting to sleep, to prevent any
561 * activities from being started/resumed.
562 *
563 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
564 *
565 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
566 * while in the sleep state until there is a pending transition out of sleep, in which case
567 * mSleeping is set to false, and remains false while awake.
568 *
569 * Whether mSleeping can quickly toggled between true/false without the device actually
570 * display changing states is undefined.
571 */
572 private boolean mSleeping = false;
573
574 /**
575 * The process state used for processes that are running the top activities.
576 * This changes between TOP and TOP_SLEEPING to following mSleeping.
577 */
578 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
579
580 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
581 // automatically. Important for devices without direct input devices.
582 private boolean mShowDialogs = true;
583
584 /** Set if we are shutting down the system, similar to sleeping. */
585 boolean mShuttingDown = false;
586
587 /**
588 * We want to hold a wake lock while running a voice interaction session, since
589 * this may happen with the screen off and we need to keep the CPU running to
590 * be able to continue to interact with the user.
591 */
592 PowerManager.WakeLock mVoiceWakeLock;
593
594 /**
595 * Set while we are running a voice interaction. This overrides sleeping while it is active.
596 */
597 IVoiceInteractionSession mRunningVoice;
598
599 /**
600 * The last resumed activity. This is identical to the current resumed activity most
601 * of the time but could be different when we're pausing one activity before we resume
602 * another activity.
603 */
604 ActivityRecord mLastResumedActivity;
605
606 /**
607 * The activity that is currently being traced as the active resumed activity.
608 *
609 * @see #updateResumedAppTrace
610 */
611 private @Nullable ActivityRecord mTracedResumedActivity;
612
613 /** If non-null, we are tracking the time the user spends in the currently focused app. */
614 AppTimeTracker mCurAppTimeTracker;
615
Wale Ogunwale008163e2018-07-23 23:11:08 -0700616 private AppWarnings mAppWarnings;
617
Wale Ogunwale53783742018-09-16 10:21:51 -0700618 /**
619 * Packages that the user has asked to have run in screen size
620 * compatibility mode instead of filling the screen.
621 */
622 CompatModePackages mCompatModePackages;
623
Wale Ogunwalef6733932018-06-27 05:14:34 -0700624 private FontScaleSettingObserver mFontScaleSettingObserver;
625
626 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
Michal Karpinski302dcec2019-02-01 11:48:25 +0000841 DevicePolicyManager getDevicePolicyManager() {
842 if (mDpm == null) {
843 mDpm = mContext.getSystemService(DevicePolicyManager.class);
844 }
845 return mDpm;
846 }
847
Wale Ogunwalef6733932018-06-27 05:14:34 -0700848 boolean hasUserRestriction(String restriction, int userId) {
849 return getUserManager().hasUserRestriction(restriction, userId);
850 }
851
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700852 protected RecentTasks createRecentTasks() {
853 return new RecentTasks(this, mStackSupervisor);
854 }
855
856 RecentTasks getRecentTasks() {
857 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700858 }
859
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700860 ClientLifecycleManager getLifecycleManager() {
861 return mLifecycleManager;
862 }
863
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700864 ActivityStartController getActivityStartController() {
865 return mActivityStartController;
866 }
867
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700868 TaskChangeNotificationController getTaskChangeNotificationController() {
869 return mTaskChangeNotificationController;
870 }
871
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700872 LockTaskController getLockTaskController() {
873 return mLockTaskController;
874 }
875
Yunfan Chen75157d72018-07-27 14:47:21 +0900876 /**
877 * Return the global configuration used by the process corresponding to the input pid. This is
878 * usually the global configuration with some overrides specific to that process.
879 */
880 Configuration getGlobalConfigurationForCallingPid() {
881 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800882 return getGlobalConfigurationForPid(pid);
883 }
884
885 /**
886 * Return the global configuration used by the process corresponding to the given pid.
887 */
888 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900889 if (pid == MY_PID || pid < 0) {
890 return getGlobalConfiguration();
891 }
892 synchronized (mGlobalLock) {
893 final WindowProcessController app = mPidMap.get(pid);
894 return app != null ? app.getConfiguration() : getGlobalConfiguration();
895 }
896 }
897
898 /**
899 * Return the device configuration info used by the process corresponding to the input pid.
900 * The value is consistent with the global configuration for the process.
901 */
902 @Override
903 public ConfigurationInfo getDeviceConfigurationInfo() {
904 ConfigurationInfo config = new ConfigurationInfo();
905 synchronized (mGlobalLock) {
906 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
907 config.reqTouchScreen = globalConfig.touchscreen;
908 config.reqKeyboardType = globalConfig.keyboard;
909 config.reqNavigation = globalConfig.navigation;
910 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
911 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
912 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
913 }
914 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
915 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
916 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
917 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700918 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900919 }
920 return config;
921 }
922
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700923 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700924 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700925 }
926
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700927 public static final class Lifecycle extends SystemService {
928 private final ActivityTaskManagerService mService;
929
930 public Lifecycle(Context context) {
931 super(context);
932 mService = new ActivityTaskManagerService(context);
933 }
934
935 @Override
936 public void onStart() {
937 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700938 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700939 }
940
Garfield Tan891146c2018-10-09 12:14:00 -0700941 @Override
942 public void onUnlockUser(int userId) {
943 synchronized (mService.getGlobalLock()) {
944 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
945 }
946 }
947
948 @Override
949 public void onCleanupUser(int userId) {
950 synchronized (mService.getGlobalLock()) {
951 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
952 }
953 }
954
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700955 public ActivityTaskManagerService getService() {
956 return mService;
957 }
958 }
959
960 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700961 public final int startActivity(IApplicationThread caller, String callingPackage,
962 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
963 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
964 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
965 resultWho, requestCode, startFlags, profilerInfo, bOptions,
966 UserHandle.getCallingUserId());
967 }
968
969 @Override
970 public final int startActivities(IApplicationThread caller, String callingPackage,
971 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
972 int userId) {
973 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700974 enforceNotIsolatedCaller(reason);
975 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700976 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000977 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
978 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
979 reason, null /* originatingPendingIntent */,
980 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700981 }
982
983 @Override
984 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
985 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
986 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
987 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
988 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
989 true /*validateIncomingUser*/);
990 }
991
992 int startActivityAsUser(IApplicationThread caller, String callingPackage,
993 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
994 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
995 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700996 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700998 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700999 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1000
1001 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001002 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001003 .setCaller(caller)
1004 .setCallingPackage(callingPackage)
1005 .setResolvedType(resolvedType)
1006 .setResultTo(resultTo)
1007 .setResultWho(resultWho)
1008 .setRequestCode(requestCode)
1009 .setStartFlags(startFlags)
1010 .setProfilerInfo(profilerInfo)
1011 .setActivityOptions(bOptions)
1012 .setMayWait(userId)
1013 .execute();
1014
1015 }
1016
1017 @Override
1018 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1019 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001020 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1021 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 // Refuse possible leaked file descriptors
1023 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1024 throw new IllegalArgumentException("File descriptors passed in Intent");
1025 }
1026
1027 if (!(target instanceof PendingIntentRecord)) {
1028 throw new IllegalArgumentException("Bad PendingIntent object");
1029 }
1030
1031 PendingIntentRecord pir = (PendingIntentRecord)target;
1032
1033 synchronized (mGlobalLock) {
1034 // If this is coming from the currently resumed activity, it is
1035 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001036 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 if (stack.mResumedActivity != null &&
1038 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001039 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 }
1041 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001042 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 }
1045
1046 @Override
1047 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1048 Bundle bOptions) {
1049 // Refuse possible leaked file descriptors
1050 if (intent != null && intent.hasFileDescriptors()) {
1051 throw new IllegalArgumentException("File descriptors passed in Intent");
1052 }
1053 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1054
1055 synchronized (mGlobalLock) {
1056 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1057 if (r == null) {
1058 SafeActivityOptions.abort(options);
1059 return false;
1060 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001061 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 // The caller is not running... d'oh!
1063 SafeActivityOptions.abort(options);
1064 return false;
1065 }
1066 intent = new Intent(intent);
1067 // The caller is not allowed to change the data.
1068 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1069 // And we are resetting to find the next component...
1070 intent.setComponent(null);
1071
1072 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1073
1074 ActivityInfo aInfo = null;
1075 try {
1076 List<ResolveInfo> resolves =
1077 AppGlobals.getPackageManager().queryIntentActivities(
1078 intent, r.resolvedType,
1079 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1080 UserHandle.getCallingUserId()).getList();
1081
1082 // Look for the original activity in the list...
1083 final int N = resolves != null ? resolves.size() : 0;
1084 for (int i=0; i<N; i++) {
1085 ResolveInfo rInfo = resolves.get(i);
1086 if (rInfo.activityInfo.packageName.equals(r.packageName)
1087 && rInfo.activityInfo.name.equals(r.info.name)) {
1088 // We found the current one... the next matching is
1089 // after it.
1090 i++;
1091 if (i<N) {
1092 aInfo = resolves.get(i).activityInfo;
1093 }
1094 if (debug) {
1095 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1096 + "/" + r.info.name);
1097 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1098 ? "null" : aInfo.packageName + "/" + aInfo.name));
1099 }
1100 break;
1101 }
1102 }
1103 } catch (RemoteException e) {
1104 }
1105
1106 if (aInfo == null) {
1107 // Nobody who is next!
1108 SafeActivityOptions.abort(options);
1109 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1110 return false;
1111 }
1112
1113 intent.setComponent(new ComponentName(
1114 aInfo.applicationInfo.packageName, aInfo.name));
1115 intent.setFlags(intent.getFlags()&~(
1116 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1117 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1118 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1119 FLAG_ACTIVITY_NEW_TASK));
1120
1121 // Okay now we need to start the new activity, replacing the currently running activity.
1122 // This is a little tricky because we want to start the new one as if the current one is
1123 // finished, but not finish the current one first so that there is no flicker.
1124 // And thus...
1125 final boolean wasFinishing = r.finishing;
1126 r.finishing = true;
1127
1128 // Propagate reply information over to the new activity.
1129 final ActivityRecord resultTo = r.resultTo;
1130 final String resultWho = r.resultWho;
1131 final int requestCode = r.requestCode;
1132 r.resultTo = null;
1133 if (resultTo != null) {
1134 resultTo.removeResultsLocked(r, resultWho, requestCode);
1135 }
1136
1137 final long origId = Binder.clearCallingIdentity();
1138 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001139 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001140 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001141 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001142 .setResolvedType(r.resolvedType)
1143 .setActivityInfo(aInfo)
1144 .setResultTo(resultTo != null ? resultTo.appToken : null)
1145 .setResultWho(resultWho)
1146 .setRequestCode(requestCode)
1147 .setCallingPid(-1)
1148 .setCallingUid(r.launchedFromUid)
1149 .setCallingPackage(r.launchedFromPackage)
1150 .setRealCallingPid(-1)
1151 .setRealCallingUid(r.launchedFromUid)
1152 .setActivityOptions(options)
1153 .execute();
1154 Binder.restoreCallingIdentity(origId);
1155
1156 r.finishing = wasFinishing;
1157 if (res != ActivityManager.START_SUCCESS) {
1158 return false;
1159 }
1160 return true;
1161 }
1162 }
1163
1164 @Override
1165 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1166 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1167 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1168 final WaitResult res = new WaitResult();
1169 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001170 enforceNotIsolatedCaller("startActivityAndWait");
1171 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1172 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001173 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001174 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 .setCaller(caller)
1176 .setCallingPackage(callingPackage)
1177 .setResolvedType(resolvedType)
1178 .setResultTo(resultTo)
1179 .setResultWho(resultWho)
1180 .setRequestCode(requestCode)
1181 .setStartFlags(startFlags)
1182 .setActivityOptions(bOptions)
1183 .setMayWait(userId)
1184 .setProfilerInfo(profilerInfo)
1185 .setWaitResult(res)
1186 .execute();
1187 }
1188 return res;
1189 }
1190
1191 @Override
1192 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1193 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1194 int startFlags, Configuration config, Bundle bOptions, int userId) {
1195 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001196 enforceNotIsolatedCaller("startActivityWithConfig");
1197 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1198 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001199 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001200 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001201 .setCaller(caller)
1202 .setCallingPackage(callingPackage)
1203 .setResolvedType(resolvedType)
1204 .setResultTo(resultTo)
1205 .setResultWho(resultWho)
1206 .setRequestCode(requestCode)
1207 .setStartFlags(startFlags)
1208 .setGlobalConfiguration(config)
1209 .setActivityOptions(bOptions)
1210 .setMayWait(userId)
1211 .execute();
1212 }
1213 }
1214
Alison Cichowlas3e340502018-08-07 17:15:01 -04001215
1216 @Override
1217 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1218 int callingUid = Binder.getCallingUid();
1219 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1220 throw new SecurityException("Only the system process can request a permission token, "
1221 + "received request from uid: " + callingUid);
1222 }
1223 IBinder permissionToken = new Binder();
1224 synchronized (mGlobalLock) {
1225 mStartActivitySources.put(permissionToken, delegatorToken);
1226 }
1227
1228 Message expireMsg = PooledLambda.obtainMessage(
1229 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1230 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1231
1232 Message forgetMsg = PooledLambda.obtainMessage(
1233 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1234 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1235
1236 return permissionToken;
1237 }
1238
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 @Override
1240 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1241 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001242 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1243 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001245 // permission grants) as any app that may launch one of your own activities. So we only
1246 // allow this in two cases:
1247 // 1) The caller is an activity that is part of the core framework, and then only when it
1248 // is running as the system.
1249 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1250 // can only be requested by a system activity, which may then delegate this call to
1251 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001252 final ActivityRecord sourceRecord;
1253 final int targetUid;
1254 final String targetPackage;
1255 final boolean isResolver;
1256 synchronized (mGlobalLock) {
1257 if (resultTo == null) {
1258 throw new SecurityException("Must be called from an activity");
1259 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260 final IBinder sourceToken;
1261 if (permissionToken != null) {
1262 // To even attempt to use a permissionToken, an app must also have this signature
1263 // permission.
1264 mAmInternal.enforceCallingPermission(
1265 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1266 "startActivityAsCaller");
1267 // If called with a permissionToken, we want the sourceRecord from the delegator
1268 // activity that requested this token.
1269 sourceToken = mStartActivitySources.remove(permissionToken);
1270 if (sourceToken == null) {
1271 // Invalid permissionToken, check if it recently expired.
1272 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1273 throw new SecurityException("Called with expired permission token: "
1274 + permissionToken);
1275 } else {
1276 throw new SecurityException("Called with invalid permission token: "
1277 + permissionToken);
1278 }
1279 }
1280 } else {
1281 // This method was called directly by the source.
1282 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001283 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001284
Wale Ogunwaled32da472018-11-16 07:19:28 -08001285 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001286 if (sourceRecord == null) {
1287 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 }
1289 if (sourceRecord.app == null) {
1290 throw new SecurityException("Called without a process attached to activity");
1291 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001292
1293 // Whether called directly or from a delegate, the source activity must be from the
1294 // android package.
1295 if (!sourceRecord.info.packageName.equals("android")) {
1296 throw new SecurityException("Must be called from an activity that is "
1297 + "declared in the android package");
1298 }
1299
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001300 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 // This is still okay, as long as this activity is running under the
1302 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001303 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001305 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 + " must be system uid or original calling uid "
1307 + sourceRecord.launchedFromUid);
1308 }
1309 }
1310 if (ignoreTargetSecurity) {
1311 if (intent.getComponent() == null) {
1312 throw new SecurityException(
1313 "Component must be specified with ignoreTargetSecurity");
1314 }
1315 if (intent.getSelector() != null) {
1316 throw new SecurityException(
1317 "Selector not allowed with ignoreTargetSecurity");
1318 }
1319 }
1320 targetUid = sourceRecord.launchedFromUid;
1321 targetPackage = sourceRecord.launchedFromPackage;
1322 isResolver = sourceRecord.isResolverOrChildActivity();
1323 }
1324
1325 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001326 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 }
1328
1329 // TODO: Switch to user app stacks here.
1330 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001331 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001332 .setCallingUid(targetUid)
1333 .setCallingPackage(targetPackage)
1334 .setResolvedType(resolvedType)
1335 .setResultTo(resultTo)
1336 .setResultWho(resultWho)
1337 .setRequestCode(requestCode)
1338 .setStartFlags(startFlags)
1339 .setActivityOptions(bOptions)
1340 .setMayWait(userId)
1341 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1342 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1343 .execute();
1344 } catch (SecurityException e) {
1345 // XXX need to figure out how to propagate to original app.
1346 // A SecurityException here is generally actually a fault of the original
1347 // calling activity (such as a fairly granting permissions), so propagate it
1348 // back to them.
1349 /*
1350 StringBuilder msg = new StringBuilder();
1351 msg.append("While launching");
1352 msg.append(intent.toString());
1353 msg.append(": ");
1354 msg.append(e.getMessage());
1355 */
1356 throw e;
1357 }
1358 }
1359
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001360 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1361 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1362 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1363 }
1364
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 @Override
1366 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1367 Intent intent, String resolvedType, IVoiceInteractionSession session,
1368 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1369 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001370 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 if (session == null || interactor == null) {
1372 throw new NullPointerException("null session or interactor");
1373 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001374 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001376 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 .setCallingUid(callingUid)
1378 .setCallingPackage(callingPackage)
1379 .setResolvedType(resolvedType)
1380 .setVoiceSession(session)
1381 .setVoiceInteractor(interactor)
1382 .setStartFlags(startFlags)
1383 .setProfilerInfo(profilerInfo)
1384 .setActivityOptions(bOptions)
1385 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001386 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 .execute();
1388 }
1389
1390 @Override
1391 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1392 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001393 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1394 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001396 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 .setCallingUid(callingUid)
1398 .setCallingPackage(callingPackage)
1399 .setResolvedType(resolvedType)
1400 .setActivityOptions(bOptions)
1401 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001402 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 .execute();
1404 }
1405
1406 @Override
1407 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1408 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 final int callingPid = Binder.getCallingPid();
1411 final long origId = Binder.clearCallingIdentity();
1412 try {
1413 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001414 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1415 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416
1417 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1419 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1421 recentsUid, assistDataReceiver);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(origId);
1425 }
1426 }
1427
1428 @Override
1429 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 "startActivityFromRecents()");
1432
1433 final int callingPid = Binder.getCallingPid();
1434 final int callingUid = Binder.getCallingUid();
1435 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1436 final long origId = Binder.clearCallingIdentity();
1437 try {
1438 synchronized (mGlobalLock) {
1439 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1440 safeOptions);
1441 }
1442 } finally {
1443 Binder.restoreCallingIdentity(origId);
1444 }
1445 }
1446
1447 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001448 * Public API to check if the client is allowed to start an activity on specified display.
1449 *
1450 * If the target display is private or virtual, some restrictions will apply.
1451 *
1452 * @param displayId Target display id.
1453 * @param intent Intent used to launch the activity.
1454 * @param resolvedType The MIME type of the intent.
1455 * @param userId The id of the user for whom the call is made.
1456 * @return {@code true} if a call to start an activity on the target display should succeed and
1457 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1458 */
1459 @Override
1460 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1461 String resolvedType, int userId) {
1462 final int callingUid = Binder.getCallingUid();
1463 final int callingPid = Binder.getCallingPid();
1464 final long origId = Binder.clearCallingIdentity();
1465
1466 try {
1467 // Collect information about the target of the Intent.
1468 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1469 0 /* startFlags */, null /* profilerInfo */, userId,
1470 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1471 UserHandle.USER_NULL));
1472 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1473
1474 synchronized (mGlobalLock) {
1475 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1476 aInfo);
1477 }
1478 } finally {
1479 Binder.restoreCallingIdentity(origId);
1480 }
1481 }
1482
1483 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 * This is the internal entry point for handling Activity.finish().
1485 *
1486 * @param token The Binder token referencing the Activity we want to finish.
1487 * @param resultCode Result code, if any, from this Activity.
1488 * @param resultData Result data (Intent), if any, from this Activity.
1489 * @param finishTask Whether to finish the task associated with this Activity.
1490 *
1491 * @return Returns true if the activity successfully finished, or false if it is still running.
1492 */
1493 @Override
1494 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1495 int finishTask) {
1496 // Refuse possible leaked file descriptors
1497 if (resultData != null && resultData.hasFileDescriptors()) {
1498 throw new IllegalArgumentException("File descriptors passed in Intent");
1499 }
1500
1501 synchronized (mGlobalLock) {
1502 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1503 if (r == null) {
1504 return true;
1505 }
1506 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001507 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 ActivityRecord rootR = tr.getRootActivity();
1509 if (rootR == null) {
1510 Slog.w(TAG, "Finishing task with all activities already finished");
1511 }
1512 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1513 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001514 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001515 return false;
1516 }
1517
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001518 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1519 // We should consolidate.
1520 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001522 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 if (next != null) {
1524 // ask watcher if this is allowed
1525 boolean resumeOK = true;
1526 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001527 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001529 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001530 Watchdog.getInstance().setActivityController(null);
1531 }
1532
1533 if (!resumeOK) {
1534 Slog.i(TAG, "Not finishing activity because controller resumed");
1535 return false;
1536 }
1537 }
1538 }
1539 final long origId = Binder.clearCallingIdentity();
1540 try {
1541 boolean res;
1542 final boolean finishWithRootActivity =
1543 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1544 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1545 || (finishWithRootActivity && r == rootR)) {
1546 // If requested, remove the task that is associated to this activity only if it
1547 // was the root activity in the task. The result code and data is ignored
1548 // because we don't support returning them across task boundaries. Also, to
1549 // keep backwards compatibility we remove the task from recents when finishing
1550 // task with root activity.
1551 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1552 finishWithRootActivity, "finish-activity");
1553 if (!res) {
1554 Slog.i(TAG, "Removing task failed to finish activity");
1555 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001556 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001557 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 } else {
1559 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1560 resultData, "app-request", true);
1561 if (!res) {
1562 Slog.i(TAG, "Failed to finish by app-request");
1563 }
1564 }
1565 return res;
1566 } finally {
1567 Binder.restoreCallingIdentity(origId);
1568 }
1569 }
1570 }
1571
1572 @Override
1573 public boolean finishActivityAffinity(IBinder token) {
1574 synchronized (mGlobalLock) {
1575 final long origId = Binder.clearCallingIdentity();
1576 try {
1577 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1578 if (r == null) {
1579 return false;
1580 }
1581
1582 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1583 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001584 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001585 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 return false;
1587 }
1588 return task.getStack().finishActivityAffinityLocked(r);
1589 } finally {
1590 Binder.restoreCallingIdentity(origId);
1591 }
1592 }
1593 }
1594
1595 @Override
1596 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1597 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001598 try {
1599 WindowProcessController proc = null;
1600 synchronized (mGlobalLock) {
1601 ActivityStack stack = ActivityRecord.getStackLocked(token);
1602 if (stack == null) {
1603 return;
1604 }
1605 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1606 false /* fromTimeout */, false /* processPausingActivities */, config);
1607 if (r != null) {
1608 proc = r.app;
1609 }
1610 if (stopProfiling && proc != null) {
1611 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001612 }
1613 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001614 } finally {
1615 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 }
1618
1619 @Override
1620 public final void activityResumed(IBinder token) {
1621 final long origId = Binder.clearCallingIdentity();
1622 synchronized (mGlobalLock) {
1623 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001624 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 }
1626 Binder.restoreCallingIdentity(origId);
1627 }
1628
1629 @Override
1630 public final void activityPaused(IBinder token) {
1631 final long origId = Binder.clearCallingIdentity();
1632 synchronized (mGlobalLock) {
1633 ActivityStack stack = ActivityRecord.getStackLocked(token);
1634 if (stack != null) {
1635 stack.activityPausedLocked(token, false);
1636 }
1637 }
1638 Binder.restoreCallingIdentity(origId);
1639 }
1640
1641 @Override
1642 public final void activityStopped(IBinder token, Bundle icicle,
1643 PersistableBundle persistentState, CharSequence description) {
1644 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1645
1646 // Refuse possible leaked file descriptors
1647 if (icicle != null && icicle.hasFileDescriptors()) {
1648 throw new IllegalArgumentException("File descriptors passed in Bundle");
1649 }
1650
1651 final long origId = Binder.clearCallingIdentity();
1652
1653 synchronized (mGlobalLock) {
1654 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r != null) {
1656 r.activityStoppedLocked(icicle, persistentState, description);
1657 }
1658 }
1659
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001660 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661
1662 Binder.restoreCallingIdentity(origId);
1663 }
1664
1665 @Override
1666 public final void activityDestroyed(IBinder token) {
1667 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1668 synchronized (mGlobalLock) {
1669 ActivityStack stack = ActivityRecord.getStackLocked(token);
1670 if (stack != null) {
1671 stack.activityDestroyedLocked(token, "activityDestroyed");
1672 }
1673 }
1674 }
1675
1676 @Override
1677 public final void activityRelaunched(IBinder token) {
1678 final long origId = Binder.clearCallingIdentity();
1679 synchronized (mGlobalLock) {
1680 mStackSupervisor.activityRelaunchedLocked(token);
1681 }
1682 Binder.restoreCallingIdentity(origId);
1683 }
1684
1685 public final void activitySlept(IBinder token) {
1686 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1687
1688 final long origId = Binder.clearCallingIdentity();
1689
1690 synchronized (mGlobalLock) {
1691 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1692 if (r != null) {
1693 mStackSupervisor.activitySleptLocked(r);
1694 }
1695 }
1696
1697 Binder.restoreCallingIdentity(origId);
1698 }
1699
1700 @Override
1701 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1702 synchronized (mGlobalLock) {
1703 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1704 if (r == null) {
1705 return;
1706 }
1707 final long origId = Binder.clearCallingIdentity();
1708 try {
1709 r.setRequestedOrientation(requestedOrientation);
1710 } finally {
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713 }
1714 }
1715
1716 @Override
1717 public int getRequestedOrientation(IBinder token) {
1718 synchronized (mGlobalLock) {
1719 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1720 if (r == null) {
1721 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1722 }
1723 return r.getRequestedOrientation();
1724 }
1725 }
1726
1727 @Override
1728 public void setImmersive(IBinder token, boolean immersive) {
1729 synchronized (mGlobalLock) {
1730 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1731 if (r == null) {
1732 throw new IllegalArgumentException();
1733 }
1734 r.immersive = immersive;
1735
1736 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001737 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001739 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 }
1741 }
1742 }
1743
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001744 void applyUpdateLockStateLocked(ActivityRecord r) {
1745 // Modifications to the UpdateLock state are done on our handler, outside
1746 // the activity manager's locks. The new state is determined based on the
1747 // state *now* of the relevant activity record. The object is passed to
1748 // the handler solely for logging detail, not to be consulted/modified.
1749 final boolean nextState = r != null && r.immersive;
1750 mH.post(() -> {
1751 if (mUpdateLock.isHeld() != nextState) {
1752 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1753 "Applying new update lock state '" + nextState + "' for " + r);
1754 if (nextState) {
1755 mUpdateLock.acquire();
1756 } else {
1757 mUpdateLock.release();
1758 }
1759 }
1760 });
1761 }
1762
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 @Override
1764 public boolean isImmersive(IBinder token) {
1765 synchronized (mGlobalLock) {
1766 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1767 if (r == null) {
1768 throw new IllegalArgumentException();
1769 }
1770 return r.immersive;
1771 }
1772 }
1773
1774 @Override
1775 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001776 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001778 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 return (r != null) ? r.immersive : false;
1780 }
1781 }
1782
1783 @Override
1784 public void overridePendingTransition(IBinder token, String packageName,
1785 int enterAnim, int exitAnim) {
1786 synchronized (mGlobalLock) {
1787 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1788 if (self == null) {
1789 return;
1790 }
1791
1792 final long origId = Binder.clearCallingIdentity();
1793
1794 if (self.isState(
1795 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001796 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001797 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001798 }
1799
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802 }
1803
1804 @Override
1805 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001806 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001807 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001808 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001809 if (r == null) {
1810 return ActivityManager.COMPAT_MODE_UNKNOWN;
1811 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001812 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 }
1814 }
1815
1816 @Override
1817 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001818 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001820 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001822 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001823 if (r == null) {
1824 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1825 return;
1826 }
1827 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001828 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001829 }
1830 }
1831
1832 @Override
1833 public int getLaunchedFromUid(IBinder activityToken) {
1834 ActivityRecord srec;
1835 synchronized (mGlobalLock) {
1836 srec = ActivityRecord.forTokenLocked(activityToken);
1837 }
1838 if (srec == null) {
1839 return -1;
1840 }
1841 return srec.launchedFromUid;
1842 }
1843
1844 @Override
1845 public String getLaunchedFromPackage(IBinder activityToken) {
1846 ActivityRecord srec;
1847 synchronized (mGlobalLock) {
1848 srec = ActivityRecord.forTokenLocked(activityToken);
1849 }
1850 if (srec == null) {
1851 return null;
1852 }
1853 return srec.launchedFromPackage;
1854 }
1855
1856 @Override
1857 public boolean convertFromTranslucent(IBinder token) {
1858 final long origId = Binder.clearCallingIdentity();
1859 try {
1860 synchronized (mGlobalLock) {
1861 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1862 if (r == null) {
1863 return false;
1864 }
1865 final boolean translucentChanged = r.changeWindowTranslucency(true);
1866 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001867 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 return translucentChanged;
1871 }
1872 } finally {
1873 Binder.restoreCallingIdentity(origId);
1874 }
1875 }
1876
1877 @Override
1878 public boolean convertToTranslucent(IBinder token, Bundle options) {
1879 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1880 final long origId = Binder.clearCallingIdentity();
1881 try {
1882 synchronized (mGlobalLock) {
1883 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1884 if (r == null) {
1885 return false;
1886 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001887 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 int index = task.mActivities.lastIndexOf(r);
1889 if (index > 0) {
1890 ActivityRecord under = task.mActivities.get(index - 1);
1891 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1892 }
1893 final boolean translucentChanged = r.changeWindowTranslucency(false);
1894 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001895 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001897 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 return translucentChanged;
1900 }
1901 } finally {
1902 Binder.restoreCallingIdentity(origId);
1903 }
1904 }
1905
1906 @Override
1907 public void notifyActivityDrawn(IBinder token) {
1908 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1909 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001910 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001912 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914 }
1915 }
1916
1917 @Override
1918 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1919 synchronized (mGlobalLock) {
1920 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1921 if (r == null) {
1922 return;
1923 }
1924 r.reportFullyDrawnLocked(restoredFromBundle);
1925 }
1926 }
1927
1928 @Override
1929 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1930 synchronized (mGlobalLock) {
1931 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1932 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1933 return stack.mDisplayId;
1934 }
1935 return DEFAULT_DISPLAY;
1936 }
1937 }
1938
1939 @Override
1940 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001941 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 long ident = Binder.clearCallingIdentity();
1943 try {
1944 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001945 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001947 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 }
1949 return null;
1950 }
1951 } finally {
1952 Binder.restoreCallingIdentity(ident);
1953 }
1954 }
1955
1956 @Override
1957 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001958 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1960 final long callingId = Binder.clearCallingIdentity();
1961 try {
1962 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 if (stack == null) {
1965 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1966 return;
1967 }
1968 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001969 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001970 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 }
1972 }
1973 } finally {
1974 Binder.restoreCallingIdentity(callingId);
1975 }
1976 }
1977
1978 @Override
1979 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001980 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1982 final long callingId = Binder.clearCallingIdentity();
1983 try {
1984 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001985 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001986 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001987 if (task == null) {
1988 return;
1989 }
1990 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001991 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001992 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 }
1994 }
1995 } finally {
1996 Binder.restoreCallingIdentity(callingId);
1997 }
1998 }
1999
2000 @Override
2001 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002002 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 synchronized (mGlobalLock) {
2004 final long ident = Binder.clearCallingIdentity();
2005 try {
2006 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2007 "remove-task");
2008 } finally {
2009 Binder.restoreCallingIdentity(ident);
2010 }
2011 }
2012 }
2013
2014 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002015 public void removeAllVisibleRecentTasks() {
2016 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2017 synchronized (mGlobalLock) {
2018 final long ident = Binder.clearCallingIdentity();
2019 try {
2020 getRecentTasks().removeAllVisibleTasks();
2021 } finally {
2022 Binder.restoreCallingIdentity(ident);
2023 }
2024 }
2025 }
2026
2027 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2029 synchronized (mGlobalLock) {
2030 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2031 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002032 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 }
2034 }
2035 return false;
2036 }
2037
2038 @Override
2039 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2040 Intent resultData) {
2041
2042 synchronized (mGlobalLock) {
2043 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2044 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002045 return r.getActivityStack().navigateUpToLocked(
2046 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 }
2048 return false;
2049 }
2050 }
2051
2052 /**
2053 * Attempts to move a task backwards in z-order (the order of activities within the task is
2054 * unchanged).
2055 *
2056 * There are several possible results of this call:
2057 * - if the task is locked, then we will show the lock toast
2058 * - if there is a task behind the provided task, then that task is made visible and resumed as
2059 * this task is moved to the back
2060 * - otherwise, if there are no other tasks in the stack:
2061 * - if this task is in the pinned stack, then we remove the stack completely, which will
2062 * have the effect of moving the task to the top or bottom of the fullscreen stack
2063 * (depending on whether it is visible)
2064 * - otherwise, we simply return home and hide this task
2065 *
2066 * @param token A reference to the activity we wish to move
2067 * @param nonRoot If false then this only works if the activity is the root
2068 * of a task; if true it will work for any activity in a task.
2069 * @return Returns true if the move completed, false if not.
2070 */
2071 @Override
2072 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002073 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 synchronized (mGlobalLock) {
2075 final long origId = Binder.clearCallingIdentity();
2076 try {
2077 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002078 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (task != null) {
2080 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(origId);
2084 }
2085 }
2086 return false;
2087 }
2088
2089 @Override
2090 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002091 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 long ident = Binder.clearCallingIdentity();
2093 Rect rect = new Rect();
2094 try {
2095 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002096 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2098 if (task == null) {
2099 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2100 return rect;
2101 }
2102 if (task.getStack() != null) {
2103 // Return the bounds from window manager since it will be adjusted for various
2104 // things like the presense of a docked stack for tasks that aren't resizeable.
2105 task.getWindowContainerBounds(rect);
2106 } else {
2107 // Task isn't in window manager yet since it isn't associated with a stack.
2108 // Return the persist value from activity manager
2109 if (!task.matchParentBounds()) {
2110 rect.set(task.getBounds());
2111 } else if (task.mLastNonFullscreenBounds != null) {
2112 rect.set(task.mLastNonFullscreenBounds);
2113 }
2114 }
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(ident);
2118 }
2119 return rect;
2120 }
2121
2122 @Override
2123 public ActivityManager.TaskDescription getTaskDescription(int id) {
2124 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002125 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002127 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2129 if (tr != null) {
2130 return tr.lastTaskDescription;
2131 }
2132 }
2133 return null;
2134 }
2135
2136 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002137 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2138 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2139 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2140 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2141 return;
2142 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002143 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002144 synchronized (mGlobalLock) {
2145 final long ident = Binder.clearCallingIdentity();
2146 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002147 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002148 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002149 if (task == null) {
2150 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2151 return;
2152 }
2153
2154 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2155 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2156
2157 if (!task.isActivityTypeStandardOrUndefined()) {
2158 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2159 + " non-standard task " + taskId + " to windowing mode="
2160 + windowingMode);
2161 }
2162
2163 final ActivityStack stack = task.getStack();
2164 if (toTop) {
2165 stack.moveToFront("setTaskWindowingMode", task);
2166 }
2167 stack.setWindowingMode(windowingMode);
2168 } finally {
2169 Binder.restoreCallingIdentity(ident);
2170 }
2171 }
2172 }
2173
2174 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002176 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 ActivityRecord r = getCallingRecordLocked(token);
2178 return r != null ? r.info.packageName : null;
2179 }
2180 }
2181
2182 @Override
2183 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002184 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 ActivityRecord r = getCallingRecordLocked(token);
2186 return r != null ? r.intent.getComponent() : null;
2187 }
2188 }
2189
2190 private ActivityRecord getCallingRecordLocked(IBinder token) {
2191 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2192 if (r == null) {
2193 return null;
2194 }
2195 return r.resultTo;
2196 }
2197
2198 @Override
2199 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201
2202 synchronized (mGlobalLock) {
2203 final long origId = Binder.clearCallingIdentity();
2204 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002205 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 } finally {
2207 Binder.restoreCallingIdentity(origId);
2208 }
2209 }
2210 }
2211
2212 /**
2213 * TODO: Add mController hook
2214 */
2215 @Override
2216 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002217 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218
2219 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2220 synchronized (mGlobalLock) {
2221 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2222 false /* fromRecents */);
2223 }
2224 }
2225
2226 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2227 boolean fromRecents) {
2228
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002229 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 Binder.getCallingUid(), -1, -1, "Task to front")) {
2231 SafeActivityOptions.abort(options);
2232 return;
2233 }
2234 final long origId = Binder.clearCallingIdentity();
2235 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002236 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 if (task == null) {
2238 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002239 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 return;
2241 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002242 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002244 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 return;
2246 }
2247 ActivityOptions realOptions = options != null
2248 ? options.getOptions(mStackSupervisor)
2249 : null;
2250 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2251 false /* forceNonResizable */);
2252
2253 final ActivityRecord topActivity = task.getTopActivity();
2254 if (topActivity != null) {
2255
2256 // We are reshowing a task, use a starting window to hide the initial draw delay
2257 // so the transition can start earlier.
2258 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2259 true /* taskSwitch */, fromRecents);
2260 }
2261 } finally {
2262 Binder.restoreCallingIdentity(origId);
2263 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002264 }
2265
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002266 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2267 int callingPid, int callingUid, String name) {
2268 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2269 return true;
2270 }
2271
2272 if (getRecentTasks().isCallerRecents(sourceUid)) {
2273 return true;
2274 }
2275
2276 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2277 if (perm == PackageManager.PERMISSION_GRANTED) {
2278 return true;
2279 }
2280 if (checkAllowAppSwitchUid(sourceUid)) {
2281 return true;
2282 }
2283
2284 // If the actual IPC caller is different from the logical source, then
2285 // also see if they are allowed to control app switches.
2286 if (callingUid != -1 && callingUid != sourceUid) {
2287 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2288 if (perm == PackageManager.PERMISSION_GRANTED) {
2289 return true;
2290 }
2291 if (checkAllowAppSwitchUid(callingUid)) {
2292 return true;
2293 }
2294 }
2295
2296 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2297 return false;
2298 }
2299
2300 private boolean checkAllowAppSwitchUid(int uid) {
2301 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2302 if (types != null) {
2303 for (int i = types.size() - 1; i >= 0; i--) {
2304 if (types.valueAt(i).intValue() == uid) {
2305 return true;
2306 }
2307 }
2308 }
2309 return false;
2310 }
2311
2312 @Override
2313 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2314 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2315 "setActivityController()");
2316 synchronized (mGlobalLock) {
2317 mController = controller;
2318 mControllerIsAMonkey = imAMonkey;
2319 Watchdog.getInstance().setActivityController(controller);
2320 }
2321 }
2322
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002323 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002324 synchronized (mGlobalLock) {
2325 return mController != null && mControllerIsAMonkey;
2326 }
2327 }
2328
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 @Override
2330 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2331 synchronized (mGlobalLock) {
2332 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2333 }
2334 }
2335
2336 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002337 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2338 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2339 }
2340
2341 @Override
2342 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2343 @WindowConfiguration.ActivityType int ignoreActivityType,
2344 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2345 final int callingUid = Binder.getCallingUid();
2346 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2347
2348 synchronized (mGlobalLock) {
2349 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2350
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002351 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002352 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002353 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002354 ignoreWindowingMode, callingUid, allowed);
2355 }
2356
2357 return list;
2358 }
2359
2360 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002361 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2362 synchronized (mGlobalLock) {
2363 final long origId = Binder.clearCallingIdentity();
2364 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2365 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002366 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367 }
2368 Binder.restoreCallingIdentity(origId);
2369 }
2370 }
2371
2372 @Override
2373 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002374 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 ActivityStack stack = ActivityRecord.getStackLocked(token);
2376 if (stack != null) {
2377 return stack.willActivityBeVisibleLocked(token);
2378 }
2379 return false;
2380 }
2381 }
2382
2383 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002384 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002385 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002386 synchronized (mGlobalLock) {
2387 final long ident = Binder.clearCallingIdentity();
2388 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002389 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002390 if (task == null) {
2391 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2392 return;
2393 }
2394
2395 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2396 + " to stackId=" + stackId + " toTop=" + toTop);
2397
Wale Ogunwaled32da472018-11-16 07:19:28 -08002398 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002399 if (stack == null) {
2400 throw new IllegalStateException(
2401 "moveTaskToStack: No stack for stackId=" + stackId);
2402 }
2403 if (!stack.isActivityTypeStandardOrUndefined()) {
2404 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2405 + taskId + " to stack " + stackId);
2406 }
2407 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002408 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002409 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2410 }
2411 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2412 "moveTaskToStack");
2413 } finally {
2414 Binder.restoreCallingIdentity(ident);
2415 }
2416 }
2417 }
2418
2419 @Override
2420 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2421 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002422 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002423
2424 final long ident = Binder.clearCallingIdentity();
2425 try {
2426 synchronized (mGlobalLock) {
2427 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002428 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002429 if (stack == null) {
2430 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2431 return;
2432 }
2433 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2434 throw new IllegalArgumentException("Stack: " + stackId
2435 + " doesn't support animated resize.");
2436 }
2437 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2438 animationDuration, false /* fromFullscreen */);
2439 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002440 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002441 if (stack == null) {
2442 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2443 return;
2444 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002445 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002446 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2447 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2448 }
2449 }
2450 } finally {
2451 Binder.restoreCallingIdentity(ident);
2452 }
2453 }
2454
2455 /**
2456 * Moves the specified task to the primary-split-screen stack.
2457 *
2458 * @param taskId Id of task to move.
2459 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2460 * exist already. See
2461 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2462 * and
2463 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2464 * @param toTop If the task and stack should be moved to the top.
2465 * @param animate Whether we should play an animation for the moving the task.
2466 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2467 * stack. Pass {@code null} to use default bounds.
2468 * @param showRecents If the recents activity should be shown on the other side of the task
2469 * going into split-screen mode.
2470 */
2471 @Override
2472 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2473 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002474 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002475 "setTaskWindowingModeSplitScreenPrimary()");
2476 synchronized (mGlobalLock) {
2477 final long ident = Binder.clearCallingIdentity();
2478 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002479 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002480 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002481 if (task == null) {
2482 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2483 return false;
2484 }
2485 if (DEBUG_STACK) Slog.d(TAG_STACK,
2486 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2487 + " to createMode=" + createMode + " toTop=" + toTop);
2488 if (!task.isActivityTypeStandardOrUndefined()) {
2489 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2490 + " non-standard task " + taskId + " to split-screen windowing mode");
2491 }
2492
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002493 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002494 final int windowingMode = task.getWindowingMode();
2495 final ActivityStack stack = task.getStack();
2496 if (toTop) {
2497 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2498 }
2499 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002500 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2501 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 return windowingMode != task.getWindowingMode();
2503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
2506 }
2507 }
2508
2509 /**
2510 * Removes stacks in the input windowing modes from the system if they are of activity type
2511 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2512 */
2513 @Override
2514 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002515 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002516 "removeStacksInWindowingModes()");
2517
2518 synchronized (mGlobalLock) {
2519 final long ident = Binder.clearCallingIdentity();
2520 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002521 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 } finally {
2523 Binder.restoreCallingIdentity(ident);
2524 }
2525 }
2526 }
2527
2528 @Override
2529 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002530 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002531 "removeStacksWithActivityTypes()");
2532
2533 synchronized (mGlobalLock) {
2534 final long ident = Binder.clearCallingIdentity();
2535 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002536 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002537 } finally {
2538 Binder.restoreCallingIdentity(ident);
2539 }
2540 }
2541 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542
2543 @Override
2544 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2545 int userId) {
2546 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002547 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2548 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002549 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002550 final boolean detailed = checkGetTasksPermission(
2551 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2552 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002553 == PackageManager.PERMISSION_GRANTED;
2554
2555 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002556 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 callingUid);
2558 }
2559 }
2560
2561 @Override
2562 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002563 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002564 long ident = Binder.clearCallingIdentity();
2565 try {
2566 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002567 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002568 }
2569 } finally {
2570 Binder.restoreCallingIdentity(ident);
2571 }
2572 }
2573
2574 @Override
2575 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002576 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 long ident = Binder.clearCallingIdentity();
2578 try {
2579 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002580 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002581 }
2582 } finally {
2583 Binder.restoreCallingIdentity(ident);
2584 }
2585 }
2586
2587 @Override
2588 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002589 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002590 final long callingUid = Binder.getCallingUid();
2591 final long origId = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
2594 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002595 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002596 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2597 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2598 }
2599 } finally {
2600 Binder.restoreCallingIdentity(origId);
2601 }
2602 }
2603
2604 @Override
2605 public void startLockTaskModeByToken(IBinder token) {
2606 synchronized (mGlobalLock) {
2607 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2608 if (r == null) {
2609 return;
2610 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002611 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002612 }
2613 }
2614
2615 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002616 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002617 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002618 // This makes inner call to look as if it was initiated by system.
2619 long ident = Binder.clearCallingIdentity();
2620 try {
2621 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002622 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002623 MATCH_TASK_IN_STACKS_ONLY);
2624 if (task == null) {
2625 return;
2626 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002627
2628 // When starting lock task mode the stack must be in front and focused
2629 task.getStack().moveToFront("startSystemLockTaskMode");
2630 startLockTaskModeLocked(task, true /* isSystemCaller */);
2631 }
2632 } finally {
2633 Binder.restoreCallingIdentity(ident);
2634 }
2635 }
2636
2637 @Override
2638 public void stopLockTaskModeByToken(IBinder token) {
2639 synchronized (mGlobalLock) {
2640 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2641 if (r == null) {
2642 return;
2643 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002644 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002645 }
2646 }
2647
2648 /**
2649 * This API should be called by SystemUI only when user perform certain action to dismiss
2650 * lock task mode. We should only dismiss pinned lock task mode in this case.
2651 */
2652 @Override
2653 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002654 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002655 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2656 }
2657
2658 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2659 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2660 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2661 return;
2662 }
2663
Wale Ogunwaled32da472018-11-16 07:19:28 -08002664 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 if (stack == null || task != stack.topTask()) {
2666 throw new IllegalArgumentException("Invalid task, not in foreground");
2667 }
2668
2669 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2670 // system or a specific app.
2671 // * System-initiated requests will only start the pinned mode (screen pinning)
2672 // * App-initiated requests
2673 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2674 // - will start the pinned mode, otherwise
2675 final int callingUid = Binder.getCallingUid();
2676 long ident = Binder.clearCallingIdentity();
2677 try {
2678 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002679 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002680
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002681 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
2686
2687 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2688 final int callingUid = Binder.getCallingUid();
2689 long ident = Binder.clearCallingIdentity();
2690 try {
2691 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002692 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002693 }
2694 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2695 // task and jumping straight into a call in the case of emergency call back.
2696 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2697 if (tm != null) {
2698 tm.showInCallScreen(false);
2699 }
2700 } finally {
2701 Binder.restoreCallingIdentity(ident);
2702 }
2703 }
2704
2705 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002706 public void updateLockTaskPackages(int userId, String[] packages) {
2707 final int callingUid = Binder.getCallingUid();
2708 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2709 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2710 "updateLockTaskPackages()");
2711 }
2712 synchronized (this) {
2713 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2714 + Arrays.toString(packages));
2715 getLockTaskController().updateLockTaskPackages(userId, packages);
2716 }
2717 }
2718
2719 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 public boolean isInLockTaskMode() {
2721 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2722 }
2723
2724 @Override
2725 public int getLockTaskModeState() {
2726 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002727 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002728 }
2729 }
2730
2731 @Override
2732 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2733 synchronized (mGlobalLock) {
2734 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2735 if (r != null) {
2736 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002737 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002738 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002739 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 }
2741 }
2742 }
2743
2744 @Override
2745 public Bundle getActivityOptions(IBinder token) {
2746 final long origId = Binder.clearCallingIdentity();
2747 try {
2748 synchronized (mGlobalLock) {
2749 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2750 if (r != null) {
2751 final ActivityOptions activityOptions = r.takeOptionsLocked();
2752 return activityOptions == null ? null : activityOptions.toBundle();
2753 }
2754 return null;
2755 }
2756 } finally {
2757 Binder.restoreCallingIdentity(origId);
2758 }
2759 }
2760
2761 @Override
2762 public List<IBinder> getAppTasks(String callingPackage) {
2763 int callingUid = Binder.getCallingUid();
2764 long ident = Binder.clearCallingIdentity();
2765 try {
2766 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002767 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 }
2769 } finally {
2770 Binder.restoreCallingIdentity(ident);
2771 }
2772 }
2773
2774 @Override
2775 public void finishVoiceTask(IVoiceInteractionSession session) {
2776 synchronized (mGlobalLock) {
2777 final long origId = Binder.clearCallingIdentity();
2778 try {
2779 // TODO: VI Consider treating local voice interactions and voice tasks
2780 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002781 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 } finally {
2783 Binder.restoreCallingIdentity(origId);
2784 }
2785 }
2786
2787 }
2788
2789 @Override
2790 public boolean isTopOfTask(IBinder token) {
2791 synchronized (mGlobalLock) {
2792 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002793 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 }
2795 }
2796
2797 @Override
2798 public void notifyLaunchTaskBehindComplete(IBinder token) {
2799 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2800 }
2801
2802 @Override
2803 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002804 mH.post(() -> {
2805 synchronized (mGlobalLock) {
2806 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002807 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002808 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002809 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002810 } catch (RemoteException e) {
2811 }
2812 }
2813 }
2814
2815 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 }
2817
2818 /** Called from an app when assist data is ready. */
2819 @Override
2820 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2821 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002822 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 synchronized (pae) {
2824 pae.result = extras;
2825 pae.structure = structure;
2826 pae.content = content;
2827 if (referrer != null) {
2828 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2829 }
2830 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002831 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002832 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2833 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002834 structure.setHomeActivity(pae.isHome);
2835 }
2836 pae.haveResult = true;
2837 pae.notifyAll();
2838 if (pae.intent == null && pae.receiver == null) {
2839 // Caller is just waiting for the result.
2840 return;
2841 }
2842 }
2843 // We are now ready to launch the assist activity.
2844 IAssistDataReceiver sendReceiver = null;
2845 Bundle sendBundle = null;
2846 synchronized (mGlobalLock) {
2847 buildAssistBundleLocked(pae, extras);
2848 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002849 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 if (!exists) {
2851 // Timed out.
2852 return;
2853 }
2854
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 // Caller wants result sent back to them.
2857 sendBundle = new Bundle();
2858 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2859 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2860 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2861 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2862 }
2863 }
2864 if (sendReceiver != null) {
2865 try {
2866 sendReceiver.onHandleAssistData(sendBundle);
2867 } catch (RemoteException e) {
2868 }
2869 return;
2870 }
2871
2872 final long ident = Binder.clearCallingIdentity();
2873 try {
2874 if (TextUtils.equals(pae.intent.getAction(),
2875 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2876 pae.intent.putExtras(pae.extras);
2877 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2878 } else {
2879 pae.intent.replaceExtras(pae.extras);
2880 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2881 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2882 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002883 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884
2885 try {
2886 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2887 } catch (ActivityNotFoundException e) {
2888 Slog.w(TAG, "No activity to handle assist action.", e);
2889 }
2890 }
2891 } finally {
2892 Binder.restoreCallingIdentity(ident);
2893 }
2894 }
2895
2896 @Override
2897 public int addAppTask(IBinder activityToken, Intent intent,
2898 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2899 final int callingUid = Binder.getCallingUid();
2900 final long callingIdent = Binder.clearCallingIdentity();
2901
2902 try {
2903 synchronized (mGlobalLock) {
2904 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2905 if (r == null) {
2906 throw new IllegalArgumentException("Activity does not exist; token="
2907 + activityToken);
2908 }
2909 ComponentName comp = intent.getComponent();
2910 if (comp == null) {
2911 throw new IllegalArgumentException("Intent " + intent
2912 + " must specify explicit component");
2913 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002914 if (thumbnail.getWidth() != mThumbnailWidth
2915 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 throw new IllegalArgumentException("Bad thumbnail size: got "
2917 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002918 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 }
2920 if (intent.getSelector() != null) {
2921 intent.setSelector(null);
2922 }
2923 if (intent.getSourceBounds() != null) {
2924 intent.setSourceBounds(null);
2925 }
2926 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2927 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2928 // The caller has added this as an auto-remove task... that makes no
2929 // sense, so turn off auto-remove.
2930 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2931 }
2932 }
2933 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2934 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2935 if (ainfo.applicationInfo.uid != callingUid) {
2936 throw new SecurityException(
2937 "Can't add task for another application: target uid="
2938 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2939 }
2940
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002941 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002943 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002945 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 // The app has too many tasks already and we can't add any more
2947 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2948 return INVALID_TASK_ID;
2949 }
2950 task.lastTaskDescription.copyFrom(description);
2951
2952 // TODO: Send the thumbnail to WM to store it.
2953
2954 return task.taskId;
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(callingIdent);
2958 }
2959 }
2960
2961 @Override
2962 public Point getAppTaskThumbnailSize() {
2963 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002964 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 }
2966 }
2967
2968 @Override
2969 public void setTaskResizeable(int taskId, int resizeableMode) {
2970 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002971 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2973 if (task == null) {
2974 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2975 return;
2976 }
2977 task.setResizeMode(resizeableMode);
2978 }
2979 }
2980
2981 @Override
2982 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002983 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 long ident = Binder.clearCallingIdentity();
2985 try {
2986 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002987 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002988 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002989 if (task == null) {
2990 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2991 return;
2992 }
2993 // Place the task in the right stack if it isn't there already based on
2994 // the requested bounds.
2995 // The stack transition logic is:
2996 // - a null bounds on a freeform task moves that task to fullscreen
2997 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2998 // that task to freeform
2999 // - otherwise the task is not moved
3000 ActivityStack stack = task.getStack();
3001 if (!task.getWindowConfiguration().canResizeTask()) {
3002 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3003 }
3004 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3005 stack = stack.getDisplay().getOrCreateStack(
3006 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3007 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3008 stack = stack.getDisplay().getOrCreateStack(
3009 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3010 }
3011
3012 // Reparent the task to the right stack if necessary
3013 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3014 if (stack != task.getStack()) {
3015 // Defer resume until the task is resized below
3016 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3017 DEFER_RESUME, "resizeTask");
3018 preserveWindow = false;
3019 }
3020
3021 // After reparenting (which only resizes the task to the stack bounds), resize the
3022 // task to the actual bounds provided
3023 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3024 }
3025 } finally {
3026 Binder.restoreCallingIdentity(ident);
3027 }
3028 }
3029
3030 @Override
3031 public boolean releaseActivityInstance(IBinder token) {
3032 synchronized (mGlobalLock) {
3033 final long origId = Binder.clearCallingIdentity();
3034 try {
3035 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3036 if (r == null) {
3037 return false;
3038 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003039 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003040 } finally {
3041 Binder.restoreCallingIdentity(origId);
3042 }
3043 }
3044 }
3045
3046 @Override
3047 public void releaseSomeActivities(IApplicationThread appInt) {
3048 synchronized (mGlobalLock) {
3049 final long origId = Binder.clearCallingIdentity();
3050 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003051 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003052 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003053 } finally {
3054 Binder.restoreCallingIdentity(origId);
3055 }
3056 }
3057 }
3058
3059 @Override
3060 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003061 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003062 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003063 != PackageManager.PERMISSION_GRANTED) {
3064 throw new SecurityException("Requires permission "
3065 + android.Manifest.permission.DEVICE_POWER);
3066 }
3067
3068 synchronized (mGlobalLock) {
3069 long ident = Binder.clearCallingIdentity();
3070 if (mKeyguardShown != keyguardShowing) {
3071 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003072 final Message msg = PooledLambda.obtainMessage(
3073 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3074 keyguardShowing);
3075 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 }
3077 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003078 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003079 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 } finally {
3081 Binder.restoreCallingIdentity(ident);
3082 }
3083 }
3084
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003085 mH.post(() -> {
3086 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3087 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3088 }
3089 });
3090 }
3091
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003092 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003093 mH.post(() -> {
3094 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3095 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3096 }
3097 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 }
3099
3100 @Override
3101 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003102 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3103 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003104
3105 final File passedIconFile = new File(filePath);
3106 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3107 passedIconFile.getName());
3108 if (!legitIconFile.getPath().equals(filePath)
3109 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3110 throw new IllegalArgumentException("Bad file path: " + filePath
3111 + " passed for userId " + userId);
3112 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003113 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 }
3115
3116 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003117 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3119 final ActivityOptions activityOptions = safeOptions != null
3120 ? safeOptions.getOptions(mStackSupervisor)
3121 : null;
3122 if (activityOptions == null
3123 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3124 || activityOptions.getCustomInPlaceResId() == 0) {
3125 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3126 "with valid animation");
3127 }
lumark588a3e82018-07-20 18:53:54 +08003128 // Get top display of front most application.
3129 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3130 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003131 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3132 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3133 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003134 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003135 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003136 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 }
3138
3139 @Override
3140 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003141 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142 synchronized (mGlobalLock) {
3143 final long ident = Binder.clearCallingIdentity();
3144 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003145 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 if (stack == null) {
3147 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3148 return;
3149 }
3150 if (!stack.isActivityTypeStandardOrUndefined()) {
3151 throw new IllegalArgumentException(
3152 "Removing non-standard stack is not allowed.");
3153 }
3154 mStackSupervisor.removeStack(stack);
3155 } finally {
3156 Binder.restoreCallingIdentity(ident);
3157 }
3158 }
3159 }
3160
3161 @Override
3162 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003163 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164
3165 synchronized (mGlobalLock) {
3166 final long ident = Binder.clearCallingIdentity();
3167 try {
3168 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3169 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003170 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 } finally {
3172 Binder.restoreCallingIdentity(ident);
3173 }
3174 }
3175 }
3176
3177 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 public void exitFreeformMode(IBinder token) {
3179 synchronized (mGlobalLock) {
3180 long ident = Binder.clearCallingIdentity();
3181 try {
3182 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3183 if (r == null) {
3184 throw new IllegalArgumentException(
3185 "exitFreeformMode: No activity record matching token=" + token);
3186 }
3187
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003188 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 if (stack == null || !stack.inFreeformWindowingMode()) {
3190 throw new IllegalStateException(
3191 "exitFreeformMode: You can only go fullscreen from freeform.");
3192 }
3193
3194 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3195 } finally {
3196 Binder.restoreCallingIdentity(ident);
3197 }
3198 }
3199 }
3200
3201 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3202 @Override
3203 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003204 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003206 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 }
3208
3209 /** Unregister a task stack listener so that it stops receiving callbacks. */
3210 @Override
3211 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003212 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003214 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 }
3216
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 @Override
3218 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3219 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3220 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3221 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3222 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3223 }
3224
3225 @Override
3226 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3227 IBinder activityToken, int flags) {
3228 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3229 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3230 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3231 }
3232
3233 @Override
3234 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3235 Bundle args) {
3236 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3237 true /* focused */, true /* newSessionId */, userHandle, args,
3238 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3239 }
3240
3241 @Override
3242 public Bundle getAssistContextExtras(int requestType) {
3243 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3244 null, null, true /* focused */, true /* newSessionId */,
3245 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3246 if (pae == null) {
3247 return null;
3248 }
3249 synchronized (pae) {
3250 while (!pae.haveResult) {
3251 try {
3252 pae.wait();
3253 } catch (InterruptedException e) {
3254 }
3255 }
3256 }
3257 synchronized (mGlobalLock) {
3258 buildAssistBundleLocked(pae, pae.result);
3259 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003260 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 }
3262 return pae.extras;
3263 }
3264
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003265 /**
3266 * Binder IPC calls go through the public entry point.
3267 * This can be called with or without the global lock held.
3268 */
3269 private static int checkCallingPermission(String permission) {
3270 return checkPermission(
3271 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3272 }
3273
3274 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003275 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003276 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3277 mAmInternal.enforceCallingPermission(permission, func);
3278 }
3279 }
3280
3281 @VisibleForTesting
3282 int checkGetTasksPermission(String permission, int pid, int uid) {
3283 return checkPermission(permission, pid, uid);
3284 }
3285
3286 static int checkPermission(String permission, int pid, int uid) {
3287 if (permission == null) {
3288 return PackageManager.PERMISSION_DENIED;
3289 }
3290 return checkComponentPermission(permission, pid, uid, -1, true);
3291 }
3292
Wale Ogunwale214f3482018-10-04 11:00:47 -07003293 public static int checkComponentPermission(String permission, int pid, int uid,
3294 int owningUid, boolean exported) {
3295 return ActivityManagerService.checkComponentPermission(
3296 permission, pid, uid, owningUid, exported);
3297 }
3298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003299 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3300 if (getRecentTasks().isCallerRecents(callingUid)) {
3301 // Always allow the recents component to get tasks
3302 return true;
3303 }
3304
3305 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3306 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3307 if (!allowed) {
3308 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3309 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3310 // Temporary compatibility: some existing apps on the system image may
3311 // still be requesting the old permission and not switched to the new
3312 // one; if so, we'll still allow them full access. This means we need
3313 // to see if they are holding the old permission and are a system app.
3314 try {
3315 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3316 allowed = true;
3317 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3318 + " is using old GET_TASKS but privileged; allowing");
3319 }
3320 } catch (RemoteException e) {
3321 }
3322 }
3323 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3324 + " does not hold REAL_GET_TASKS; limiting output");
3325 }
3326 return allowed;
3327 }
3328
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3330 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3331 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3332 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003333 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 "enqueueAssistContext()");
3335
3336 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003337 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003338 if (activity == null) {
3339 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3340 return null;
3341 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003342 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3344 return null;
3345 }
3346 if (focused) {
3347 if (activityToken != null) {
3348 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3349 if (activity != caller) {
3350 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3351 + " is not current top " + activity);
3352 return null;
3353 }
3354 }
3355 } else {
3356 activity = ActivityRecord.forTokenLocked(activityToken);
3357 if (activity == null) {
3358 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3359 + " couldn't be found");
3360 return null;
3361 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003362 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003363 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3364 return null;
3365 }
3366 }
3367
3368 PendingAssistExtras pae;
3369 Bundle extras = new Bundle();
3370 if (args != null) {
3371 extras.putAll(args);
3372 }
3373 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003374 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375
3376 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3377 userHandle);
3378 pae.isHome = activity.isActivityTypeHome();
3379
3380 // Increment the sessionId if necessary
3381 if (newSessionId) {
3382 mViSessionId++;
3383 }
3384 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003385 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3386 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003388 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 } catch (RemoteException e) {
3390 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3391 return null;
3392 }
3393 return pae;
3394 }
3395 }
3396
3397 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3398 if (result != null) {
3399 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3400 }
3401 if (pae.hint != null) {
3402 pae.extras.putBoolean(pae.hint, true);
3403 }
3404 }
3405
3406 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3407 IAssistDataReceiver receiver;
3408 synchronized (mGlobalLock) {
3409 mPendingAssistExtras.remove(pae);
3410 receiver = pae.receiver;
3411 }
3412 if (receiver != null) {
3413 // Caller wants result sent back to them.
3414 Bundle sendBundle = new Bundle();
3415 // At least return the receiver extras
3416 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3417 try {
3418 pae.receiver.onHandleAssistData(sendBundle);
3419 } catch (RemoteException e) {
3420 }
3421 }
3422 }
3423
3424 public class PendingAssistExtras extends Binder implements Runnable {
3425 public final ActivityRecord activity;
3426 public boolean isHome;
3427 public final Bundle extras;
3428 public final Intent intent;
3429 public final String hint;
3430 public final IAssistDataReceiver receiver;
3431 public final int userHandle;
3432 public boolean haveResult = false;
3433 public Bundle result = null;
3434 public AssistStructure structure = null;
3435 public AssistContent content = null;
3436 public Bundle receiverExtras;
3437
3438 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3439 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3440 int _userHandle) {
3441 activity = _activity;
3442 extras = _extras;
3443 intent = _intent;
3444 hint = _hint;
3445 receiver = _receiver;
3446 receiverExtras = _receiverExtras;
3447 userHandle = _userHandle;
3448 }
3449
3450 @Override
3451 public void run() {
3452 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3453 synchronized (this) {
3454 haveResult = true;
3455 notifyAll();
3456 }
3457 pendingAssistExtrasTimedOut(this);
3458 }
3459 }
3460
3461 @Override
3462 public boolean isAssistDataAllowedOnCurrentActivity() {
3463 int userId;
3464 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003465 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3467 return false;
3468 }
3469
3470 final ActivityRecord activity = focusedStack.getTopActivity();
3471 if (activity == null) {
3472 return false;
3473 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003474 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 }
3476 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3477 }
3478
3479 @Override
3480 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3481 long ident = Binder.clearCallingIdentity();
3482 try {
3483 synchronized (mGlobalLock) {
3484 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003485 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003486 if (top != caller) {
3487 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3488 + " is not current top " + top);
3489 return false;
3490 }
3491 if (!top.nowVisible) {
3492 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3493 + " is not visible");
3494 return false;
3495 }
3496 }
3497 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3498 token);
3499 } finally {
3500 Binder.restoreCallingIdentity(ident);
3501 }
3502 }
3503
3504 @Override
3505 public boolean isRootVoiceInteraction(IBinder token) {
3506 synchronized (mGlobalLock) {
3507 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3508 if (r == null) {
3509 return false;
3510 }
3511 return r.rootVoiceInteraction;
3512 }
3513 }
3514
Wale Ogunwalef6733932018-06-27 05:14:34 -07003515 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3516 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3517 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3518 if (activityToCallback == null) return;
3519 activityToCallback.setVoiceSessionLocked(voiceSession);
3520
3521 // Inform the activity
3522 try {
3523 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3524 voiceInteractor);
3525 long token = Binder.clearCallingIdentity();
3526 try {
3527 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3528 } finally {
3529 Binder.restoreCallingIdentity(token);
3530 }
3531 // TODO: VI Should we cache the activity so that it's easier to find later
3532 // rather than scan through all the stacks and activities?
3533 } catch (RemoteException re) {
3534 activityToCallback.clearVoiceSessionLocked();
3535 // TODO: VI Should this terminate the voice session?
3536 }
3537 }
3538
3539 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3540 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3541 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3542 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3543 boolean wasRunningVoice = mRunningVoice != null;
3544 mRunningVoice = session;
3545 if (!wasRunningVoice) {
3546 mVoiceWakeLock.acquire();
3547 updateSleepIfNeededLocked();
3548 }
3549 }
3550 }
3551
3552 void finishRunningVoiceLocked() {
3553 if (mRunningVoice != null) {
3554 mRunningVoice = null;
3555 mVoiceWakeLock.release();
3556 updateSleepIfNeededLocked();
3557 }
3558 }
3559
3560 @Override
3561 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3562 synchronized (mGlobalLock) {
3563 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3564 if (keepAwake) {
3565 mVoiceWakeLock.acquire();
3566 } else {
3567 mVoiceWakeLock.release();
3568 }
3569 }
3570 }
3571 }
3572
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003573 @Override
3574 public ComponentName getActivityClassForToken(IBinder token) {
3575 synchronized (mGlobalLock) {
3576 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3577 if (r == null) {
3578 return null;
3579 }
3580 return r.intent.getComponent();
3581 }
3582 }
3583
3584 @Override
3585 public String getPackageForToken(IBinder token) {
3586 synchronized (mGlobalLock) {
3587 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3588 if (r == null) {
3589 return null;
3590 }
3591 return r.packageName;
3592 }
3593 }
3594
3595 @Override
3596 public void showLockTaskEscapeMessage(IBinder token) {
3597 synchronized (mGlobalLock) {
3598 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3599 if (r == null) {
3600 return;
3601 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003602 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 }
3604 }
3605
3606 @Override
3607 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003608 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 final long token = Binder.clearCallingIdentity();
3610 try {
3611 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003612 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003613 }
3614 } finally {
3615 Binder.restoreCallingIdentity(token);
3616 }
3617 }
3618
3619 /**
3620 * Try to place task to provided position. The final position might be different depending on
3621 * current user and stacks state. The task will be moved to target stack if it's currently in
3622 * different stack.
3623 */
3624 @Override
3625 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003626 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003627 synchronized (mGlobalLock) {
3628 long ident = Binder.clearCallingIdentity();
3629 try {
3630 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3631 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003632 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 if (task == null) {
3634 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3635 + taskId);
3636 }
3637
Wale Ogunwaled32da472018-11-16 07:19:28 -08003638 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639
3640 if (stack == null) {
3641 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3642 + stackId);
3643 }
3644 if (!stack.isActivityTypeStandardOrUndefined()) {
3645 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3646 + " the position of task " + taskId + " in/to non-standard stack");
3647 }
3648
3649 // TODO: Have the callers of this API call a separate reparent method if that is
3650 // what they intended to do vs. having this method also do reparenting.
3651 if (task.getStack() == stack) {
3652 // Change position in current stack.
3653 stack.positionChildAt(task, position);
3654 } else {
3655 // Reparent to new stack.
3656 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3657 !DEFER_RESUME, "positionTaskInStack");
3658 }
3659 } finally {
3660 Binder.restoreCallingIdentity(ident);
3661 }
3662 }
3663 }
3664
3665 @Override
3666 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3667 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3668 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3669 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3670 synchronized (mGlobalLock) {
3671 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3672 if (record == null) {
3673 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3674 + "found for: " + token);
3675 }
3676 record.setSizeConfigurations(horizontalSizeConfiguration,
3677 verticalSizeConfigurations, smallestSizeConfigurations);
3678 }
3679 }
3680
3681 /**
3682 * Dismisses split-screen multi-window mode.
3683 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3684 */
3685 @Override
3686 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003687 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003688 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3689 final long ident = Binder.clearCallingIdentity();
3690 try {
3691 synchronized (mGlobalLock) {
3692 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003693 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 if (stack == null) {
3695 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3696 return;
3697 }
3698
3699 if (toTop) {
3700 // Caller wants the current split-screen primary stack to be the top stack after
3701 // it goes fullscreen, so move it to the front.
3702 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003703 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003704 // In this case the current split-screen primary stack shouldn't be the top
3705 // stack after it goes fullscreen, but it current has focus, so we move the
3706 // focus to the top-most split-screen secondary stack next to it.
3707 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3708 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3709 if (otherStack != null) {
3710 otherStack.moveToFront("dismissSplitScreenMode_other");
3711 }
3712 }
3713
Evan Rosky10475742018-09-05 19:02:48 -07003714 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 }
3716 } finally {
3717 Binder.restoreCallingIdentity(ident);
3718 }
3719 }
3720
3721 /**
3722 * Dismisses Pip
3723 * @param animate True if the dismissal should be animated.
3724 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3725 * default animation duration should be used.
3726 */
3727 @Override
3728 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003729 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003730 final long ident = Binder.clearCallingIdentity();
3731 try {
3732 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003733 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003734 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 if (stack == null) {
3736 Slog.w(TAG, "dismissPip: pinned stack not found.");
3737 return;
3738 }
3739 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3740 throw new IllegalArgumentException("Stack: " + stack
3741 + " doesn't support animated resize.");
3742 }
3743 if (animate) {
3744 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3745 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3746 } else {
3747 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3748 }
3749 }
3750 } finally {
3751 Binder.restoreCallingIdentity(ident);
3752 }
3753 }
3754
3755 @Override
3756 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003757 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003758 synchronized (mGlobalLock) {
3759 mSuppressResizeConfigChanges = suppress;
3760 }
3761 }
3762
3763 /**
3764 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3765 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3766 * activity and clearing the task at the same time.
3767 */
3768 @Override
3769 // TODO: API should just be about changing windowing modes...
3770 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003771 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003772 "moveTasksToFullscreenStack()");
3773 synchronized (mGlobalLock) {
3774 final long origId = Binder.clearCallingIdentity();
3775 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003776 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003777 if (stack != null){
3778 if (!stack.isActivityTypeStandardOrUndefined()) {
3779 throw new IllegalArgumentException(
3780 "You can't move tasks from non-standard stacks.");
3781 }
3782 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3783 }
3784 } finally {
3785 Binder.restoreCallingIdentity(origId);
3786 }
3787 }
3788 }
3789
3790 /**
3791 * Moves the top activity in the input stackId to the pinned stack.
3792 *
3793 * @param stackId Id of stack to move the top activity to pinned stack.
3794 * @param bounds Bounds to use for pinned stack.
3795 *
3796 * @return True if the top activity of the input stack was successfully moved to the pinned
3797 * stack.
3798 */
3799 @Override
3800 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003801 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003802 "moveTopActivityToPinnedStack()");
3803 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003804 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003805 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3806 + "Device doesn't support picture-in-picture mode");
3807 }
3808
3809 long ident = Binder.clearCallingIdentity();
3810 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003811 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003812 } finally {
3813 Binder.restoreCallingIdentity(ident);
3814 }
3815 }
3816 }
3817
3818 @Override
3819 public boolean isInMultiWindowMode(IBinder token) {
3820 final long origId = Binder.clearCallingIdentity();
3821 try {
3822 synchronized (mGlobalLock) {
3823 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3824 if (r == null) {
3825 return false;
3826 }
3827 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3828 return r.inMultiWindowMode();
3829 }
3830 } finally {
3831 Binder.restoreCallingIdentity(origId);
3832 }
3833 }
3834
3835 @Override
3836 public boolean isInPictureInPictureMode(IBinder token) {
3837 final long origId = Binder.clearCallingIdentity();
3838 try {
3839 synchronized (mGlobalLock) {
3840 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3841 }
3842 } finally {
3843 Binder.restoreCallingIdentity(origId);
3844 }
3845 }
3846
3847 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003848 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3849 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 return false;
3851 }
3852
3853 // If we are animating to fullscreen then we have already dispatched the PIP mode
3854 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003855 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3856 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003857 }
3858
3859 @Override
3860 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3861 final long origId = Binder.clearCallingIdentity();
3862 try {
3863 synchronized (mGlobalLock) {
3864 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3865 "enterPictureInPictureMode", token, params);
3866
3867 // If the activity is already in picture in picture mode, then just return early
3868 if (isInPictureInPictureMode(r)) {
3869 return true;
3870 }
3871
3872 // Activity supports picture-in-picture, now check that we can enter PiP at this
3873 // point, if it is
3874 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3875 false /* beforeStopping */)) {
3876 return false;
3877 }
3878
3879 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003880 synchronized (mGlobalLock) {
3881 // Only update the saved args from the args that are set
3882 r.pictureInPictureArgs.copyOnlySet(params);
3883 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3884 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3885 // Adjust the source bounds by the insets for the transition down
3886 final Rect sourceBounds = new Rect(
3887 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003888 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003889 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003890 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003891 stack.setPictureInPictureAspectRatio(aspectRatio);
3892 stack.setPictureInPictureActions(actions);
3893 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3894 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3895 logPictureInPictureArgs(params);
3896 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003897 };
3898
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003899 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900 // If the keyguard is showing or occluded, then try and dismiss it before
3901 // entering picture-in-picture (this will prompt the user to authenticate if the
3902 // device is currently locked).
3903 dismissKeyguard(token, new KeyguardDismissCallback() {
3904 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003905 public void onDismissSucceeded() {
3906 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003907 }
3908 }, null /* message */);
3909 } else {
3910 // Enter picture in picture immediately otherwise
3911 enterPipRunnable.run();
3912 }
3913 return true;
3914 }
3915 } finally {
3916 Binder.restoreCallingIdentity(origId);
3917 }
3918 }
3919
3920 @Override
3921 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3922 final long origId = Binder.clearCallingIdentity();
3923 try {
3924 synchronized (mGlobalLock) {
3925 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3926 "setPictureInPictureParams", token, params);
3927
3928 // Only update the saved args from the args that are set
3929 r.pictureInPictureArgs.copyOnlySet(params);
3930 if (r.inPinnedWindowingMode()) {
3931 // If the activity is already in picture-in-picture, update the pinned stack now
3932 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3933 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003934 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 if (!stack.isAnimatingBoundsToFullscreen()) {
3936 stack.setPictureInPictureAspectRatio(
3937 r.pictureInPictureArgs.getAspectRatio());
3938 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3939 }
3940 }
3941 logPictureInPictureArgs(params);
3942 }
3943 } finally {
3944 Binder.restoreCallingIdentity(origId);
3945 }
3946 }
3947
3948 @Override
3949 public int getMaxNumPictureInPictureActions(IBinder token) {
3950 // Currently, this is a static constant, but later, we may change this to be dependent on
3951 // the context of the activity
3952 return 3;
3953 }
3954
3955 private void logPictureInPictureArgs(PictureInPictureParams params) {
3956 if (params.hasSetActions()) {
3957 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3958 params.getActions().size());
3959 }
3960 if (params.hasSetAspectRatio()) {
3961 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3962 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3963 MetricsLogger.action(lm);
3964 }
3965 }
3966
3967 /**
3968 * Checks the state of the system and the activity associated with the given {@param token} to
3969 * verify that picture-in-picture is supported for that activity.
3970 *
3971 * @return the activity record for the given {@param token} if all the checks pass.
3972 */
3973 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3974 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003975 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 throw new IllegalStateException(caller
3977 + ": Device doesn't support picture-in-picture mode.");
3978 }
3979
3980 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3981 if (r == null) {
3982 throw new IllegalStateException(caller
3983 + ": Can't find activity for token=" + token);
3984 }
3985
3986 if (!r.supportsPictureInPicture()) {
3987 throw new IllegalStateException(caller
3988 + ": Current activity does not support picture-in-picture.");
3989 }
3990
3991 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003992 && !mWindowManager.isValidPictureInPictureAspectRatio(
3993 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003994 final float minAspectRatio = mContext.getResources().getFloat(
3995 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3996 final float maxAspectRatio = mContext.getResources().getFloat(
3997 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3998 throw new IllegalArgumentException(String.format(caller
3999 + ": Aspect ratio is too extreme (must be between %f and %f).",
4000 minAspectRatio, maxAspectRatio));
4001 }
4002
4003 // Truncate the number of actions if necessary
4004 params.truncateActions(getMaxNumPictureInPictureActions(token));
4005
4006 return r;
4007 }
4008
4009 @Override
4010 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004011 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 synchronized (mGlobalLock) {
4013 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4014 if (r == null) {
4015 throw new IllegalArgumentException("Activity does not exist; token="
4016 + activityToken);
4017 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004018 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 }
4020 }
4021
4022 @Override
4023 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4024 Rect tempDockedTaskInsetBounds,
4025 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004026 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 long ident = Binder.clearCallingIdentity();
4028 try {
4029 synchronized (mGlobalLock) {
4030 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4031 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4032 PRESERVE_WINDOWS);
4033 }
4034 } finally {
4035 Binder.restoreCallingIdentity(ident);
4036 }
4037 }
4038
4039 @Override
4040 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 final long ident = Binder.clearCallingIdentity();
4043 try {
4044 synchronized (mGlobalLock) {
4045 mStackSupervisor.setSplitScreenResizing(resizing);
4046 }
4047 } finally {
4048 Binder.restoreCallingIdentity(ident);
4049 }
4050 }
4051
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 /**
4053 * Check that we have the features required for VR-related API calls, and throw an exception if
4054 * not.
4055 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004056 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004057 if (!mContext.getPackageManager().hasSystemFeature(
4058 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4059 throw new UnsupportedOperationException("VR mode not supported on this device!");
4060 }
4061 }
4062
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 @Override
4064 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004065 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004066
4067 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4068
4069 ActivityRecord r;
4070 synchronized (mGlobalLock) {
4071 r = ActivityRecord.isInStackLocked(token);
4072 }
4073
4074 if (r == null) {
4075 throw new IllegalArgumentException();
4076 }
4077
4078 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004079 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 VrManagerInternal.NO_ERROR) {
4081 return err;
4082 }
4083
4084 // Clear the binder calling uid since this path may call moveToTask().
4085 final long callingId = Binder.clearCallingIdentity();
4086 try {
4087 synchronized (mGlobalLock) {
4088 r.requestedVrComponent = (enabled) ? packageName : null;
4089
4090 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004091 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004092 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093 }
4094 return 0;
4095 }
4096 } finally {
4097 Binder.restoreCallingIdentity(callingId);
4098 }
4099 }
4100
4101 @Override
4102 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4103 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4104 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004105 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004106 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4107 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4108 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004109 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004110 || activity.voiceSession != null) {
4111 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4112 return;
4113 }
4114 if (activity.pendingVoiceInteractionStart) {
4115 Slog.w(TAG, "Pending start of voice interaction already.");
4116 return;
4117 }
4118 activity.pendingVoiceInteractionStart = true;
4119 }
4120 LocalServices.getService(VoiceInteractionManagerInternal.class)
4121 .startLocalVoiceInteraction(callingActivity, options);
4122 }
4123
4124 @Override
4125 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4126 LocalServices.getService(VoiceInteractionManagerInternal.class)
4127 .stopLocalVoiceInteraction(callingActivity);
4128 }
4129
4130 @Override
4131 public boolean supportsLocalVoiceInteraction() {
4132 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4133 .supportsLocalVoiceInteraction();
4134 }
4135
4136 /** Notifies all listeners when the pinned stack animation starts. */
4137 @Override
4138 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004139 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 }
4141
4142 /** Notifies all listeners when the pinned stack animation ends. */
4143 @Override
4144 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004145 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146 }
4147
4148 @Override
4149 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004150 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 final long ident = Binder.clearCallingIdentity();
4152 try {
4153 synchronized (mGlobalLock) {
4154 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4155 }
4156 } finally {
4157 Binder.restoreCallingIdentity(ident);
4158 }
4159 }
4160
4161 @Override
4162 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004163 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164
4165 synchronized (mGlobalLock) {
4166 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004167 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 // Call might come when display is not yet added or has already been removed.
4169 if (DEBUG_CONFIGURATION) {
4170 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4171 + displayId);
4172 }
4173 return false;
4174 }
4175
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004176 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004178 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004179 }
4180
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004181 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004182 final Message msg = PooledLambda.obtainMessage(
4183 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4184 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 }
4186
4187 final long origId = Binder.clearCallingIdentity();
4188 try {
4189 if (values != null) {
4190 Settings.System.clearConfiguration(values);
4191 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4194 return mTmpUpdateConfigurationResult.changes != 0;
4195 } finally {
4196 Binder.restoreCallingIdentity(origId);
4197 }
4198 }
4199 }
4200
4201 @Override
4202 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004203 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204
4205 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 }
4210
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004211 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004212 final Message msg = PooledLambda.obtainMessage(
4213 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4214 DEFAULT_DISPLAY);
4215 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004216 }
4217
4218 final long origId = Binder.clearCallingIdentity();
4219 try {
4220 if (values != null) {
4221 Settings.System.clearConfiguration(values);
4222 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004223 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 UserHandle.USER_NULL, false /* deferResume */,
4225 mTmpUpdateConfigurationResult);
4226 return mTmpUpdateConfigurationResult.changes != 0;
4227 } finally {
4228 Binder.restoreCallingIdentity(origId);
4229 }
4230 }
4231 }
4232
4233 @Override
4234 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4235 CharSequence message) {
4236 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004237 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4239 }
4240 final long callingId = Binder.clearCallingIdentity();
4241 try {
4242 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004243 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 }
4245 } finally {
4246 Binder.restoreCallingIdentity(callingId);
4247 }
4248 }
4249
4250 @Override
4251 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 "cancelTaskWindowTransition()");
4254 final long ident = Binder.clearCallingIdentity();
4255 try {
4256 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004257 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 MATCH_TASK_IN_STACKS_ONLY);
4259 if (task == null) {
4260 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4261 return;
4262 }
4263 task.cancelWindowTransition();
4264 }
4265 } finally {
4266 Binder.restoreCallingIdentity(ident);
4267 }
4268 }
4269
4270 @Override
4271 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004272 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004273 final long ident = Binder.clearCallingIdentity();
4274 try {
4275 final TaskRecord task;
4276 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004277 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004278 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4279 if (task == null) {
4280 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4281 return null;
4282 }
4283 }
4284 // Don't call this while holding the lock as this operation might hit the disk.
4285 return task.getSnapshot(reducedResolution);
4286 } finally {
4287 Binder.restoreCallingIdentity(ident);
4288 }
4289 }
4290
4291 @Override
4292 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4293 synchronized (mGlobalLock) {
4294 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4295 if (r == null) {
4296 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4297 + token);
4298 return;
4299 }
4300 final long origId = Binder.clearCallingIdentity();
4301 try {
4302 r.setDisablePreviewScreenshots(disable);
4303 } finally {
4304 Binder.restoreCallingIdentity(origId);
4305 }
4306 }
4307 }
4308
4309 /** Return the user id of the last resumed activity. */
4310 @Override
4311 public @UserIdInt
4312 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004313 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4315 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004316 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004317 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004319 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004320 }
4321 }
4322
4323 @Override
4324 public void updateLockTaskFeatures(int userId, int flags) {
4325 final int callingUid = Binder.getCallingUid();
4326 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004327 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 "updateLockTaskFeatures()");
4329 }
4330 synchronized (mGlobalLock) {
4331 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4332 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004333 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 }
4335 }
4336
4337 @Override
4338 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4339 synchronized (mGlobalLock) {
4340 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4341 if (r == null) {
4342 return;
4343 }
4344 final long origId = Binder.clearCallingIdentity();
4345 try {
4346 r.setShowWhenLocked(showWhenLocked);
4347 } finally {
4348 Binder.restoreCallingIdentity(origId);
4349 }
4350 }
4351 }
4352
4353 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004354 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4355 synchronized (mGlobalLock) {
4356 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4357 if (r == null) {
4358 return;
4359 }
4360 final long origId = Binder.clearCallingIdentity();
4361 try {
4362 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4363 } finally {
4364 Binder.restoreCallingIdentity(origId);
4365 }
4366 }
4367 }
4368
4369 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4371 synchronized (mGlobalLock) {
4372 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4373 if (r == null) {
4374 return;
4375 }
4376 final long origId = Binder.clearCallingIdentity();
4377 try {
4378 r.setTurnScreenOn(turnScreenOn);
4379 } finally {
4380 Binder.restoreCallingIdentity(origId);
4381 }
4382 }
4383 }
4384
4385 @Override
4386 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 "registerRemoteAnimations");
4389 definition.setCallingPid(Binder.getCallingPid());
4390 synchronized (mGlobalLock) {
4391 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4392 if (r == null) {
4393 return;
4394 }
4395 final long origId = Binder.clearCallingIdentity();
4396 try {
4397 r.registerRemoteAnimations(definition);
4398 } finally {
4399 Binder.restoreCallingIdentity(origId);
4400 }
4401 }
4402 }
4403
4404 @Override
4405 public void registerRemoteAnimationForNextActivityStart(String packageName,
4406 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004407 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 "registerRemoteAnimationForNextActivityStart");
4409 adapter.setCallingPid(Binder.getCallingPid());
4410 synchronized (mGlobalLock) {
4411 final long origId = Binder.clearCallingIdentity();
4412 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004413 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 packageName, adapter);
4415 } finally {
4416 Binder.restoreCallingIdentity(origId);
4417 }
4418 }
4419 }
4420
Evan Rosky966759f2019-01-15 10:33:58 -08004421 @Override
4422 public void registerRemoteAnimationsForDisplay(int displayId,
4423 RemoteAnimationDefinition definition) {
4424 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4425 "registerRemoteAnimations");
4426 definition.setCallingPid(Binder.getCallingPid());
4427 synchronized (mGlobalLock) {
4428 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4429 if (display == null) {
4430 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4431 return;
4432 }
4433 final long origId = Binder.clearCallingIdentity();
4434 try {
4435 display.mDisplayContent.registerRemoteAnimations(definition);
4436 } finally {
4437 Binder.restoreCallingIdentity(origId);
4438 }
4439 }
4440 }
4441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4443 @Override
4444 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4445 synchronized (mGlobalLock) {
4446 final long origId = Binder.clearCallingIdentity();
4447 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004448 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449 } finally {
4450 Binder.restoreCallingIdentity(origId);
4451 }
4452 }
4453 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004454
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004455 @Override
4456 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004458 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004459 final int pid = Binder.getCallingPid();
4460 final WindowProcessController wpc = mPidMap.get(pid);
4461 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004462 }
4463 }
4464
4465 @Override
4466 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004468 != PERMISSION_GRANTED) {
4469 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4470 + Binder.getCallingPid()
4471 + ", uid=" + Binder.getCallingUid()
4472 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4473 Slog.w(TAG, msg);
4474 throw new SecurityException(msg);
4475 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004476 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004477 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004478 final int pid = Binder.getCallingPid();
4479 final WindowProcessController proc = mPidMap.get(pid);
4480 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004481 }
4482 }
4483
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004484 @Override
4485 public void stopAppSwitches() {
4486 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4487 synchronized (mGlobalLock) {
4488 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4489 mDidAppSwitch = false;
4490 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4491 }
4492 }
4493
4494 @Override
4495 public void resumeAppSwitches() {
4496 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4497 synchronized (mGlobalLock) {
4498 // Note that we don't execute any pending app switches... we will
4499 // let those wait until either the timeout, or the next start
4500 // activity request.
4501 mAppSwitchesAllowedTime = 0;
4502 }
4503 }
4504
4505 void onStartActivitySetDidAppSwitch() {
4506 if (mDidAppSwitch) {
4507 // This is the second allowed switch since we stopped switches, so now just generally
4508 // allow switches. Use case:
4509 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4510 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4511 // anyone to switch again).
4512 mAppSwitchesAllowedTime = 0;
4513 } else {
4514 mDidAppSwitch = true;
4515 }
4516 }
4517
4518 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004519 boolean shouldDisableNonVrUiLocked() {
4520 return mVrController.shouldDisableNonVrUiLocked();
4521 }
4522
Wale Ogunwale53783742018-09-16 10:21:51 -07004523 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004524 // VR apps are expected to run in a main display. If an app is turning on VR for
4525 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4526 // fullscreen stack before enabling VR Mode.
4527 // TODO: The goal of this code is to keep the VR app on the main display. When the
4528 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4529 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4530 // option would be a better choice here.
4531 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4532 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4533 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004534 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004535 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004536 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004537 }
4538 mH.post(() -> {
4539 if (!mVrController.onVrModeChanged(r)) {
4540 return;
4541 }
4542 synchronized (mGlobalLock) {
4543 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4544 mWindowManager.disableNonVrUi(disableNonVrUi);
4545 if (disableNonVrUi) {
4546 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4547 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004548 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004549 }
4550 }
4551 });
4552 }
4553
Wale Ogunwale53783742018-09-16 10:21:51 -07004554 @Override
4555 public int getPackageScreenCompatMode(String packageName) {
4556 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4557 synchronized (mGlobalLock) {
4558 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4559 }
4560 }
4561
4562 @Override
4563 public void setPackageScreenCompatMode(String packageName, int mode) {
4564 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4565 "setPackageScreenCompatMode");
4566 synchronized (mGlobalLock) {
4567 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4568 }
4569 }
4570
4571 @Override
4572 public boolean getPackageAskScreenCompat(String packageName) {
4573 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4574 synchronized (mGlobalLock) {
4575 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4576 }
4577 }
4578
4579 @Override
4580 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4581 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4582 "setPackageAskScreenCompat");
4583 synchronized (mGlobalLock) {
4584 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4585 }
4586 }
4587
Wale Ogunwale64258362018-10-16 15:13:37 -07004588 public static String relaunchReasonToString(int relaunchReason) {
4589 switch (relaunchReason) {
4590 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4591 return "window_resize";
4592 case RELAUNCH_REASON_FREE_RESIZE:
4593 return "free_resize";
4594 default:
4595 return null;
4596 }
4597 }
4598
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004599 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004600 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004601 }
4602
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004603 /** Pokes the task persister. */
4604 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4605 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4606 }
4607
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004608 boolean isKeyguardLocked() {
4609 return mKeyguardController.isKeyguardLocked();
4610 }
4611
Garfield Tan01548632018-11-27 10:15:48 -08004612 /**
4613 * Clears launch params for the given package.
4614 * @param packageNames the names of the packages of which the launch params are to be cleared
4615 */
4616 @Override
4617 public void clearLaunchParamsForPackages(List<String> packageNames) {
4618 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4619 "clearLaunchParamsForPackages");
4620 synchronized (mGlobalLock) {
4621 for (int i = 0; i < packageNames.size(); ++i) {
4622 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4623 }
4624 }
4625 }
4626
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004627 /**
4628 * Makes the display with the given id a single task instance display. I.e the display can only
4629 * contain one task.
4630 */
4631 @Override
4632 public void setDisplayToSingleTaskInstance(int displayId) {
4633 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4634 "setDisplayToSingleTaskInstance");
4635 final long origId = Binder.clearCallingIdentity();
4636 try {
4637 final ActivityDisplay display =
4638 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4639 if (display != null) {
4640 display.setDisplayToSingleTaskInstance();
4641 }
4642 } finally {
4643 Binder.restoreCallingIdentity(origId);
4644 }
4645 }
4646
Wale Ogunwale31913b52018-10-13 08:29:31 -07004647 void dumpLastANRLocked(PrintWriter pw) {
4648 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4649 if (mLastANRState == null) {
4650 pw.println(" <no ANR has occurred since boot>");
4651 } else {
4652 pw.println(mLastANRState);
4653 }
4654 }
4655
4656 void dumpLastANRTracesLocked(PrintWriter pw) {
4657 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4658
4659 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4660 if (ArrayUtils.isEmpty(files)) {
4661 pw.println(" <no ANR has occurred since boot>");
4662 return;
4663 }
4664 // Find the latest file.
4665 File latest = null;
4666 for (File f : files) {
4667 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4668 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004669 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004670 }
4671 pw.print("File: ");
4672 pw.print(latest.getName());
4673 pw.println();
4674 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4675 String line;
4676 while ((line = in.readLine()) != null) {
4677 pw.println(line);
4678 }
4679 } catch (IOException e) {
4680 pw.print("Unable to read: ");
4681 pw.print(e);
4682 pw.println();
4683 }
4684 }
4685
4686 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4687 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4688 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4689 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4690 }
4691
4692 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4693 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4694 pw.println(header);
4695
Wale Ogunwaled32da472018-11-16 07:19:28 -08004696 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004697 dumpPackage);
4698 boolean needSep = printedAnything;
4699
4700 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004701 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004702 " ResumedActivity: ");
4703 if (printed) {
4704 printedAnything = true;
4705 needSep = false;
4706 }
4707
4708 if (dumpPackage == null) {
4709 if (needSep) {
4710 pw.println();
4711 }
4712 printedAnything = true;
4713 mStackSupervisor.dump(pw, " ");
4714 }
4715
4716 if (!printedAnything) {
4717 pw.println(" (nothing)");
4718 }
4719 }
4720
4721 void dumpActivityContainersLocked(PrintWriter pw) {
4722 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004723 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004724 pw.println(" ");
4725 }
4726
4727 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4728 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4729 getActivityStartController().dump(pw, "", dumpPackage);
4730 }
4731
4732 /**
4733 * There are three things that cmd can be:
4734 * - a flattened component name that matches an existing activity
4735 * - the cmd arg isn't the flattened component name of an existing activity:
4736 * dump all activity whose component contains the cmd as a substring
4737 * - A hex number of the ActivityRecord object instance.
4738 *
4739 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4740 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4741 */
4742 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4743 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4744 ArrayList<ActivityRecord> activities;
4745
4746 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004747 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004748 dumpFocusedStackOnly);
4749 }
4750
4751 if (activities.size() <= 0) {
4752 return false;
4753 }
4754
4755 String[] newArgs = new String[args.length - opti];
4756 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4757
4758 TaskRecord lastTask = null;
4759 boolean needSep = false;
4760 for (int i = activities.size() - 1; i >= 0; i--) {
4761 ActivityRecord r = activities.get(i);
4762 if (needSep) {
4763 pw.println();
4764 }
4765 needSep = true;
4766 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004767 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004768 if (lastTask != task) {
4769 lastTask = task;
4770 pw.print("TASK "); pw.print(lastTask.affinity);
4771 pw.print(" id="); pw.print(lastTask.taskId);
4772 pw.print(" userId="); pw.println(lastTask.userId);
4773 if (dumpAll) {
4774 lastTask.dump(pw, " ");
4775 }
4776 }
4777 }
4778 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4779 }
4780 return true;
4781 }
4782
4783 /**
4784 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4785 * there is a thread associated with the activity.
4786 */
4787 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4788 final ActivityRecord r, String[] args, boolean dumpAll) {
4789 String innerPrefix = prefix + " ";
4790 synchronized (mGlobalLock) {
4791 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4792 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4793 pw.print(" pid=");
4794 if (r.hasProcess()) pw.println(r.app.getPid());
4795 else pw.println("(not running)");
4796 if (dumpAll) {
4797 r.dump(pw, innerPrefix);
4798 }
4799 }
4800 if (r.attachedToProcess()) {
4801 // flush anything that is already in the PrintWriter since the thread is going
4802 // to write to the file descriptor directly
4803 pw.flush();
4804 try {
4805 TransferPipe tp = new TransferPipe();
4806 try {
4807 r.app.getThread().dumpActivity(tp.getWriteFd(),
4808 r.appToken, innerPrefix, args);
4809 tp.go(fd);
4810 } finally {
4811 tp.kill();
4812 }
4813 } catch (IOException e) {
4814 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4815 } catch (RemoteException e) {
4816 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4817 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004818 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004819 }
4820
sanryhuang498e77e2018-12-06 14:57:01 +08004821 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4822 boolean testPssMode) {
4823 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4824 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4825 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004826 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004827 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4828 st.toString());
4829 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004830 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4831 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4832 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004833 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4834 testPssMode);
4835 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004836 }
4837
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004838 int getCurrentUserId() {
4839 return mAmInternal.getCurrentUserId();
4840 }
4841
4842 private void enforceNotIsolatedCaller(String caller) {
4843 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4844 throw new SecurityException("Isolated process not allowed to call " + caller);
4845 }
4846 }
4847
Wale Ogunwalef6733932018-06-27 05:14:34 -07004848 public Configuration getConfiguration() {
4849 Configuration ci;
4850 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004851 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004852 ci.userSetLocale = false;
4853 }
4854 return ci;
4855 }
4856
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004857 /**
4858 * Current global configuration information. Contains general settings for the entire system,
4859 * also corresponds to the merged configuration of the default display.
4860 */
4861 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004862 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004863 }
4864
4865 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4866 boolean initLocale) {
4867 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4868 }
4869
4870 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4871 boolean initLocale, boolean deferResume) {
4872 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4873 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4874 UserHandle.USER_NULL, deferResume);
4875 }
4876
Wale Ogunwale59507092018-10-29 09:00:30 -07004877 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004878 final long origId = Binder.clearCallingIdentity();
4879 try {
4880 synchronized (mGlobalLock) {
4881 updateConfigurationLocked(values, null, false, true, userId,
4882 false /* deferResume */);
4883 }
4884 } finally {
4885 Binder.restoreCallingIdentity(origId);
4886 }
4887 }
4888
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004889 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4890 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4891 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4892 deferResume, null /* result */);
4893 }
4894
4895 /**
4896 * Do either or both things: (1) change the current configuration, and (2)
4897 * make sure the given activity is running with the (now) current
4898 * configuration. Returns true if the activity has been left running, or
4899 * false if <var>starting</var> is being destroyed to match the new
4900 * configuration.
4901 *
4902 * @param userId is only used when persistent parameter is set to true to persist configuration
4903 * for that particular user
4904 */
4905 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4906 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4907 ActivityTaskManagerService.UpdateConfigurationResult result) {
4908 int changes = 0;
4909 boolean kept = true;
4910
4911 if (mWindowManager != null) {
4912 mWindowManager.deferSurfaceLayout();
4913 }
4914 try {
4915 if (values != null) {
4916 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4917 deferResume);
4918 }
4919
4920 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4921 } finally {
4922 if (mWindowManager != null) {
4923 mWindowManager.continueSurfaceLayout();
4924 }
4925 }
4926
4927 if (result != null) {
4928 result.changes = changes;
4929 result.activityRelaunched = !kept;
4930 }
4931 return kept;
4932 }
4933
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004934 /** Update default (global) configuration and notify listeners about changes. */
4935 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4936 boolean persistent, int userId, boolean deferResume) {
4937 mTempConfig.setTo(getGlobalConfiguration());
4938 final int changes = mTempConfig.updateFrom(values);
4939 if (changes == 0) {
4940 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4941 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4942 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4943 // (even if there are no actual changes) to unfreeze the window.
4944 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4945 return 0;
4946 }
4947
4948 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4949 "Updating global configuration to: " + values);
4950
4951 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4952 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4953 values.colorMode,
4954 values.densityDpi,
4955 values.fontScale,
4956 values.hardKeyboardHidden,
4957 values.keyboard,
4958 values.keyboardHidden,
4959 values.mcc,
4960 values.mnc,
4961 values.navigation,
4962 values.navigationHidden,
4963 values.orientation,
4964 values.screenHeightDp,
4965 values.screenLayout,
4966 values.screenWidthDp,
4967 values.smallestScreenWidthDp,
4968 values.touchscreen,
4969 values.uiMode);
4970
4971
4972 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4973 final LocaleList locales = values.getLocales();
4974 int bestLocaleIndex = 0;
4975 if (locales.size() > 1) {
4976 if (mSupportedSystemLocales == null) {
4977 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4978 }
4979 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4980 }
4981 SystemProperties.set("persist.sys.locale",
4982 locales.get(bestLocaleIndex).toLanguageTag());
4983 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004984
4985 final Message m = PooledLambda.obtainMessage(
4986 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4987 locales.get(bestLocaleIndex));
4988 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004989 }
4990
Yunfan Chen75157d72018-07-27 14:47:21 +09004991 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004992
4993 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004994 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004995
4996 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4997 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004998 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004999
5000 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005002
5003 AttributeCache ac = AttributeCache.instance();
5004 if (ac != null) {
5005 ac.updateConfiguration(mTempConfig);
5006 }
5007
5008 // Make sure all resources in our process are updated right now, so that anyone who is going
5009 // to retrieve resource values after we return will be sure to get the new ones. This is
5010 // especially important during boot, where the first config change needs to guarantee all
5011 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005012 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005013
5014 // We need another copy of global config because we're scheduling some calls instead of
5015 // running them in place. We need to be sure that object we send will be handled unchanged.
5016 final Configuration configCopy = new Configuration(mTempConfig);
5017 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005018 final Message msg = PooledLambda.obtainMessage(
5019 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5020 this, userId, configCopy);
5021 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005022 }
5023
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005024 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005025 final int pid = mPidMap.keyAt(i);
5026 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005027 if (DEBUG_CONFIGURATION) {
5028 Slog.v(TAG_CONFIGURATION, "Update process config of "
5029 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005030 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005031 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005032 }
5033
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005034 final Message msg = PooledLambda.obtainMessage(
5035 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5036 mAmInternal, changes, initLocale);
5037 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005038
5039 // Override configuration of the default display duplicates global config, so we need to
5040 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005041 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005042 DEFAULT_DISPLAY);
5043
5044 return changes;
5045 }
5046
5047 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5048 boolean deferResume, int displayId) {
5049 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5050 displayId, null /* result */);
5051 }
5052
5053 /**
5054 * Updates override configuration specific for the selected display. If no config is provided,
5055 * new one will be computed in WM based on current display info.
5056 */
5057 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5058 ActivityRecord starting, boolean deferResume, int displayId,
5059 ActivityTaskManagerService.UpdateConfigurationResult result) {
5060 int changes = 0;
5061 boolean kept = true;
5062
5063 if (mWindowManager != null) {
5064 mWindowManager.deferSurfaceLayout();
5065 }
5066 try {
5067 if (values != null) {
5068 if (displayId == DEFAULT_DISPLAY) {
5069 // Override configuration of the default display duplicates global config, so
5070 // we're calling global config update instead for default display. It will also
5071 // apply the correct override config.
5072 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5073 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5074 } else {
5075 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5076 }
5077 }
5078
5079 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5080 } finally {
5081 if (mWindowManager != null) {
5082 mWindowManager.continueSurfaceLayout();
5083 }
5084 }
5085
5086 if (result != null) {
5087 result.changes = changes;
5088 result.activityRelaunched = !kept;
5089 }
5090 return kept;
5091 }
5092
5093 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5094 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005095 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005096 final int changes = mTempConfig.updateFrom(values);
5097 if (changes != 0) {
5098 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5099 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005100 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005101
5102 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5103 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005104 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105
Wale Ogunwale5c918702018-10-18 11:06:33 -07005106 // Post message to start process to avoid possible deadlock of calling into AMS with
5107 // the ATMS lock held.
5108 final Message msg = PooledLambda.obtainMessage(
5109 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5110 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5111 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005112 }
5113 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005114 return changes;
5115 }
5116
Wale Ogunwalef6733932018-06-27 05:14:34 -07005117 private void updateEventDispatchingLocked(boolean booted) {
5118 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5119 }
5120
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005121 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5122 final ContentResolver resolver = mContext.getContentResolver();
5123 Settings.System.putConfigurationForUser(resolver, config, userId);
5124 }
5125
5126 private void sendLocaleToMountDaemonMsg(Locale l) {
5127 try {
5128 IBinder service = ServiceManager.getService("mount");
5129 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5130 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5131 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5132 } catch (RemoteException e) {
5133 Log.e(TAG, "Error storing locale for decryption UI", e);
5134 }
5135 }
5136
Alison Cichowlas3e340502018-08-07 17:15:01 -04005137 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5138 mStartActivitySources.remove(permissionToken);
5139 mExpiredStartAsCallerTokens.add(permissionToken);
5140 }
5141
5142 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5143 mExpiredStartAsCallerTokens.remove(permissionToken);
5144 }
5145
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005146 boolean isActivityStartsLoggingEnabled() {
5147 return mAmInternal.isActivityStartsLoggingEnabled();
5148 }
5149
Michal Karpinski8596ded2018-11-14 14:43:48 +00005150 boolean isBackgroundActivityStartsEnabled() {
5151 return mAmInternal.isBackgroundActivityStartsEnabled();
5152 }
5153
Wale Ogunwalef6733932018-06-27 05:14:34 -07005154 void enableScreenAfterBoot(boolean booted) {
5155 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5156 SystemClock.uptimeMillis());
5157 mWindowManager.enableScreenAfterBoot();
5158
5159 synchronized (mGlobalLock) {
5160 updateEventDispatchingLocked(booted);
5161 }
5162 }
5163
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005164 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5165 if (r == null || !r.hasProcess()) {
5166 return KEY_DISPATCHING_TIMEOUT_MS;
5167 }
5168 return getInputDispatchingTimeoutLocked(r.app);
5169 }
5170
5171 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005172 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005173 }
5174
Wale Ogunwalef6733932018-06-27 05:14:34 -07005175 /**
5176 * Decide based on the configuration whether we should show the ANR,
5177 * crash, etc dialogs. The idea is that if there is no affordance to
5178 * press the on-screen buttons, or the user experience would be more
5179 * greatly impacted than the crash itself, we shouldn't show the dialog.
5180 *
5181 * A thought: SystemUI might also want to get told about this, the Power
5182 * dialog / global actions also might want different behaviors.
5183 */
5184 private void updateShouldShowDialogsLocked(Configuration config) {
5185 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5186 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5187 && config.navigation == Configuration.NAVIGATION_NONAV);
5188 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5189 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5190 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5191 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5192 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5193 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5194 HIDE_ERROR_DIALOGS, 0) != 0;
5195 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5196 }
5197
5198 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5199 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5200 FONT_SCALE, 1.0f, userId);
5201
5202 synchronized (this) {
5203 if (getGlobalConfiguration().fontScale == scaleFactor) {
5204 return;
5205 }
5206
5207 final Configuration configuration
5208 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5209 configuration.fontScale = scaleFactor;
5210 updatePersistentConfiguration(configuration, userId);
5211 }
5212 }
5213
5214 // Actually is sleeping or shutting down or whatever else in the future
5215 // is an inactive state.
5216 boolean isSleepingOrShuttingDownLocked() {
5217 return isSleepingLocked() || mShuttingDown;
5218 }
5219
5220 boolean isSleepingLocked() {
5221 return mSleeping;
5222 }
5223
Riddle Hsu16567132018-08-16 21:37:47 +08005224 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005225 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005226 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005227 if (task.isActivityTypeStandard()) {
5228 if (mCurAppTimeTracker != r.appTimeTracker) {
5229 // We are switching app tracking. Complete the current one.
5230 if (mCurAppTimeTracker != null) {
5231 mCurAppTimeTracker.stop();
5232 mH.obtainMessage(
5233 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005234 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005235 mCurAppTimeTracker = null;
5236 }
5237 if (r.appTimeTracker != null) {
5238 mCurAppTimeTracker = r.appTimeTracker;
5239 startTimeTrackingFocusedActivityLocked();
5240 }
5241 } else {
5242 startTimeTrackingFocusedActivityLocked();
5243 }
5244 } else {
5245 r.appTimeTracker = null;
5246 }
5247 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5248 // TODO: Probably not, because we don't want to resume voice on switching
5249 // back to this activity
5250 if (task.voiceInteractor != null) {
5251 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5252 } else {
5253 finishRunningVoiceLocked();
5254
5255 if (mLastResumedActivity != null) {
5256 final IVoiceInteractionSession session;
5257
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005258 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005259 if (lastResumedActivityTask != null
5260 && lastResumedActivityTask.voiceSession != null) {
5261 session = lastResumedActivityTask.voiceSession;
5262 } else {
5263 session = mLastResumedActivity.voiceSession;
5264 }
5265
5266 if (session != null) {
5267 // We had been in a voice interaction session, but now focused has
5268 // move to something different. Just finish the session, we can't
5269 // return to it and retain the proper state and synchronization with
5270 // the voice interaction service.
5271 finishVoiceTask(session);
5272 }
5273 }
5274 }
5275
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005276 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5277 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 }
5279 updateResumedAppTrace(r);
5280 mLastResumedActivity = r;
5281
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005282 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005283
5284 applyUpdateLockStateLocked(r);
5285 applyUpdateVrModeLocked(r);
5286
5287 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005288 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005289 r == null ? "NULL" : r.shortComponentName,
5290 reason);
5291 }
5292
5293 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5294 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005295 final ActivityTaskManagerInternal.SleepToken token =
5296 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 updateSleepIfNeededLocked();
5298 return token;
5299 }
5300 }
5301
5302 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005303 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005304 final boolean wasSleeping = mSleeping;
5305 boolean updateOomAdj = false;
5306
5307 if (!shouldSleep) {
5308 // If wasSleeping is true, we need to wake up activity manager state from when
5309 // we started sleeping. In either case, we need to apply the sleep tokens, which
5310 // will wake up stacks or put them to sleep as appropriate.
5311 if (wasSleeping) {
5312 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005313 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5314 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005315 startTimeTrackingFocusedActivityLocked();
5316 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5317 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5318 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005319 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005320 if (wasSleeping) {
5321 updateOomAdj = true;
5322 }
5323 } else if (!mSleeping && shouldSleep) {
5324 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005325 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5326 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005327 if (mCurAppTimeTracker != null) {
5328 mCurAppTimeTracker.stop();
5329 }
5330 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5331 mStackSupervisor.goingToSleepLocked();
5332 updateResumedAppTrace(null /* resumed */);
5333 updateOomAdj = true;
5334 }
5335 if (updateOomAdj) {
5336 mH.post(mAmInternal::updateOomAdj);
5337 }
5338 }
5339
5340 void updateOomAdj() {
5341 mH.post(mAmInternal::updateOomAdj);
5342 }
5343
Wale Ogunwale53783742018-09-16 10:21:51 -07005344 void updateCpuStats() {
5345 mH.post(mAmInternal::updateCpuStats);
5346 }
5347
Hui Yu03d12402018-12-06 18:00:37 -08005348 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5349 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005350 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5351 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005352 mH.sendMessage(m);
5353 }
5354
Hui Yu03d12402018-12-06 18:00:37 -08005355 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005356 ComponentName taskRoot = null;
5357 final TaskRecord task = activity.getTaskRecord();
5358 if (task != null) {
5359 final ActivityRecord rootActivity = task.getRootActivity();
5360 if (rootActivity != null) {
5361 taskRoot = rootActivity.mActivityComponent;
5362 }
5363 }
5364
Hui Yu03d12402018-12-06 18:00:37 -08005365 final Message m = PooledLambda.obtainMessage(
5366 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005367 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005368 mH.sendMessage(m);
5369 }
5370
Wale Ogunwale53783742018-09-16 10:21:51 -07005371 void setBooting(boolean booting) {
5372 mAmInternal.setBooting(booting);
5373 }
5374
5375 boolean isBooting() {
5376 return mAmInternal.isBooting();
5377 }
5378
5379 void setBooted(boolean booted) {
5380 mAmInternal.setBooted(booted);
5381 }
5382
5383 boolean isBooted() {
5384 return mAmInternal.isBooted();
5385 }
5386
5387 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5388 mH.post(() -> {
5389 if (finishBooting) {
5390 mAmInternal.finishBooting();
5391 }
5392 if (enableScreen) {
5393 mInternal.enableScreenAfterBoot(isBooted());
5394 }
5395 });
5396 }
5397
5398 void setHeavyWeightProcess(ActivityRecord root) {
5399 mHeavyWeightProcess = root.app;
5400 final Message m = PooledLambda.obtainMessage(
5401 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005402 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005403 mH.sendMessage(m);
5404 }
5405
5406 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5407 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5408 return;
5409 }
5410
5411 mHeavyWeightProcess = null;
5412 final Message m = PooledLambda.obtainMessage(
5413 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5414 proc.mUserId);
5415 mH.sendMessage(m);
5416 }
5417
5418 private void cancelHeavyWeightProcessNotification(int userId) {
5419 final INotificationManager inm = NotificationManager.getService();
5420 if (inm == null) {
5421 return;
5422 }
5423 try {
5424 inm.cancelNotificationWithTag("android", null,
5425 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5426 } catch (RuntimeException e) {
5427 Slog.w(TAG, "Error canceling notification for service", e);
5428 } catch (RemoteException e) {
5429 }
5430
5431 }
5432
5433 private void postHeavyWeightProcessNotification(
5434 WindowProcessController proc, Intent intent, int userId) {
5435 if (proc == null) {
5436 return;
5437 }
5438
5439 final INotificationManager inm = NotificationManager.getService();
5440 if (inm == null) {
5441 return;
5442 }
5443
5444 try {
5445 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5446 String text = mContext.getString(R.string.heavy_weight_notification,
5447 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5448 Notification notification =
5449 new Notification.Builder(context,
5450 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5451 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5452 .setWhen(0)
5453 .setOngoing(true)
5454 .setTicker(text)
5455 .setColor(mContext.getColor(
5456 com.android.internal.R.color.system_notification_accent_color))
5457 .setContentTitle(text)
5458 .setContentText(
5459 mContext.getText(R.string.heavy_weight_notification_detail))
5460 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5461 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5462 new UserHandle(userId)))
5463 .build();
5464 try {
5465 inm.enqueueNotificationWithTag("android", "android", null,
5466 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5467 } catch (RuntimeException e) {
5468 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5469 } catch (RemoteException e) {
5470 }
5471 } catch (PackageManager.NameNotFoundException e) {
5472 Slog.w(TAG, "Unable to create context for heavy notification", e);
5473 }
5474
5475 }
5476
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005477 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5478 IBinder token, String resultWho, int requestCode, Intent[] intents,
5479 String[] resolvedTypes, int flags, Bundle bOptions) {
5480
5481 ActivityRecord activity = null;
5482 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5483 activity = ActivityRecord.isInStackLocked(token);
5484 if (activity == null) {
5485 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5486 return null;
5487 }
5488 if (activity.finishing) {
5489 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5490 return null;
5491 }
5492 }
5493
5494 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5495 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5496 bOptions);
5497 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5498 if (noCreate) {
5499 return rec;
5500 }
5501 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5502 if (activity.pendingResults == null) {
5503 activity.pendingResults = new HashSet<>();
5504 }
5505 activity.pendingResults.add(rec.ref);
5506 }
5507 return rec;
5508 }
5509
Andrii Kulian52d255c2018-07-13 11:32:19 -07005510 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005512 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5514 mCurAppTimeTracker.start(resumedActivity.packageName);
5515 }
5516 }
5517
5518 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5519 if (mTracedResumedActivity != null) {
5520 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5521 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5522 }
5523 if (resumed != null) {
5524 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5525 constructResumedTraceName(resumed.packageName), 0);
5526 }
5527 mTracedResumedActivity = resumed;
5528 }
5529
5530 private String constructResumedTraceName(String packageName) {
5531 return "focused app: " + packageName;
5532 }
5533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005534 /** Applies latest configuration and/or visibility updates if needed. */
5535 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5536 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005537 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005538 // mainStack is null during startup.
5539 if (mainStack != null) {
5540 if (changes != 0 && starting == null) {
5541 // If the configuration changed, and the caller is not already
5542 // in the process of starting an activity, then find the top
5543 // activity to check if its configuration needs to change.
5544 starting = mainStack.topRunningActivityLocked();
5545 }
5546
5547 if (starting != null) {
5548 kept = starting.ensureActivityConfiguration(changes,
5549 false /* preserveWindow */);
5550 // And we need to make sure at this point that all other activities
5551 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005552 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005553 !PRESERVE_WINDOWS);
5554 }
5555 }
5556
5557 return kept;
5558 }
5559
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005560 void scheduleAppGcsLocked() {
5561 mH.post(() -> mAmInternal.scheduleAppGcs());
5562 }
5563
Wale Ogunwale53783742018-09-16 10:21:51 -07005564 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5565 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5566 }
5567
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005568 /**
5569 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5570 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5571 * on demand.
5572 */
5573 IPackageManager getPackageManager() {
5574 return AppGlobals.getPackageManager();
5575 }
5576
5577 PackageManagerInternal getPackageManagerInternalLocked() {
5578 if (mPmInternal == null) {
5579 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5580 }
5581 return mPmInternal;
5582 }
5583
Wale Ogunwale008163e2018-07-23 23:11:08 -07005584 AppWarnings getAppWarningsLocked() {
5585 return mAppWarnings;
5586 }
5587
Wale Ogunwale214f3482018-10-04 11:00:47 -07005588 Intent getHomeIntent() {
5589 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5590 intent.setComponent(mTopComponent);
5591 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5592 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5593 intent.addCategory(Intent.CATEGORY_HOME);
5594 }
5595 return intent;
5596 }
5597
Chilun2ef71f72018-11-16 17:57:15 +08005598 /**
5599 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5600 * activities.
5601 *
5602 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5603 * component defined in config_secondaryHomeComponent.
5604 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5605 */
5606 Intent getSecondaryHomeIntent(String preferredPackage) {
5607 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5608 if (preferredPackage == null) {
5609 // Using the component stored in config if no package name.
5610 final String secondaryHomeComponent = mContext.getResources().getString(
5611 com.android.internal.R.string.config_secondaryHomeComponent);
5612 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5613 } else {
5614 intent.setPackage(preferredPackage);
5615 }
5616 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5617 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5618 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5619 }
5620 return intent;
5621 }
5622
Wale Ogunwale214f3482018-10-04 11:00:47 -07005623 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5624 if (info == null) return null;
5625 ApplicationInfo newInfo = new ApplicationInfo(info);
5626 newInfo.initForUser(userId);
5627 return newInfo;
5628 }
5629
Wale Ogunwale9c103022018-10-18 07:44:54 -07005630 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005631 if (uid == SYSTEM_UID) {
5632 // The system gets to run in any process. If there are multiple processes with the same
5633 // uid, just pick the first (this should never happen).
5634 final SparseArray<WindowProcessController> procs =
5635 mProcessNames.getMap().get(processName);
5636 if (procs == null) return null;
5637 final int procCount = procs.size();
5638 for (int i = 0; i < procCount; i++) {
5639 final int procUid = procs.keyAt(i);
5640 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5641 // Don't use an app process or different user process for system component.
5642 continue;
5643 }
5644 return procs.valueAt(i);
5645 }
5646 }
5647
5648 return mProcessNames.get(processName, uid);
5649 }
5650
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005651 WindowProcessController getProcessController(IApplicationThread thread) {
5652 if (thread == null) {
5653 return null;
5654 }
5655
5656 final IBinder threadBinder = thread.asBinder();
5657 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5658 for (int i = pmap.size()-1; i >= 0; i--) {
5659 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5660 for (int j = procs.size() - 1; j >= 0; j--) {
5661 final WindowProcessController proc = procs.valueAt(j);
5662 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5663 return proc;
5664 }
5665 }
5666 }
5667
5668 return null;
5669 }
5670
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005671 WindowProcessController getProcessController(int pid, int uid) {
5672 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5673 for (int i = pmap.size()-1; i >= 0; i--) {
5674 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5675 for (int j = procs.size() - 1; j >= 0; j--) {
5676 final WindowProcessController proc = procs.valueAt(j);
5677 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5678 return proc;
5679 }
5680 }
5681 }
5682 return null;
5683 }
5684
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005685 int getUidStateLocked(int uid) {
5686 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5687 }
5688
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005689 boolean isUidForeground(int uid) {
5690 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5691 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5692 }
5693
Wale Ogunwale9de19442018-10-18 19:05:03 -07005694 /**
5695 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5696 * the whitelist
5697 */
5698 String getPendingTempWhitelistTagForUidLocked(int uid) {
5699 return mPendingTempWhitelist.get(uid);
5700 }
5701
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005702 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5703 if (true || Build.IS_USER) {
5704 return;
5705 }
5706
5707 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5708 StrictMode.allowThreadDiskWrites();
5709 try {
5710 File tracesDir = new File("/data/anr");
5711 File tracesFile = null;
5712 try {
5713 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5714
5715 StringBuilder sb = new StringBuilder();
5716 Time tobj = new Time();
5717 tobj.set(System.currentTimeMillis());
5718 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5719 sb.append(": ");
5720 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5721 sb.append(" since ");
5722 sb.append(msg);
5723 FileOutputStream fos = new FileOutputStream(tracesFile);
5724 fos.write(sb.toString().getBytes());
5725 if (app == null) {
5726 fos.write("\n*** No application process!".getBytes());
5727 }
5728 fos.close();
5729 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5730 } catch (IOException e) {
5731 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5732 return;
5733 }
5734
5735 if (app != null && app.getPid() > 0) {
5736 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5737 firstPids.add(app.getPid());
5738 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5739 }
5740
5741 File lastTracesFile = null;
5742 File curTracesFile = null;
5743 for (int i=9; i>=0; i--) {
5744 String name = String.format(Locale.US, "slow%02d.txt", i);
5745 curTracesFile = new File(tracesDir, name);
5746 if (curTracesFile.exists()) {
5747 if (lastTracesFile != null) {
5748 curTracesFile.renameTo(lastTracesFile);
5749 } else {
5750 curTracesFile.delete();
5751 }
5752 }
5753 lastTracesFile = curTracesFile;
5754 }
5755 tracesFile.renameTo(curTracesFile);
5756 } finally {
5757 StrictMode.setThreadPolicy(oldPolicy);
5758 }
5759 }
5760
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005761 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005762 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005763
5764
Wale Ogunwale98875612018-10-12 07:53:02 -07005765 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5766 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005767
Riddle Hsud93a6c42018-11-29 21:50:06 +08005768 H(Looper looper) {
5769 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005770 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005771
5772 @Override
5773 public void handleMessage(Message msg) {
5774 switch (msg.what) {
5775 case REPORT_TIME_TRACKER_MSG: {
5776 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5777 tracker.deliverResult(mContext);
5778 } break;
5779 }
5780 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005781 }
5782
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005783 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005784 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005785
5786 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005787 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005788 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005789
5790 @Override
5791 public void handleMessage(Message msg) {
5792 switch (msg.what) {
5793 case DISMISS_DIALOG_UI_MSG: {
5794 final Dialog d = (Dialog) msg.obj;
5795 d.dismiss();
5796 break;
5797 }
5798 }
5799 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005800 }
5801
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005802 final class LocalService extends ActivityTaskManagerInternal {
5803 @Override
5804 public SleepToken acquireSleepToken(String tag, int displayId) {
5805 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005806 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005807 }
5808
5809 @Override
5810 public ComponentName getHomeActivityForUser(int userId) {
5811 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005812 final ActivityRecord homeActivity =
5813 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005814 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005815 }
5816 }
5817
5818 @Override
5819 public void onLocalVoiceInteractionStarted(IBinder activity,
5820 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5821 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005822 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005823 }
5824 }
5825
5826 @Override
5827 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5828 synchronized (mGlobalLock) {
5829 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5830 reasons, timestamp);
5831 }
5832 }
5833
5834 @Override
5835 public void notifyAppTransitionFinished() {
5836 synchronized (mGlobalLock) {
5837 mStackSupervisor.notifyAppTransitionDone();
5838 }
5839 }
5840
5841 @Override
5842 public void notifyAppTransitionCancelled() {
5843 synchronized (mGlobalLock) {
5844 mStackSupervisor.notifyAppTransitionDone();
5845 }
5846 }
5847
5848 @Override
5849 public List<IBinder> getTopVisibleActivities() {
5850 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005851 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005852 }
5853 }
5854
5855 @Override
5856 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5857 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005858 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005859 }
5860 }
5861
5862 @Override
5863 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5864 Bundle bOptions) {
5865 Preconditions.checkNotNull(intents, "intents");
5866 final String[] resolvedTypes = new String[intents.length];
5867
5868 // UID of the package on user userId.
5869 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5870 // packageUid may not be initialized.
5871 int packageUid = 0;
5872 final long ident = Binder.clearCallingIdentity();
5873
5874 try {
5875 for (int i = 0; i < intents.length; i++) {
5876 resolvedTypes[i] =
5877 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5878 }
5879
5880 packageUid = AppGlobals.getPackageManager().getPackageUid(
5881 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5882 } catch (RemoteException e) {
5883 // Shouldn't happen.
5884 } finally {
5885 Binder.restoreCallingIdentity(ident);
5886 }
5887
5888 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005889 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005890 packageUid, packageName,
5891 intents, resolvedTypes, null /* resultTo */,
5892 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005893 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5894 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005895 }
5896 }
5897
5898 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005899 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5900 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5901 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5902 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005903 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005904 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005905 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5906 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5907 userId, validateIncomingUser, originatingPendingIntent,
5908 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005909 }
5910 }
5911
5912 @Override
5913 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5914 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5915 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5916 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005917 PendingIntentRecord originatingPendingIntent,
5918 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005919 synchronized (mGlobalLock) {
5920 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5921 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5922 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005923 validateIncomingUser, originatingPendingIntent,
5924 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005925 }
5926 }
5927
5928 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5930 Intent intent, Bundle options, int userId) {
5931 return ActivityTaskManagerService.this.startActivityAsUser(
5932 caller, callerPacakge, intent,
5933 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5934 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5935 false /*validateIncomingUser*/);
5936 }
5937
5938 @Override
lumark588a3e82018-07-20 18:53:54 +08005939 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005940 synchronized (mGlobalLock) {
5941
5942 // We might change the visibilities here, so prepare an empty app transition which
5943 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005944 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005945 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005946 if (activityDisplay == null) {
5947 return;
5948 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005949 final DisplayContent dc = activityDisplay.mDisplayContent;
5950 final boolean wasTransitionSet =
5951 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005952 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005953 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005954 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005955 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005956
5957 // If there was a transition set already we don't want to interfere with it as we
5958 // might be starting it too early.
5959 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005960 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005961 }
5962 }
5963 if (callback != null) {
5964 callback.run();
5965 }
5966 }
5967
5968 @Override
5969 public void notifyKeyguardTrustedChanged() {
5970 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005971 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005972 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005973 }
5974 }
5975 }
5976
5977 /**
5978 * Called after virtual display Id is updated by
5979 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5980 * {@param vrVr2dDisplayId}.
5981 */
5982 @Override
5983 public void setVr2dDisplayId(int vr2dDisplayId) {
5984 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5985 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005986 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005987 }
5988 }
5989
5990 @Override
5991 public void setFocusedActivity(IBinder token) {
5992 synchronized (mGlobalLock) {
5993 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5994 if (r == null) {
5995 throw new IllegalArgumentException(
5996 "setFocusedActivity: No activity record matching token=" + token);
5997 }
Louis Chang19443452018-10-09 12:10:21 +08005998 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005999 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006000 }
6001 }
6002 }
6003
6004 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006005 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006006 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006007 }
6008
6009 @Override
6010 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006011 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006012 }
6013
6014 @Override
6015 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006016 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006017 }
6018
6019 @Override
6020 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6021 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6022 }
6023
6024 @Override
6025 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006026 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006027 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006028
6029 @Override
6030 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6031 synchronized (mGlobalLock) {
6032 mActiveVoiceInteractionServiceComponent = component;
6033 }
6034 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006035
6036 @Override
6037 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6038 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6039 return;
6040 }
6041 synchronized (mGlobalLock) {
6042 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6043 if (types == null) {
6044 if (uid < 0) {
6045 return;
6046 }
6047 types = new ArrayMap<>();
6048 mAllowAppSwitchUids.put(userId, types);
6049 }
6050 if (uid < 0) {
6051 types.remove(type);
6052 } else {
6053 types.put(type, uid);
6054 }
6055 }
6056 }
6057
6058 @Override
6059 public void onUserStopped(int userId) {
6060 synchronized (mGlobalLock) {
6061 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6062 mAllowAppSwitchUids.remove(userId);
6063 }
6064 }
6065
6066 @Override
6067 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6068 synchronized (mGlobalLock) {
6069 return ActivityTaskManagerService.this.isGetTasksAllowed(
6070 caller, callingPid, callingUid);
6071 }
6072 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006073
6074 @Override
6075 public void onProcessAdded(WindowProcessController proc) {
6076 synchronized (mGlobalLock) {
6077 mProcessNames.put(proc.mName, proc.mUid, proc);
6078 }
6079 }
6080
6081 @Override
6082 public void onProcessRemoved(String name, int uid) {
6083 synchronized (mGlobalLock) {
6084 mProcessNames.remove(name, uid);
6085 }
6086 }
6087
6088 @Override
6089 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6090 synchronized (mGlobalLock) {
6091 if (proc == mHomeProcess) {
6092 mHomeProcess = null;
6093 }
6094 if (proc == mPreviousProcess) {
6095 mPreviousProcess = null;
6096 }
6097 }
6098 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006099
6100 @Override
6101 public int getTopProcessState() {
6102 synchronized (mGlobalLock) {
6103 return mTopProcessState;
6104 }
6105 }
6106
6107 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006108 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6109 synchronized (mGlobalLock) {
6110 return proc == mHeavyWeightProcess;
6111 }
6112 }
6113
6114 @Override
6115 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6116 synchronized (mGlobalLock) {
6117 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6118 }
6119 }
6120
6121 @Override
6122 public void finishHeavyWeightApp() {
6123 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006124 if (mHeavyWeightProcess != null) {
6125 mHeavyWeightProcess.finishActivities();
6126 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006127 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6128 mHeavyWeightProcess);
6129 }
6130 }
6131
6132 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006133 public boolean isSleeping() {
6134 synchronized (mGlobalLock) {
6135 return isSleepingLocked();
6136 }
6137 }
6138
6139 @Override
6140 public boolean isShuttingDown() {
6141 synchronized (mGlobalLock) {
6142 return mShuttingDown;
6143 }
6144 }
6145
6146 @Override
6147 public boolean shuttingDown(boolean booted, int timeout) {
6148 synchronized (mGlobalLock) {
6149 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006150 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006151 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006152 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006153 return mStackSupervisor.shutdownLocked(timeout);
6154 }
6155 }
6156
6157 @Override
6158 public void enableScreenAfterBoot(boolean booted) {
6159 synchronized (mGlobalLock) {
6160 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6161 SystemClock.uptimeMillis());
6162 mWindowManager.enableScreenAfterBoot();
6163 updateEventDispatchingLocked(booted);
6164 }
6165 }
6166
6167 @Override
6168 public boolean showStrictModeViolationDialog() {
6169 synchronized (mGlobalLock) {
6170 return mShowDialogs && !mSleeping && !mShuttingDown;
6171 }
6172 }
6173
6174 @Override
6175 public void showSystemReadyErrorDialogsIfNeeded() {
6176 synchronized (mGlobalLock) {
6177 try {
6178 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6179 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6180 + " data partition or your device will be unstable.");
6181 mUiHandler.post(() -> {
6182 if (mShowDialogs) {
6183 AlertDialog d = new BaseErrorDialog(mUiContext);
6184 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6185 d.setCancelable(false);
6186 d.setTitle(mUiContext.getText(R.string.android_system_label));
6187 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6188 d.setButton(DialogInterface.BUTTON_POSITIVE,
6189 mUiContext.getText(R.string.ok),
6190 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6191 d.show();
6192 }
6193 });
6194 }
6195 } catch (RemoteException e) {
6196 }
6197
6198 if (!Build.isBuildConsistent()) {
6199 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6200 mUiHandler.post(() -> {
6201 if (mShowDialogs) {
6202 AlertDialog d = new BaseErrorDialog(mUiContext);
6203 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6204 d.setCancelable(false);
6205 d.setTitle(mUiContext.getText(R.string.android_system_label));
6206 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6207 d.setButton(DialogInterface.BUTTON_POSITIVE,
6208 mUiContext.getText(R.string.ok),
6209 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6210 d.show();
6211 }
6212 });
6213 }
6214 }
6215 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006216
6217 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006218 public void onProcessMapped(int pid, WindowProcessController proc) {
6219 synchronized (mGlobalLock) {
6220 mPidMap.put(pid, proc);
6221 }
6222 }
6223
6224 @Override
6225 public void onProcessUnMapped(int pid) {
6226 synchronized (mGlobalLock) {
6227 mPidMap.remove(pid);
6228 }
6229 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006230
6231 @Override
6232 public void onPackageDataCleared(String name) {
6233 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006234 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006235 mAppWarnings.onPackageDataCleared(name);
6236 }
6237 }
6238
6239 @Override
6240 public void onPackageUninstalled(String name) {
6241 synchronized (mGlobalLock) {
6242 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006243 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006244 }
6245 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006246
6247 @Override
6248 public void onPackageAdded(String name, boolean replacing) {
6249 synchronized (mGlobalLock) {
6250 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6251 }
6252 }
6253
6254 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006255 public void onPackageReplaced(ApplicationInfo aInfo) {
6256 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006257 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006258 }
6259 }
6260
6261 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006262 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6263 synchronized (mGlobalLock) {
6264 return compatibilityInfoForPackageLocked(ai);
6265 }
6266 }
6267
Yunfan Chen75157d72018-07-27 14:47:21 +09006268 /**
6269 * Set the corresponding display information for the process global configuration. To be
6270 * called when we need to show IME on a different display.
6271 *
6272 * @param pid The process id associated with the IME window.
6273 * @param displayId The ID of the display showing the IME.
6274 */
6275 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006276 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006277 if (pid == MY_PID || pid < 0) {
6278 if (DEBUG_CONFIGURATION) {
6279 Slog.w(TAG,
6280 "Trying to update display configuration for system/invalid process.");
6281 }
6282 return;
6283 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006284 synchronized (mGlobalLock) {
6285 final ActivityDisplay activityDisplay =
6286 mRootActivityContainer.getActivityDisplay(displayId);
6287 if (activityDisplay == null) {
6288 // Call might come when display is not yet added or has been removed.
6289 if (DEBUG_CONFIGURATION) {
6290 Slog.w(TAG, "Trying to update display configuration for non-existing "
6291 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006292 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006293 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006294 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006295 final WindowProcessController process = mPidMap.get(pid);
6296 if (process == null) {
6297 if (DEBUG_CONFIGURATION) {
6298 Slog.w(TAG, "Trying to update display configuration for invalid "
6299 + "process, pid=" + pid);
6300 }
6301 return;
6302 }
6303 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6304 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006305 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006306
6307 @Override
6308 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6309 int requestCode, int resultCode, Intent data) {
6310 synchronized (mGlobalLock) {
6311 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006312 if (r != null && r.getActivityStack() != null) {
6313 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6314 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006315 }
6316 }
6317 }
6318
6319 @Override
6320 public void clearPendingResultForActivity(IBinder activityToken,
6321 WeakReference<PendingIntentRecord> pir) {
6322 synchronized (mGlobalLock) {
6323 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6324 if (r != null && r.pendingResults != null) {
6325 r.pendingResults.remove(pir);
6326 }
6327 }
6328 }
6329
6330 @Override
6331 public IIntentSender getIntentSender(int type, String packageName,
6332 int callingUid, int userId, IBinder token, String resultWho,
6333 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6334 Bundle bOptions) {
6335 synchronized (mGlobalLock) {
6336 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6337 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6338 }
6339 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006340
6341 @Override
6342 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6343 synchronized (mGlobalLock) {
6344 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6345 if (r == null) {
6346 return null;
6347 }
6348 if (r.mServiceConnectionsHolder == null) {
6349 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6350 ActivityTaskManagerService.this, r);
6351 }
6352
6353 return r.mServiceConnectionsHolder;
6354 }
6355 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006356
6357 @Override
6358 public Intent getHomeIntent() {
6359 synchronized (mGlobalLock) {
6360 return ActivityTaskManagerService.this.getHomeIntent();
6361 }
6362 }
6363
6364 @Override
6365 public boolean startHomeActivity(int userId, String reason) {
6366 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006367 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006368 }
6369 }
6370
6371 @Override
6372 public boolean startHomeOnAllDisplays(int userId, String reason) {
6373 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006374 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006375 }
6376 }
6377
6378 @Override
6379 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6380 synchronized (mGlobalLock) {
6381 if (mFactoryTest == FACTORY_TEST_OFF) {
6382 return false;
6383 }
6384 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6385 && wpc.mName.equals(mTopComponent.getPackageName())) {
6386 return true;
6387 }
6388 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6389 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6390 }
6391 }
6392
6393 @Override
6394 public void updateTopComponentForFactoryTest() {
6395 synchronized (mGlobalLock) {
6396 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6397 return;
6398 }
6399 final ResolveInfo ri = mContext.getPackageManager()
6400 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6401 final CharSequence errorMsg;
6402 if (ri != null) {
6403 final ActivityInfo ai = ri.activityInfo;
6404 final ApplicationInfo app = ai.applicationInfo;
6405 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6406 mTopAction = Intent.ACTION_FACTORY_TEST;
6407 mTopData = null;
6408 mTopComponent = new ComponentName(app.packageName, ai.name);
6409 errorMsg = null;
6410 } else {
6411 errorMsg = mContext.getResources().getText(
6412 com.android.internal.R.string.factorytest_not_system);
6413 }
6414 } else {
6415 errorMsg = mContext.getResources().getText(
6416 com.android.internal.R.string.factorytest_no_action);
6417 }
6418 if (errorMsg == null) {
6419 return;
6420 }
6421
6422 mTopAction = null;
6423 mTopData = null;
6424 mTopComponent = null;
6425 mUiHandler.post(() -> {
6426 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6427 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006428 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006429 });
6430 }
6431 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006432
6433 @Override
6434 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6435 Runnable finishInstrumentationCallback) {
6436 synchronized (mGlobalLock) {
6437 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006438 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006439
6440 wpc.clearRecentTasks();
6441 wpc.clearActivities();
6442
6443 if (wpc.isInstrumenting()) {
6444 finishInstrumentationCallback.run();
6445 }
6446
Jorim Jaggid0752812018-10-16 16:07:20 +02006447 if (!restarting && hasVisibleActivities) {
6448 mWindowManager.deferSurfaceLayout();
6449 try {
6450 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6451 // If there was nothing to resume, and we are not already restarting
6452 // this process, but there is a visible activity that is hosted by the
6453 // process...then make sure all visible activities are running, taking
6454 // care of restarting this process.
6455 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6456 !PRESERVE_WINDOWS);
6457 }
6458 } finally {
6459 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006460 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006461 }
6462 }
6463 }
6464
6465 @Override
6466 public void closeSystemDialogs(String reason) {
6467 enforceNotIsolatedCaller("closeSystemDialogs");
6468
6469 final int pid = Binder.getCallingPid();
6470 final int uid = Binder.getCallingUid();
6471 final long origId = Binder.clearCallingIdentity();
6472 try {
6473 synchronized (mGlobalLock) {
6474 // Only allow this from foreground processes, so that background
6475 // applications can't abuse it to prevent system UI from being shown.
6476 if (uid >= FIRST_APPLICATION_UID) {
6477 final WindowProcessController proc = mPidMap.get(pid);
6478 if (!proc.isPerceptible()) {
6479 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6480 + " from background process " + proc);
6481 return;
6482 }
6483 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006484 mWindowManager.closeSystemDialogs(reason);
6485
Wale Ogunwaled32da472018-11-16 07:19:28 -08006486 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006487 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006488 // Call into AM outside the synchronized block.
6489 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006490 } finally {
6491 Binder.restoreCallingIdentity(origId);
6492 }
6493 }
6494
6495 @Override
6496 public void cleanupDisabledPackageComponents(
6497 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6498 synchronized (mGlobalLock) {
6499 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006500 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006501 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006502 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006503 mStackSupervisor.scheduleIdleLocked();
6504 }
6505
6506 // Clean-up disabled tasks
6507 getRecentTasks().cleanupDisabledPackageTasksLocked(
6508 packageName, disabledClasses, userId);
6509 }
6510 }
6511
6512 @Override
6513 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6514 int userId) {
6515 synchronized (mGlobalLock) {
6516
6517 boolean didSomething =
6518 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006519 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006520 null, doit, evenPersistent, userId);
6521 return didSomething;
6522 }
6523 }
6524
6525 @Override
6526 public void resumeTopActivities(boolean scheduleIdle) {
6527 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006528 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006529 if (scheduleIdle) {
6530 mStackSupervisor.scheduleIdleLocked();
6531 }
6532 }
6533 }
6534
6535 @Override
6536 public void preBindApplication(WindowProcessController wpc) {
6537 synchronized (mGlobalLock) {
6538 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6539 }
6540 }
6541
6542 @Override
6543 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6544 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006545 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006546 }
6547 }
6548
6549 @Override
6550 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6551 try {
6552 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6553 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6554 }
6555 } catch (RemoteException ex) {
6556 throw new SecurityException("Fail to check is caller a privileged app", ex);
6557 }
6558
6559 synchronized (mGlobalLock) {
6560 final long ident = Binder.clearCallingIdentity();
6561 try {
6562 if (mAmInternal.shouldConfirmCredentials(userId)) {
6563 if (mKeyguardController.isKeyguardLocked()) {
6564 // Showing launcher to avoid user entering credential twice.
6565 startHomeActivity(currentUserId, "notifyLockedProfile");
6566 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006567 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006568 }
6569 } finally {
6570 Binder.restoreCallingIdentity(ident);
6571 }
6572 }
6573 }
6574
6575 @Override
6576 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6577 mAmInternal.enforceCallingPermission(
6578 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6579
6580 synchronized (mGlobalLock) {
6581 final long ident = Binder.clearCallingIdentity();
6582 try {
6583 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6584 FLAG_ACTIVITY_TASK_ON_HOME);
6585 ActivityOptions activityOptions = options != null
6586 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006587 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006588 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006589 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006590 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006591 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006592 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6593 UserHandle.CURRENT);
6594 } finally {
6595 Binder.restoreCallingIdentity(ident);
6596 }
6597 }
6598 }
6599
6600 @Override
6601 public void writeActivitiesToProto(ProtoOutputStream proto) {
6602 synchronized (mGlobalLock) {
6603 // The output proto of "activity --proto activities"
6604 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006605 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006606 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6607 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006608 }
6609 }
6610
6611 @Override
6612 public void saveANRState(String reason) {
6613 synchronized (mGlobalLock) {
6614 final StringWriter sw = new StringWriter();
6615 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6616 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6617 if (reason != null) {
6618 pw.println(" Reason: " + reason);
6619 }
6620 pw.println();
6621 getActivityStartController().dump(pw, " ", null);
6622 pw.println();
6623 pw.println("-------------------------------------------------------------------------------");
6624 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6625 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6626 "" /* header */);
6627 pw.println();
6628 pw.close();
6629
6630 mLastANRState = sw.toString();
6631 }
6632 }
6633
6634 @Override
6635 public void clearSavedANRState() {
6636 synchronized (mGlobalLock) {
6637 mLastANRState = null;
6638 }
6639 }
6640
6641 @Override
6642 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6643 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6644 synchronized (mGlobalLock) {
6645 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6646 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6647 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6648 dumpLastANRLocked(pw);
6649 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6650 dumpLastANRTracesLocked(pw);
6651 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6652 dumpActivityStarterLocked(pw, dumpPackage);
6653 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6654 dumpActivityContainersLocked(pw);
6655 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6656 if (getRecentTasks() != null) {
6657 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6658 }
6659 }
6660 }
6661 }
6662
6663 @Override
6664 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6665 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6666 int wakefulness) {
6667 synchronized (mGlobalLock) {
6668 if (mHomeProcess != null && (dumpPackage == null
6669 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6670 if (needSep) {
6671 pw.println();
6672 needSep = false;
6673 }
6674 pw.println(" mHomeProcess: " + mHomeProcess);
6675 }
6676 if (mPreviousProcess != null && (dumpPackage == null
6677 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6678 if (needSep) {
6679 pw.println();
6680 needSep = false;
6681 }
6682 pw.println(" mPreviousProcess: " + mPreviousProcess);
6683 }
6684 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6685 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6686 StringBuilder sb = new StringBuilder(128);
6687 sb.append(" mPreviousProcessVisibleTime: ");
6688 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6689 pw.println(sb);
6690 }
6691 if (mHeavyWeightProcess != null && (dumpPackage == null
6692 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6693 if (needSep) {
6694 pw.println();
6695 needSep = false;
6696 }
6697 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6698 }
6699 if (dumpPackage == null) {
6700 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006701 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006702 }
6703 if (dumpAll) {
6704 if (dumpPackage == null) {
6705 pw.println(" mConfigWillChange: "
6706 + getTopDisplayFocusedStack().mConfigWillChange);
6707 }
6708 if (mCompatModePackages.getPackages().size() > 0) {
6709 boolean printed = false;
6710 for (Map.Entry<String, Integer> entry
6711 : mCompatModePackages.getPackages().entrySet()) {
6712 String pkg = entry.getKey();
6713 int mode = entry.getValue();
6714 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6715 continue;
6716 }
6717 if (!printed) {
6718 pw.println(" mScreenCompatPackages:");
6719 printed = true;
6720 }
6721 pw.println(" " + pkg + ": " + mode);
6722 }
6723 }
6724 }
6725
6726 if (dumpPackage == null) {
6727 pw.println(" mWakefulness="
6728 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006729 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 if (mRunningVoice != null) {
6731 pw.println(" mRunningVoice=" + mRunningVoice);
6732 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6733 }
6734 pw.println(" mSleeping=" + mSleeping);
6735 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6736 pw.println(" mVrController=" + mVrController);
6737 }
6738 if (mCurAppTimeTracker != null) {
6739 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6740 }
6741 if (mAllowAppSwitchUids.size() > 0) {
6742 boolean printed = false;
6743 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6744 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6745 for (int j = 0; j < types.size(); j++) {
6746 if (dumpPackage == null ||
6747 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6748 if (needSep) {
6749 pw.println();
6750 needSep = false;
6751 }
6752 if (!printed) {
6753 pw.println(" mAllowAppSwitchUids:");
6754 printed = true;
6755 }
6756 pw.print(" User ");
6757 pw.print(mAllowAppSwitchUids.keyAt(i));
6758 pw.print(": Type ");
6759 pw.print(types.keyAt(j));
6760 pw.print(" = ");
6761 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6762 pw.println();
6763 }
6764 }
6765 }
6766 }
6767 if (dumpPackage == null) {
6768 if (mController != null) {
6769 pw.println(" mController=" + mController
6770 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6771 }
6772 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6773 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6774 }
6775
6776 return needSep;
6777 }
6778 }
6779
6780 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006781 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6782 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 synchronized (mGlobalLock) {
6784 if (dumpPackage == null) {
6785 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6786 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006787 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6788 if (mRunningVoice != null) {
6789 final long vrToken = proto.start(
6790 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6791 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6792 mRunningVoice.toString());
6793 mVoiceWakeLock.writeToProto(
6794 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6795 proto.end(vrToken);
6796 }
6797 mVrController.writeToProto(proto,
6798 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 if (mController != null) {
6800 final long token = proto.start(CONTROLLER);
6801 proto.write(CONTROLLER, mController.toString());
6802 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6803 proto.end(token);
6804 }
6805 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6806 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6807 }
6808
6809 if (mHomeProcess != null && (dumpPackage == null
6810 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006811 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 }
6813
6814 if (mPreviousProcess != null && (dumpPackage == null
6815 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006816 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6818 }
6819
6820 if (mHeavyWeightProcess != null && (dumpPackage == null
6821 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006822 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 }
6824
6825 for (Map.Entry<String, Integer> entry
6826 : mCompatModePackages.getPackages().entrySet()) {
6827 String pkg = entry.getKey();
6828 int mode = entry.getValue();
6829 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6830 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6831 proto.write(PACKAGE, pkg);
6832 proto.write(MODE, mode);
6833 proto.end(compatToken);
6834 }
6835 }
6836
6837 if (mCurAppTimeTracker != null) {
6838 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6839 }
6840
6841 }
6842 }
6843
6844 @Override
6845 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6846 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6847 boolean dumpFocusedStackOnly) {
6848 synchronized (mGlobalLock) {
6849 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6850 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6851 }
6852 }
6853
6854 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006855 public void dumpForOom(PrintWriter pw) {
6856 synchronized (mGlobalLock) {
6857 pw.println(" mHomeProcess: " + mHomeProcess);
6858 pw.println(" mPreviousProcess: " + mPreviousProcess);
6859 if (mHeavyWeightProcess != null) {
6860 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6861 }
6862 }
6863 }
6864
6865 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 public boolean canGcNow() {
6867 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006868 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006869 }
6870 }
6871
6872 @Override
6873 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006874 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006875 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 return top != null ? top.app : null;
6877 }
6878 }
6879
6880 @Override
6881 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006882 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006883 if (mRootActivityContainer != null) {
6884 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 }
6886 }
6887 }
6888
6889 @Override
6890 public void scheduleDestroyAllActivities(String reason) {
6891 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006892 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006893 }
6894 }
6895
6896 @Override
6897 public void removeUser(int userId) {
6898 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006899 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006900 }
6901 }
6902
6903 @Override
6904 public boolean switchUser(int userId, UserState userState) {
6905 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006906 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 }
6908 }
6909
6910 @Override
6911 public void onHandleAppCrash(WindowProcessController wpc) {
6912 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006913 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 }
6915 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006916
6917 @Override
6918 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6919 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006920 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006921 }
6922 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006923
6924 @Override
6925 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006926 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006927 mActiveUids.put(uid, procState);
6928 }
6929 }
6930
6931 @Override
6932 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006933 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006934 mActiveUids.remove(uid);
6935 }
6936 }
6937
6938 @Override
6939 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006940 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006941 mActiveUids.clear();
6942 }
6943 }
6944
6945 @Override
6946 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006947 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006948 if (mActiveUids.get(uid) != null) {
6949 mActiveUids.put(uid, procState);
6950 }
6951 }
6952 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006953
6954 @Override
6955 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006956 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006957 mPendingTempWhitelist.put(uid, tag);
6958 }
6959 }
6960
6961 @Override
6962 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006963 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006964 mPendingTempWhitelist.remove(uid);
6965 }
6966 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006967
6968 @Override
6969 public boolean handleAppCrashInActivityController(String processName, int pid,
6970 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6971 Runnable killCrashingAppCallback) {
6972 synchronized (mGlobalLock) {
6973 if (mController == null) {
6974 return false;
6975 }
6976
6977 try {
6978 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6979 stackTrace)) {
6980 killCrashingAppCallback.run();
6981 return true;
6982 }
6983 } catch (RemoteException e) {
6984 mController = null;
6985 Watchdog.getInstance().setActivityController(null);
6986 }
6987 return false;
6988 }
6989 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006990
6991 @Override
6992 public void removeRecentTasksByPackageName(String packageName, int userId) {
6993 synchronized (mGlobalLock) {
6994 mRecentTasks.removeTasksByPackageName(packageName, userId);
6995 }
6996 }
6997
6998 @Override
6999 public void cleanupRecentTasksForUser(int userId) {
7000 synchronized (mGlobalLock) {
7001 mRecentTasks.cleanupLocked(userId);
7002 }
7003 }
7004
7005 @Override
7006 public void loadRecentTasksForUser(int userId) {
7007 synchronized (mGlobalLock) {
7008 mRecentTasks.loadUserRecentsLocked(userId);
7009 }
7010 }
7011
7012 @Override
7013 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7014 synchronized (mGlobalLock) {
7015 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7016 }
7017 }
7018
7019 @Override
7020 public void flushRecentTasks() {
7021 mRecentTasks.flush();
7022 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007023
7024 @Override
7025 public WindowProcessController getHomeProcess() {
7026 synchronized (mGlobalLock) {
7027 return mHomeProcess;
7028 }
7029 }
7030
7031 @Override
7032 public WindowProcessController getPreviousProcess() {
7033 synchronized (mGlobalLock) {
7034 return mPreviousProcess;
7035 }
7036 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007037
7038 @Override
7039 public void clearLockedTasks(String reason) {
7040 synchronized (mGlobalLock) {
7041 getLockTaskController().clearLockedTasks(reason);
7042 }
7043 }
7044
7045 @Override
7046 public void updateUserConfiguration() {
7047 synchronized (mGlobalLock) {
7048 final Configuration configuration = new Configuration(getGlobalConfiguration());
7049 final int currentUserId = mAmInternal.getCurrentUserId();
7050 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7051 configuration, currentUserId, Settings.System.canWrite(mContext));
7052 updateConfigurationLocked(configuration, null /* starting */,
7053 false /* initLocale */, false /* persistent */, currentUserId,
7054 false /* deferResume */);
7055 }
7056 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007057
7058 @Override
7059 public boolean canShowErrorDialogs() {
7060 synchronized (mGlobalLock) {
7061 return mShowDialogs && !mSleeping && !mShuttingDown
7062 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7063 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7064 mAmInternal.getCurrentUserId())
7065 && !(UserManager.isDeviceInDemoMode(mContext)
7066 && mAmInternal.getCurrentUser().isDemo());
7067 }
7068 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007069
7070 @Override
7071 public void setProfileApp(String profileApp) {
7072 synchronized (mGlobalLock) {
7073 mProfileApp = profileApp;
7074 }
7075 }
7076
7077 @Override
7078 public void setProfileProc(WindowProcessController wpc) {
7079 synchronized (mGlobalLock) {
7080 mProfileProc = wpc;
7081 }
7082 }
7083
7084 @Override
7085 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7086 synchronized (mGlobalLock) {
7087 mProfilerInfo = profilerInfo;
7088 }
7089 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007090
7091 @Override
7092 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7093 synchronized (mGlobalLock) {
7094 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7095 }
7096 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007097
7098 @Override
7099 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7100 synchronized (mGlobalLock) {
7101 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7102 }
7103 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007104
7105 @Override
7106 public boolean isUidForeground(int uid) {
7107 synchronized (mGlobalLock) {
7108 return ActivityTaskManagerService.this.isUidForeground(uid);
7109 }
7110 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007111 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007112}