blob: 297613cd6f8f83bf5003725ba4611e65b7d2fdf0 [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.ALWAYS_FINISH_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
62import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070063import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
64import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040066import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.Display.DEFAULT_DISPLAY;
68import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070069import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070070import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070071
Yunfan Chen79b96062018-10-17 12:45:23 -070072import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
73import static com.android.server.am.ActivityManagerService.MY_PID;
74import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
75import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070076import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Wale Ogunwale59507092018-10-29 09:00:30 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
87 .PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070088import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
90 .MODE;
91import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
92 .PACKAGE;
93import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
94import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
95import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
96import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
97import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
98import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
99import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
115import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
116import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
117import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
119import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
120import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
121import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
123import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
125import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
wilsonshihe7903ea2018-09-26 16:17:59 +0800126import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
127import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
128import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700130import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.annotation.Nullable;
133import android.annotation.UserIdInt;
134import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700135import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700136import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.ActivityOptions;
138import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700139import android.app.ActivityThread;
140import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700142import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700143import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700144import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.IApplicationThread;
146import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700160import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.ActivityNotFoundException;
162import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700163import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700164import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700165import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700166import android.content.IIntentSender;
167import android.content.Intent;
168import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700169import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900170import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.ParceledListSlice;
175import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700176import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700178import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700179import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.graphics.Bitmap;
181import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.metrics.LogMaker;
184import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700185import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700188import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700189import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700193import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700248import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.DisplayThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700278import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700280import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700281import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400283import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700286import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Map;
288import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289
290/**
291 * System service for managing activities and their containers (task, stacks, displays,... ).
292 *
293 * {@hide}
294 */
295public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700296 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700298 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
299 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
300 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
301 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
302 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700303 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700308 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309
Wale Ogunwale98875612018-10-12 07:53:02 -0700310 /** Used to indicate that an app transition should be animated. */
311 static final boolean ANIMATE = true;
312
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700313 /** Hardware-reported OpenGLES version. */
314 final int GL_ES_VERSION;
315
Wale Ogunwale31913b52018-10-13 08:29:31 -0700316 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
317 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
318 public static final String DUMP_LASTANR_CMD = "lastanr" ;
319 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
320 public static final String DUMP_STARTER_CMD = "starter" ;
321 public static final String DUMP_CONTAINERS_CMD = "containers" ;
322 public static final String DUMP_RECENTS_CMD = "recents" ;
323 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
324
Wale Ogunwale64258362018-10-16 15:13:37 -0700325 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
326 public static final int RELAUNCH_REASON_NONE = 0;
327 /** This activity is being relaunched due to windowing mode change. */
328 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
329 /** This activity is being relaunched due to a free-resize operation. */
330 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
331
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700332 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700333
Wale Ogunwalef6733932018-06-27 05:14:34 -0700334 /**
335 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
336 * change at runtime. Use mContext for non-UI purposes.
337 */
338 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700339 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700340 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700342 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700343 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700344 private PackageManagerInternal mPmInternal;
Wale Ogunwale53783742018-09-16 10:21:51 -0700345 private ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 PowerManagerInternal mPowerManagerInternal;
347 private UsageStatsManagerInternal mUsageStatsInternal;
348
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700349 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 IntentFirewall mIntentFirewall;
351
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700352 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800353 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700354 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700356 private UserManagerService mUserManager;
357 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700358 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700359 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
360 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700361 /** All processes currently running that might have a window organized by name. */
362 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700363 /** All processes we currently have running mapped by pid */
364 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700365 /** This is the process holding what we currently consider to be the "home" activity. */
366 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700367 /** The currently running heavy-weight process, if any. */
368 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700369 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700370 /**
371 * This is the process holding the activity the user last visited that is in a different process
372 * from the one they are currently in.
373 */
374 WindowProcessController mPreviousProcess;
375 /** The time at which the previous process was last visible. */
376 long mPreviousProcessVisibleTime;
377
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 /** List of intents that were used to start the most recent tasks. */
379 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700380 /** State of external calls telling us if the device is awake or asleep. */
381 private boolean mKeyguardShown = false;
382
383 // Wrapper around VoiceInteractionServiceManager
384 private AssistUtils mAssistUtils;
385
386 // VoiceInteraction session ID that changes for each new request except when
387 // being called for multi-window assist in a single session.
388 private int mViSessionId = 1000;
389
390 // How long to wait in getAssistContextExtras for the activity and foreground services
391 // to respond with the result.
392 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
393
394 // How long top wait when going through the modern assist (which doesn't need to block
395 // on getting this result before starting to launch its UI).
396 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
397
398 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
399 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
400
Alison Cichowlas3e340502018-08-07 17:15:01 -0400401 // Permission tokens are used to temporarily granted a trusted app the ability to call
402 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
403 // showing any appropriate error messages to the user.
404 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
405 10 * MINUTE_IN_MILLIS;
406
407 // How long before the service actually expires a token. This is slightly longer than
408 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
409 // expiration exception.
410 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
411 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
412
413 // How long the service will remember expired tokens, for the purpose of providing error
414 // messaging when a client uses an expired token.
415 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
416 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
417
418 // Activity tokens of system activities that are delegating their call to
419 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
420 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
421
422 // Permission tokens that have expired, but we remember for error reporting.
423 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
424
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700425 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
426
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700427 // Keeps track of the active voice interaction service component, notified from
428 // VoiceInteractionManagerService
429 ComponentName mActiveVoiceInteractionServiceComponent;
430
Wale Ogunwalee2172292018-10-25 10:11:10 -0700431 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700432 KeyguardController mKeyguardController;
433 private final ClientLifecycleManager mLifecycleManager;
434 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700435 /** The controller for all operations related to locktask. */
436 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700437 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700438
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700439 boolean mSuppressResizeConfigChanges;
440
441 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
442 new UpdateConfigurationResult();
443
444 static final class UpdateConfigurationResult {
445 // Configuration changes that were updated.
446 int changes;
447 // If the activity was relaunched to match the new configuration.
448 boolean activityRelaunched;
449
450 void reset() {
451 changes = 0;
452 activityRelaunched = false;
453 }
454 }
455
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700456 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700457 private int mConfigurationSeq;
458 // To cache the list of supported system locales
459 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700460
461 /**
462 * Temp object used when global and/or display override configuration is updated. It is also
463 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
464 * anyone...
465 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700466 private Configuration mTempConfig = new Configuration();
467
Wale Ogunwalef6733932018-06-27 05:14:34 -0700468 /** Temporary to avoid allocations. */
469 final StringBuilder mStringBuilder = new StringBuilder(256);
470
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700471 // Amount of time after a call to stopAppSwitches() during which we will
472 // prevent further untrusted switches from happening.
473 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
474
475 /**
476 * The time at which we will allow normal application switches again,
477 * after a call to {@link #stopAppSwitches()}.
478 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700479 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 /**
481 * This is set to true after the first switch after mAppSwitchesAllowedTime
482 * is set; any switches after that will clear the time.
483 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700484 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485
486 IActivityController mController = null;
487 boolean mControllerIsAMonkey = false;
488
Wale Ogunwale214f3482018-10-04 11:00:47 -0700489 final int mFactoryTest;
490
491 /** Used to control how we initialize the service. */
492 ComponentName mTopComponent;
493 String mTopAction = Intent.ACTION_MAIN;
494 String mTopData;
495
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800496 /** Profiling app information. */
497 String mProfileApp = null;
498 WindowProcessController mProfileProc = null;
499 ProfilerInfo mProfilerInfo = null;
500
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700502 * Dump of the activity state at the time of the last ANR. Cleared after
503 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
504 */
505 String mLastANRState;
506
507 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 * Used to retain an update lock when the foreground activity is in
509 * immersive mode.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
513 /**
514 * Packages that are being allowed to perform unrestricted app switches. Mapping is
515 * User -> Type -> uid.
516 */
517 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
518
519 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700520 private int mThumbnailWidth;
521 private int mThumbnailHeight;
522 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523
524 /**
525 * Flag that indicates if multi-window is enabled.
526 *
527 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
528 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
529 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
530 * At least one of the forms of multi-window must be enabled in order for this flag to be
531 * initialized to 'true'.
532 *
533 * @see #mSupportsSplitScreenMultiWindow
534 * @see #mSupportsFreeformWindowManagement
535 * @see #mSupportsPictureInPicture
536 * @see #mSupportsMultiDisplay
537 */
538 boolean mSupportsMultiWindow;
539 boolean mSupportsSplitScreenMultiWindow;
540 boolean mSupportsFreeformWindowManagement;
541 boolean mSupportsPictureInPicture;
542 boolean mSupportsMultiDisplay;
543 boolean mForceResizableActivities;
544
545 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
546
547 // VR Vr2d Display Id.
548 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700549
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 /**
551 * Set while we are wanting to sleep, to prevent any
552 * activities from being started/resumed.
553 *
554 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
555 *
556 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
557 * while in the sleep state until there is a pending transition out of sleep, in which case
558 * mSleeping is set to false, and remains false while awake.
559 *
560 * Whether mSleeping can quickly toggled between true/false without the device actually
561 * display changing states is undefined.
562 */
563 private boolean mSleeping = false;
564
565 /**
566 * The process state used for processes that are running the top activities.
567 * This changes between TOP and TOP_SLEEPING to following mSleeping.
568 */
569 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
570
571 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
572 // automatically. Important for devices without direct input devices.
573 private boolean mShowDialogs = true;
574
575 /** Set if we are shutting down the system, similar to sleeping. */
576 boolean mShuttingDown = false;
577
578 /**
579 * We want to hold a wake lock while running a voice interaction session, since
580 * this may happen with the screen off and we need to keep the CPU running to
581 * be able to continue to interact with the user.
582 */
583 PowerManager.WakeLock mVoiceWakeLock;
584
585 /**
586 * Set while we are running a voice interaction. This overrides sleeping while it is active.
587 */
588 IVoiceInteractionSession mRunningVoice;
589
590 /**
591 * The last resumed activity. This is identical to the current resumed activity most
592 * of the time but could be different when we're pausing one activity before we resume
593 * another activity.
594 */
595 ActivityRecord mLastResumedActivity;
596
597 /**
598 * The activity that is currently being traced as the active resumed activity.
599 *
600 * @see #updateResumedAppTrace
601 */
602 private @Nullable ActivityRecord mTracedResumedActivity;
603
604 /** If non-null, we are tracking the time the user spends in the currently focused app. */
605 AppTimeTracker mCurAppTimeTracker;
606
Wale Ogunwale008163e2018-07-23 23:11:08 -0700607 private AppWarnings mAppWarnings;
608
Wale Ogunwale53783742018-09-16 10:21:51 -0700609 /**
610 * Packages that the user has asked to have run in screen size
611 * compatibility mode instead of filling the screen.
612 */
613 CompatModePackages mCompatModePackages;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 private FontScaleSettingObserver mFontScaleSettingObserver;
616
617 private final class FontScaleSettingObserver extends ContentObserver {
618 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
619 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
620
621 public FontScaleSettingObserver() {
622 super(mH);
623 final ContentResolver resolver = mContext.getContentResolver();
624 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
625 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
626 UserHandle.USER_ALL);
627 }
628
629 @Override
630 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
631 if (mFontScaleUri.equals(uri)) {
632 updateFontScaleIfNeeded(userId);
633 } else if (mHideErrorDialogsUri.equals(uri)) {
634 synchronized (mGlobalLock) {
635 updateShouldShowDialogsLocked(getGlobalConfiguration());
636 }
637 }
638 }
639 }
640
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700641 ActivityTaskManagerService(Context context) {
642 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700643 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700644 mSystemThread = ActivityThread.currentActivityThread();
645 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700646 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700647 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700648 }
649
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700650 public void onSystemReady() {
651 synchronized (mGlobalLock) {
652 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
653 PackageManager.FEATURE_CANT_SAVE_STATE);
654 mAssistUtils = new AssistUtils(mContext);
655 mVrController.onSystemReady();
656 mRecentTasks.onSystemReadyLocked();
657 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700658 }
659
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700660 public void onInitPowerManagement() {
661 synchronized (mGlobalLock) {
662 mStackSupervisor.initPowerManagement();
663 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
664 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
665 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
666 mVoiceWakeLock.setReferenceCounted(false);
667 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700668 }
669
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700670 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 mFontScaleSettingObserver = new FontScaleSettingObserver();
672 }
673
Wale Ogunwale59507092018-10-29 09:00:30 -0700674 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700675 final boolean freeformWindowManagement =
676 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
677 || Settings.Global.getInt(
678 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
679
680 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
681 final boolean supportsPictureInPicture = supportsMultiWindow &&
682 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
683 final boolean supportsSplitScreenMultiWindow =
684 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
685 final boolean supportsMultiDisplay = mContext.getPackageManager()
686 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
687 final boolean alwaysFinishActivities =
688 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
689 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
690 final boolean forceResizable = Settings.Global.getInt(
691 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700692 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700693
694 // Transfer any global setting for forcing RTL layout, into a System Property
695 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
696
697 final Configuration configuration = new Configuration();
698 Settings.System.getConfiguration(resolver, configuration);
699 if (forceRtl) {
700 // This will take care of setting the correct layout direction flags
701 configuration.setLayoutDirection(configuration.locale);
702 }
703
704 synchronized (mGlobalLock) {
705 mForceResizableActivities = forceResizable;
706 final boolean multiWindowFormEnabled = freeformWindowManagement
707 || supportsSplitScreenMultiWindow
708 || supportsPictureInPicture
709 || supportsMultiDisplay;
710 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
711 mSupportsMultiWindow = true;
712 mSupportsFreeformWindowManagement = freeformWindowManagement;
713 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
714 mSupportsPictureInPicture = supportsPictureInPicture;
715 mSupportsMultiDisplay = supportsMultiDisplay;
716 } else {
717 mSupportsMultiWindow = false;
718 mSupportsFreeformWindowManagement = false;
719 mSupportsSplitScreenMultiWindow = false;
720 mSupportsPictureInPicture = false;
721 mSupportsMultiDisplay = false;
722 }
723 mWindowManager.setForceResizableTasks(mForceResizableActivities);
724 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700725 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
726 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727 // This happens before any activities are started, so we can change global configuration
728 // in-place.
729 updateConfigurationLocked(configuration, null, true);
730 final Configuration globalConfig = getGlobalConfiguration();
731 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
732
733 // Load resources only after the current configuration has been set.
734 final Resources res = mContext.getResources();
735 mThumbnailWidth = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_width);
737 mThumbnailHeight = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_height);
739
740 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
741 mFullscreenThumbnailScale = (float) res
742 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
743 (float) globalConfig.screenWidthDp;
744 } else {
745 mFullscreenThumbnailScale = res.getFraction(
746 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
747 }
748 }
749 }
750
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800751 public WindowManagerGlobalLock getGlobalLock() {
752 return mGlobalLock;
753 }
754
755 public void setActivityManagerService(IntentFirewall intentFirewall,
756 PendingIntentController intentController) {
757 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700759 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700760 final File systemDir = SystemServiceManager.ensureSystemDir();
761 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
762 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700763 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700764
765 mTempConfig.setToDefaults();
766 mTempConfig.setLocales(LocaleList.getDefault());
767 mConfigurationSeq = mTempConfig.seq = 1;
768 mStackSupervisor = createStackSupervisor();
769 mStackSupervisor.onConfigurationChanged(mTempConfig);
770
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700771 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700773 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700775 mRecentTasks = createRecentTasks();
776 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700777 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700778 mKeyguardController = mStackSupervisor.getKeyguardController();
779 }
780
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700781 public void onActivityManagerInternalAdded() {
782 synchronized (mGlobalLock) {
783 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
784 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
785 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700786 }
787
Yunfan Chen75157d72018-07-27 14:47:21 +0900788 int increaseConfigurationSeqLocked() {
789 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
790 return mConfigurationSeq;
791 }
792
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700793 protected ActivityStackSupervisor createStackSupervisor() {
794 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
795 supervisor.initialize();
796 return supervisor;
797 }
798
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700799 public void setWindowManager(WindowManagerService wm) {
800 synchronized (mGlobalLock) {
801 mWindowManager = wm;
802 mLockTaskController.setWindowManager(wm);
803 mStackSupervisor.setWindowManager(wm);
804 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700805 }
806
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700807 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
808 synchronized (mGlobalLock) {
809 mUsageStatsInternal = usageStatsManager;
810 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 }
812
Wale Ogunwalef6733932018-06-27 05:14:34 -0700813 UserManagerService getUserManager() {
814 if (mUserManager == null) {
815 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
816 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
817 }
818 return mUserManager;
819 }
820
821 AppOpsService getAppOpsService() {
822 if (mAppOpsService == null) {
823 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
824 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
825 }
826 return mAppOpsService;
827 }
828
829 boolean hasUserRestriction(String restriction, int userId) {
830 return getUserManager().hasUserRestriction(restriction, userId);
831 }
832
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700833 protected RecentTasks createRecentTasks() {
834 return new RecentTasks(this, mStackSupervisor);
835 }
836
837 RecentTasks getRecentTasks() {
838 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700839 }
840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 ClientLifecycleManager getLifecycleManager() {
842 return mLifecycleManager;
843 }
844
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700845 ActivityStartController getActivityStartController() {
846 return mActivityStartController;
847 }
848
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700849 TaskChangeNotificationController getTaskChangeNotificationController() {
850 return mTaskChangeNotificationController;
851 }
852
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700853 LockTaskController getLockTaskController() {
854 return mLockTaskController;
855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 /**
858 * Return the global configuration used by the process corresponding to the input pid. This is
859 * usually the global configuration with some overrides specific to that process.
860 */
861 Configuration getGlobalConfigurationForCallingPid() {
862 final int pid = Binder.getCallingPid();
863 if (pid == MY_PID || pid < 0) {
864 return getGlobalConfiguration();
865 }
866 synchronized (mGlobalLock) {
867 final WindowProcessController app = mPidMap.get(pid);
868 return app != null ? app.getConfiguration() : getGlobalConfiguration();
869 }
870 }
871
872 /**
873 * Return the device configuration info used by the process corresponding to the input pid.
874 * The value is consistent with the global configuration for the process.
875 */
876 @Override
877 public ConfigurationInfo getDeviceConfigurationInfo() {
878 ConfigurationInfo config = new ConfigurationInfo();
879 synchronized (mGlobalLock) {
880 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
881 config.reqTouchScreen = globalConfig.touchscreen;
882 config.reqKeyboardType = globalConfig.keyboard;
883 config.reqNavigation = globalConfig.navigation;
884 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
885 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
886 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
887 }
888 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
889 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
890 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
891 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700892 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900893 }
894 return config;
895 }
896
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700897 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700898 mInternal = new LocalService();
899 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700900 }
901
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700902 public static final class Lifecycle extends SystemService {
903 private final ActivityTaskManagerService mService;
904
905 public Lifecycle(Context context) {
906 super(context);
907 mService = new ActivityTaskManagerService(context);
908 }
909
910 @Override
911 public void onStart() {
912 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700913 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700914 }
915
916 public ActivityTaskManagerService getService() {
917 return mService;
918 }
919 }
920
921 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700922 public final int startActivity(IApplicationThread caller, String callingPackage,
923 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
924 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
925 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
926 resultWho, requestCode, startFlags, profilerInfo, bOptions,
927 UserHandle.getCallingUserId());
928 }
929
930 @Override
931 public final int startActivities(IApplicationThread caller, String callingPackage,
932 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
933 int userId) {
934 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700935 enforceNotIsolatedCaller(reason);
936 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700937 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700938 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100939 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
940 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700941 }
942
943 @Override
944 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
945 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
946 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
947 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
948 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
949 true /*validateIncomingUser*/);
950 }
951
952 int startActivityAsUser(IApplicationThread caller, String callingPackage,
953 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
954 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
955 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700956 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700957
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700958 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700959 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
960
961 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700962 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700963 .setCaller(caller)
964 .setCallingPackage(callingPackage)
965 .setResolvedType(resolvedType)
966 .setResultTo(resultTo)
967 .setResultWho(resultWho)
968 .setRequestCode(requestCode)
969 .setStartFlags(startFlags)
970 .setProfilerInfo(profilerInfo)
971 .setActivityOptions(bOptions)
972 .setMayWait(userId)
973 .execute();
974
975 }
976
977 @Override
978 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
979 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700980 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
981 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700982 // Refuse possible leaked file descriptors
983 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
984 throw new IllegalArgumentException("File descriptors passed in Intent");
985 }
986
987 if (!(target instanceof PendingIntentRecord)) {
988 throw new IllegalArgumentException("Bad PendingIntent object");
989 }
990
991 PendingIntentRecord pir = (PendingIntentRecord)target;
992
993 synchronized (mGlobalLock) {
994 // If this is coming from the currently resumed activity, it is
995 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700996 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700997 if (stack.mResumedActivity != null &&
998 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700999 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001000 }
1001 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001002 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001003 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 }
1005
1006 @Override
1007 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1008 Bundle bOptions) {
1009 // Refuse possible leaked file descriptors
1010 if (intent != null && intent.hasFileDescriptors()) {
1011 throw new IllegalArgumentException("File descriptors passed in Intent");
1012 }
1013 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1014
1015 synchronized (mGlobalLock) {
1016 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1017 if (r == null) {
1018 SafeActivityOptions.abort(options);
1019 return false;
1020 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001021 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 // The caller is not running... d'oh!
1023 SafeActivityOptions.abort(options);
1024 return false;
1025 }
1026 intent = new Intent(intent);
1027 // The caller is not allowed to change the data.
1028 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1029 // And we are resetting to find the next component...
1030 intent.setComponent(null);
1031
1032 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1033
1034 ActivityInfo aInfo = null;
1035 try {
1036 List<ResolveInfo> resolves =
1037 AppGlobals.getPackageManager().queryIntentActivities(
1038 intent, r.resolvedType,
1039 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1040 UserHandle.getCallingUserId()).getList();
1041
1042 // Look for the original activity in the list...
1043 final int N = resolves != null ? resolves.size() : 0;
1044 for (int i=0; i<N; i++) {
1045 ResolveInfo rInfo = resolves.get(i);
1046 if (rInfo.activityInfo.packageName.equals(r.packageName)
1047 && rInfo.activityInfo.name.equals(r.info.name)) {
1048 // We found the current one... the next matching is
1049 // after it.
1050 i++;
1051 if (i<N) {
1052 aInfo = resolves.get(i).activityInfo;
1053 }
1054 if (debug) {
1055 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1056 + "/" + r.info.name);
1057 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1058 ? "null" : aInfo.packageName + "/" + aInfo.name));
1059 }
1060 break;
1061 }
1062 }
1063 } catch (RemoteException e) {
1064 }
1065
1066 if (aInfo == null) {
1067 // Nobody who is next!
1068 SafeActivityOptions.abort(options);
1069 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1070 return false;
1071 }
1072
1073 intent.setComponent(new ComponentName(
1074 aInfo.applicationInfo.packageName, aInfo.name));
1075 intent.setFlags(intent.getFlags()&~(
1076 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1077 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1078 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1079 FLAG_ACTIVITY_NEW_TASK));
1080
1081 // Okay now we need to start the new activity, replacing the currently running activity.
1082 // This is a little tricky because we want to start the new one as if the current one is
1083 // finished, but not finish the current one first so that there is no flicker.
1084 // And thus...
1085 final boolean wasFinishing = r.finishing;
1086 r.finishing = true;
1087
1088 // Propagate reply information over to the new activity.
1089 final ActivityRecord resultTo = r.resultTo;
1090 final String resultWho = r.resultWho;
1091 final int requestCode = r.requestCode;
1092 r.resultTo = null;
1093 if (resultTo != null) {
1094 resultTo.removeResultsLocked(r, resultWho, requestCode);
1095 }
1096
1097 final long origId = Binder.clearCallingIdentity();
1098 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001099 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001100 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001101 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001102 .setResolvedType(r.resolvedType)
1103 .setActivityInfo(aInfo)
1104 .setResultTo(resultTo != null ? resultTo.appToken : null)
1105 .setResultWho(resultWho)
1106 .setRequestCode(requestCode)
1107 .setCallingPid(-1)
1108 .setCallingUid(r.launchedFromUid)
1109 .setCallingPackage(r.launchedFromPackage)
1110 .setRealCallingPid(-1)
1111 .setRealCallingUid(r.launchedFromUid)
1112 .setActivityOptions(options)
1113 .execute();
1114 Binder.restoreCallingIdentity(origId);
1115
1116 r.finishing = wasFinishing;
1117 if (res != ActivityManager.START_SUCCESS) {
1118 return false;
1119 }
1120 return true;
1121 }
1122 }
1123
1124 @Override
1125 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1126 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1127 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1128 final WaitResult res = new WaitResult();
1129 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001130 enforceNotIsolatedCaller("startActivityAndWait");
1131 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1132 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001133 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001134 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 .setCaller(caller)
1136 .setCallingPackage(callingPackage)
1137 .setResolvedType(resolvedType)
1138 .setResultTo(resultTo)
1139 .setResultWho(resultWho)
1140 .setRequestCode(requestCode)
1141 .setStartFlags(startFlags)
1142 .setActivityOptions(bOptions)
1143 .setMayWait(userId)
1144 .setProfilerInfo(profilerInfo)
1145 .setWaitResult(res)
1146 .execute();
1147 }
1148 return res;
1149 }
1150
1151 @Override
1152 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1153 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1154 int startFlags, Configuration config, Bundle bOptions, int userId) {
1155 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001156 enforceNotIsolatedCaller("startActivityWithConfig");
1157 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1158 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001159 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001160 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001161 .setCaller(caller)
1162 .setCallingPackage(callingPackage)
1163 .setResolvedType(resolvedType)
1164 .setResultTo(resultTo)
1165 .setResultWho(resultWho)
1166 .setRequestCode(requestCode)
1167 .setStartFlags(startFlags)
1168 .setGlobalConfiguration(config)
1169 .setActivityOptions(bOptions)
1170 .setMayWait(userId)
1171 .execute();
1172 }
1173 }
1174
Alison Cichowlas3e340502018-08-07 17:15:01 -04001175
1176 @Override
1177 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1178 int callingUid = Binder.getCallingUid();
1179 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1180 throw new SecurityException("Only the system process can request a permission token, "
1181 + "received request from uid: " + callingUid);
1182 }
1183 IBinder permissionToken = new Binder();
1184 synchronized (mGlobalLock) {
1185 mStartActivitySources.put(permissionToken, delegatorToken);
1186 }
1187
1188 Message expireMsg = PooledLambda.obtainMessage(
1189 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1190 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1191
1192 Message forgetMsg = PooledLambda.obtainMessage(
1193 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1194 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1195
1196 return permissionToken;
1197 }
1198
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001199 @Override
1200 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1201 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001202 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1203 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001204 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001205 // permission grants) as any app that may launch one of your own activities. So we only
1206 // allow this in two cases:
1207 // 1) The caller is an activity that is part of the core framework, and then only when it
1208 // is running as the system.
1209 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1210 // can only be requested by a system activity, which may then delegate this call to
1211 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 final ActivityRecord sourceRecord;
1213 final int targetUid;
1214 final String targetPackage;
1215 final boolean isResolver;
1216 synchronized (mGlobalLock) {
1217 if (resultTo == null) {
1218 throw new SecurityException("Must be called from an activity");
1219 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001220 final IBinder sourceToken;
1221 if (permissionToken != null) {
1222 // To even attempt to use a permissionToken, an app must also have this signature
1223 // permission.
1224 mAmInternal.enforceCallingPermission(
1225 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1226 "startActivityAsCaller");
1227 // If called with a permissionToken, we want the sourceRecord from the delegator
1228 // activity that requested this token.
1229 sourceToken = mStartActivitySources.remove(permissionToken);
1230 if (sourceToken == null) {
1231 // Invalid permissionToken, check if it recently expired.
1232 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1233 throw new SecurityException("Called with expired permission token: "
1234 + permissionToken);
1235 } else {
1236 throw new SecurityException("Called with invalid permission token: "
1237 + permissionToken);
1238 }
1239 }
1240 } else {
1241 // This method was called directly by the source.
1242 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001243 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001244
1245 sourceRecord = mStackSupervisor.isInAnyStackLocked(sourceToken);
1246 if (sourceRecord == null) {
1247 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001248 }
1249 if (sourceRecord.app == null) {
1250 throw new SecurityException("Called without a process attached to activity");
1251 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001252
1253 // Whether called directly or from a delegate, the source activity must be from the
1254 // android package.
1255 if (!sourceRecord.info.packageName.equals("android")) {
1256 throw new SecurityException("Must be called from an activity that is "
1257 + "declared in the android package");
1258 }
1259
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001260 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001261 // This is still okay, as long as this activity is running under the
1262 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001263 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001265 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 + " must be system uid or original calling uid "
1267 + sourceRecord.launchedFromUid);
1268 }
1269 }
1270 if (ignoreTargetSecurity) {
1271 if (intent.getComponent() == null) {
1272 throw new SecurityException(
1273 "Component must be specified with ignoreTargetSecurity");
1274 }
1275 if (intent.getSelector() != null) {
1276 throw new SecurityException(
1277 "Selector not allowed with ignoreTargetSecurity");
1278 }
1279 }
1280 targetUid = sourceRecord.launchedFromUid;
1281 targetPackage = sourceRecord.launchedFromPackage;
1282 isResolver = sourceRecord.isResolverOrChildActivity();
1283 }
1284
1285 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001286 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 }
1288
1289 // TODO: Switch to user app stacks here.
1290 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001291 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 .setCallingUid(targetUid)
1293 .setCallingPackage(targetPackage)
1294 .setResolvedType(resolvedType)
1295 .setResultTo(resultTo)
1296 .setResultWho(resultWho)
1297 .setRequestCode(requestCode)
1298 .setStartFlags(startFlags)
1299 .setActivityOptions(bOptions)
1300 .setMayWait(userId)
1301 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1302 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1303 .execute();
1304 } catch (SecurityException e) {
1305 // XXX need to figure out how to propagate to original app.
1306 // A SecurityException here is generally actually a fault of the original
1307 // calling activity (such as a fairly granting permissions), so propagate it
1308 // back to them.
1309 /*
1310 StringBuilder msg = new StringBuilder();
1311 msg.append("While launching");
1312 msg.append(intent.toString());
1313 msg.append(": ");
1314 msg.append(e.getMessage());
1315 */
1316 throw e;
1317 }
1318 }
1319
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001320 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1321 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1322 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1323 }
1324
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 @Override
1326 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1327 Intent intent, String resolvedType, IVoiceInteractionSession session,
1328 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1329 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001330 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001331 if (session == null || interactor == null) {
1332 throw new NullPointerException("null session or interactor");
1333 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001334 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001336 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 .setCallingUid(callingUid)
1338 .setCallingPackage(callingPackage)
1339 .setResolvedType(resolvedType)
1340 .setVoiceSession(session)
1341 .setVoiceInteractor(interactor)
1342 .setStartFlags(startFlags)
1343 .setProfilerInfo(profilerInfo)
1344 .setActivityOptions(bOptions)
1345 .setMayWait(userId)
1346 .execute();
1347 }
1348
1349 @Override
1350 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1351 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001352 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1353 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001355 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 .setCallingUid(callingUid)
1357 .setCallingPackage(callingPackage)
1358 .setResolvedType(resolvedType)
1359 .setActivityOptions(bOptions)
1360 .setMayWait(userId)
1361 .execute();
1362 }
1363
1364 @Override
1365 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1366 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 final int callingPid = Binder.getCallingPid();
1369 final long origId = Binder.clearCallingIdentity();
1370 try {
1371 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001372 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1373 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374
1375 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001376 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1377 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1379 recentsUid, assistDataReceiver);
1380 }
1381 } finally {
1382 Binder.restoreCallingIdentity(origId);
1383 }
1384 }
1385
1386 @Override
1387 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001388 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 "startActivityFromRecents()");
1390
1391 final int callingPid = Binder.getCallingPid();
1392 final int callingUid = Binder.getCallingUid();
1393 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1394 final long origId = Binder.clearCallingIdentity();
1395 try {
1396 synchronized (mGlobalLock) {
1397 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1398 safeOptions);
1399 }
1400 } finally {
1401 Binder.restoreCallingIdentity(origId);
1402 }
1403 }
1404
1405 /**
1406 * This is the internal entry point for handling Activity.finish().
1407 *
1408 * @param token The Binder token referencing the Activity we want to finish.
1409 * @param resultCode Result code, if any, from this Activity.
1410 * @param resultData Result data (Intent), if any, from this Activity.
1411 * @param finishTask Whether to finish the task associated with this Activity.
1412 *
1413 * @return Returns true if the activity successfully finished, or false if it is still running.
1414 */
1415 @Override
1416 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1417 int finishTask) {
1418 // Refuse possible leaked file descriptors
1419 if (resultData != null && resultData.hasFileDescriptors()) {
1420 throw new IllegalArgumentException("File descriptors passed in Intent");
1421 }
1422
1423 synchronized (mGlobalLock) {
1424 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1425 if (r == null) {
1426 return true;
1427 }
1428 // Keep track of the root activity of the task before we finish it
1429 TaskRecord tr = r.getTask();
1430 ActivityRecord rootR = tr.getRootActivity();
1431 if (rootR == null) {
1432 Slog.w(TAG, "Finishing task with all activities already finished");
1433 }
1434 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1435 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001436 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 return false;
1438 }
1439
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001440 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1441 // We should consolidate.
1442 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 // Find the first activity that is not finishing.
1444 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1445 if (next != null) {
1446 // ask watcher if this is allowed
1447 boolean resumeOK = true;
1448 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001451 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 Watchdog.getInstance().setActivityController(null);
1453 }
1454
1455 if (!resumeOK) {
1456 Slog.i(TAG, "Not finishing activity because controller resumed");
1457 return false;
1458 }
1459 }
1460 }
1461 final long origId = Binder.clearCallingIdentity();
1462 try {
1463 boolean res;
1464 final boolean finishWithRootActivity =
1465 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1466 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1467 || (finishWithRootActivity && r == rootR)) {
1468 // If requested, remove the task that is associated to this activity only if it
1469 // was the root activity in the task. The result code and data is ignored
1470 // because we don't support returning them across task boundaries. Also, to
1471 // keep backwards compatibility we remove the task from recents when finishing
1472 // task with root activity.
1473 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1474 finishWithRootActivity, "finish-activity");
1475 if (!res) {
1476 Slog.i(TAG, "Removing task failed to finish activity");
1477 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001478 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001479 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 } else {
1481 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1482 resultData, "app-request", true);
1483 if (!res) {
1484 Slog.i(TAG, "Failed to finish by app-request");
1485 }
1486 }
1487 return res;
1488 } finally {
1489 Binder.restoreCallingIdentity(origId);
1490 }
1491 }
1492 }
1493
1494 @Override
1495 public boolean finishActivityAffinity(IBinder token) {
1496 synchronized (mGlobalLock) {
1497 final long origId = Binder.clearCallingIdentity();
1498 try {
1499 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1500 if (r == null) {
1501 return false;
1502 }
1503
1504 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1505 // can finish.
1506 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001507 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 return false;
1509 }
1510 return task.getStack().finishActivityAffinityLocked(r);
1511 } finally {
1512 Binder.restoreCallingIdentity(origId);
1513 }
1514 }
1515 }
1516
1517 @Override
1518 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1519 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001520 try {
1521 WindowProcessController proc = null;
1522 synchronized (mGlobalLock) {
1523 ActivityStack stack = ActivityRecord.getStackLocked(token);
1524 if (stack == null) {
1525 return;
1526 }
1527 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1528 false /* fromTimeout */, false /* processPausingActivities */, config);
1529 if (r != null) {
1530 proc = r.app;
1531 }
1532 if (stopProfiling && proc != null) {
1533 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 }
1535 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001536 } finally {
1537 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 }
1540
1541 @Override
1542 public final void activityResumed(IBinder token) {
1543 final long origId = Binder.clearCallingIdentity();
1544 synchronized (mGlobalLock) {
1545 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001546 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 }
1548 Binder.restoreCallingIdentity(origId);
1549 }
1550
1551 @Override
1552 public final void activityPaused(IBinder token) {
1553 final long origId = Binder.clearCallingIdentity();
1554 synchronized (mGlobalLock) {
1555 ActivityStack stack = ActivityRecord.getStackLocked(token);
1556 if (stack != null) {
1557 stack.activityPausedLocked(token, false);
1558 }
1559 }
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562
1563 @Override
1564 public final void activityStopped(IBinder token, Bundle icicle,
1565 PersistableBundle persistentState, CharSequence description) {
1566 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1567
1568 // Refuse possible leaked file descriptors
1569 if (icicle != null && icicle.hasFileDescriptors()) {
1570 throw new IllegalArgumentException("File descriptors passed in Bundle");
1571 }
1572
1573 final long origId = Binder.clearCallingIdentity();
1574
1575 synchronized (mGlobalLock) {
1576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1577 if (r != null) {
1578 r.activityStoppedLocked(icicle, persistentState, description);
1579 }
1580 }
1581
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001582 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583
1584 Binder.restoreCallingIdentity(origId);
1585 }
1586
1587 @Override
1588 public final void activityDestroyed(IBinder token) {
1589 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1590 synchronized (mGlobalLock) {
1591 ActivityStack stack = ActivityRecord.getStackLocked(token);
1592 if (stack != null) {
1593 stack.activityDestroyedLocked(token, "activityDestroyed");
1594 }
1595 }
1596 }
1597
1598 @Override
1599 public final void activityRelaunched(IBinder token) {
1600 final long origId = Binder.clearCallingIdentity();
1601 synchronized (mGlobalLock) {
1602 mStackSupervisor.activityRelaunchedLocked(token);
1603 }
1604 Binder.restoreCallingIdentity(origId);
1605 }
1606
1607 public final void activitySlept(IBinder token) {
1608 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1609
1610 final long origId = Binder.clearCallingIdentity();
1611
1612 synchronized (mGlobalLock) {
1613 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1614 if (r != null) {
1615 mStackSupervisor.activitySleptLocked(r);
1616 }
1617 }
1618
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1624 synchronized (mGlobalLock) {
1625 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1626 if (r == null) {
1627 return;
1628 }
1629 final long origId = Binder.clearCallingIdentity();
1630 try {
1631 r.setRequestedOrientation(requestedOrientation);
1632 } finally {
1633 Binder.restoreCallingIdentity(origId);
1634 }
1635 }
1636 }
1637
1638 @Override
1639 public int getRequestedOrientation(IBinder token) {
1640 synchronized (mGlobalLock) {
1641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1642 if (r == null) {
1643 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1644 }
1645 return r.getRequestedOrientation();
1646 }
1647 }
1648
1649 @Override
1650 public void setImmersive(IBinder token, boolean immersive) {
1651 synchronized (mGlobalLock) {
1652 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1653 if (r == null) {
1654 throw new IllegalArgumentException();
1655 }
1656 r.immersive = immersive;
1657
1658 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001659 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001661 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 }
1663 }
1664 }
1665
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001666 void applyUpdateLockStateLocked(ActivityRecord r) {
1667 // Modifications to the UpdateLock state are done on our handler, outside
1668 // the activity manager's locks. The new state is determined based on the
1669 // state *now* of the relevant activity record. The object is passed to
1670 // the handler solely for logging detail, not to be consulted/modified.
1671 final boolean nextState = r != null && r.immersive;
1672 mH.post(() -> {
1673 if (mUpdateLock.isHeld() != nextState) {
1674 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1675 "Applying new update lock state '" + nextState + "' for " + r);
1676 if (nextState) {
1677 mUpdateLock.acquire();
1678 } else {
1679 mUpdateLock.release();
1680 }
1681 }
1682 });
1683 }
1684
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 @Override
1686 public boolean isImmersive(IBinder token) {
1687 synchronized (mGlobalLock) {
1688 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1689 if (r == null) {
1690 throw new IllegalArgumentException();
1691 }
1692 return r.immersive;
1693 }
1694 }
1695
1696 @Override
1697 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001698 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001699 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001700 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 return (r != null) ? r.immersive : false;
1702 }
1703 }
1704
1705 @Override
1706 public void overridePendingTransition(IBinder token, String packageName,
1707 int enterAnim, int exitAnim) {
1708 synchronized (mGlobalLock) {
1709 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1710 if (self == null) {
1711 return;
1712 }
1713
1714 final long origId = Binder.clearCallingIdentity();
1715
1716 if (self.isState(
1717 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001718 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1719 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 }
1721
1722 Binder.restoreCallingIdentity(origId);
1723 }
1724 }
1725
1726 @Override
1727 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001728 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001730 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001731 if (r == null) {
1732 return ActivityManager.COMPAT_MODE_UNKNOWN;
1733 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001734 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 }
1736 }
1737
1738 @Override
1739 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001740 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001741 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001742 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001743 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001744 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001745 if (r == null) {
1746 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1747 return;
1748 }
1749 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001750 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001751 }
1752 }
1753
1754 @Override
1755 public int getLaunchedFromUid(IBinder activityToken) {
1756 ActivityRecord srec;
1757 synchronized (mGlobalLock) {
1758 srec = ActivityRecord.forTokenLocked(activityToken);
1759 }
1760 if (srec == null) {
1761 return -1;
1762 }
1763 return srec.launchedFromUid;
1764 }
1765
1766 @Override
1767 public String getLaunchedFromPackage(IBinder activityToken) {
1768 ActivityRecord srec;
1769 synchronized (mGlobalLock) {
1770 srec = ActivityRecord.forTokenLocked(activityToken);
1771 }
1772 if (srec == null) {
1773 return null;
1774 }
1775 return srec.launchedFromPackage;
1776 }
1777
1778 @Override
1779 public boolean convertFromTranslucent(IBinder token) {
1780 final long origId = Binder.clearCallingIdentity();
1781 try {
1782 synchronized (mGlobalLock) {
1783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1784 if (r == null) {
1785 return false;
1786 }
1787 final boolean translucentChanged = r.changeWindowTranslucency(true);
1788 if (translucentChanged) {
1789 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1790 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001791 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001792 return translucentChanged;
1793 }
1794 } finally {
1795 Binder.restoreCallingIdentity(origId);
1796 }
1797 }
1798
1799 @Override
1800 public boolean convertToTranslucent(IBinder token, Bundle options) {
1801 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1802 final long origId = Binder.clearCallingIdentity();
1803 try {
1804 synchronized (mGlobalLock) {
1805 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1806 if (r == null) {
1807 return false;
1808 }
1809 final TaskRecord task = r.getTask();
1810 int index = task.mActivities.lastIndexOf(r);
1811 if (index > 0) {
1812 ActivityRecord under = task.mActivities.get(index - 1);
1813 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1814 }
1815 final boolean translucentChanged = r.changeWindowTranslucency(false);
1816 if (translucentChanged) {
1817 r.getStack().convertActivityToTranslucent(r);
1818 }
1819 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001820 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 return translucentChanged;
1822 }
1823 } finally {
1824 Binder.restoreCallingIdentity(origId);
1825 }
1826 }
1827
1828 @Override
1829 public void notifyActivityDrawn(IBinder token) {
1830 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1831 synchronized (mGlobalLock) {
1832 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1833 if (r != null) {
1834 r.getStack().notifyActivityDrawnLocked(r);
1835 }
1836 }
1837 }
1838
1839 @Override
1840 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1841 synchronized (mGlobalLock) {
1842 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1843 if (r == null) {
1844 return;
1845 }
1846 r.reportFullyDrawnLocked(restoredFromBundle);
1847 }
1848 }
1849
1850 @Override
1851 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1852 synchronized (mGlobalLock) {
1853 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1854 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1855 return stack.mDisplayId;
1856 }
1857 return DEFAULT_DISPLAY;
1858 }
1859 }
1860
1861 @Override
1862 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001863 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 long ident = Binder.clearCallingIdentity();
1865 try {
1866 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001867 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 if (focusedStack != null) {
1869 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1870 }
1871 return null;
1872 }
1873 } finally {
1874 Binder.restoreCallingIdentity(ident);
1875 }
1876 }
1877
1878 @Override
1879 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001880 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1882 final long callingId = Binder.clearCallingIdentity();
1883 try {
1884 synchronized (mGlobalLock) {
1885 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1886 if (stack == null) {
1887 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1888 return;
1889 }
1890 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001891 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001892 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 }
1894 }
1895 } finally {
1896 Binder.restoreCallingIdentity(callingId);
1897 }
1898 }
1899
1900 @Override
1901 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001902 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1904 final long callingId = Binder.clearCallingIdentity();
1905 try {
1906 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001907 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1908 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 if (task == null) {
1910 return;
1911 }
1912 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001913 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001914 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 }
1916 }
1917 } finally {
1918 Binder.restoreCallingIdentity(callingId);
1919 }
1920 }
1921
1922 @Override
1923 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001924 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 synchronized (mGlobalLock) {
1926 final long ident = Binder.clearCallingIdentity();
1927 try {
1928 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1929 "remove-task");
1930 } finally {
1931 Binder.restoreCallingIdentity(ident);
1932 }
1933 }
1934 }
1935
1936 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001937 public void removeAllVisibleRecentTasks() {
1938 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1939 synchronized (mGlobalLock) {
1940 final long ident = Binder.clearCallingIdentity();
1941 try {
1942 getRecentTasks().removeAllVisibleTasks();
1943 } finally {
1944 Binder.restoreCallingIdentity(ident);
1945 }
1946 }
1947 }
1948
1949 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1951 synchronized (mGlobalLock) {
1952 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1953 if (srec != null) {
1954 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1955 }
1956 }
1957 return false;
1958 }
1959
1960 @Override
1961 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1962 Intent resultData) {
1963
1964 synchronized (mGlobalLock) {
1965 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1966 if (r != null) {
1967 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1968 }
1969 return false;
1970 }
1971 }
1972
1973 /**
1974 * Attempts to move a task backwards in z-order (the order of activities within the task is
1975 * unchanged).
1976 *
1977 * There are several possible results of this call:
1978 * - if the task is locked, then we will show the lock toast
1979 * - if there is a task behind the provided task, then that task is made visible and resumed as
1980 * this task is moved to the back
1981 * - otherwise, if there are no other tasks in the stack:
1982 * - if this task is in the pinned stack, then we remove the stack completely, which will
1983 * have the effect of moving the task to the top or bottom of the fullscreen stack
1984 * (depending on whether it is visible)
1985 * - otherwise, we simply return home and hide this task
1986 *
1987 * @param token A reference to the activity we wish to move
1988 * @param nonRoot If false then this only works if the activity is the root
1989 * of a task; if true it will work for any activity in a task.
1990 * @return Returns true if the move completed, false if not.
1991 */
1992 @Override
1993 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001994 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 synchronized (mGlobalLock) {
1996 final long origId = Binder.clearCallingIdentity();
1997 try {
1998 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1999 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2000 if (task != null) {
2001 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2002 }
2003 } finally {
2004 Binder.restoreCallingIdentity(origId);
2005 }
2006 }
2007 return false;
2008 }
2009
2010 @Override
2011 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002012 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 long ident = Binder.clearCallingIdentity();
2014 Rect rect = new Rect();
2015 try {
2016 synchronized (mGlobalLock) {
2017 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2018 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2019 if (task == null) {
2020 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2021 return rect;
2022 }
2023 if (task.getStack() != null) {
2024 // Return the bounds from window manager since it will be adjusted for various
2025 // things like the presense of a docked stack for tasks that aren't resizeable.
2026 task.getWindowContainerBounds(rect);
2027 } else {
2028 // Task isn't in window manager yet since it isn't associated with a stack.
2029 // Return the persist value from activity manager
2030 if (!task.matchParentBounds()) {
2031 rect.set(task.getBounds());
2032 } else if (task.mLastNonFullscreenBounds != null) {
2033 rect.set(task.mLastNonFullscreenBounds);
2034 }
2035 }
2036 }
2037 } finally {
2038 Binder.restoreCallingIdentity(ident);
2039 }
2040 return rect;
2041 }
2042
2043 @Override
2044 public ActivityManager.TaskDescription getTaskDescription(int id) {
2045 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002046 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
2048 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
2049 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2050 if (tr != null) {
2051 return tr.lastTaskDescription;
2052 }
2053 }
2054 return null;
2055 }
2056
2057 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002058 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2059 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2060 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2061 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2062 return;
2063 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002064 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002065 synchronized (mGlobalLock) {
2066 final long ident = Binder.clearCallingIdentity();
2067 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002068 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2069 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002070 if (task == null) {
2071 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2072 return;
2073 }
2074
2075 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2076 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2077
2078 if (!task.isActivityTypeStandardOrUndefined()) {
2079 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2080 + " non-standard task " + taskId + " to windowing mode="
2081 + windowingMode);
2082 }
2083
2084 final ActivityStack stack = task.getStack();
2085 if (toTop) {
2086 stack.moveToFront("setTaskWindowingMode", task);
2087 }
2088 stack.setWindowingMode(windowingMode);
2089 } finally {
2090 Binder.restoreCallingIdentity(ident);
2091 }
2092 }
2093 }
2094
2095 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002097 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002098 ActivityRecord r = getCallingRecordLocked(token);
2099 return r != null ? r.info.packageName : null;
2100 }
2101 }
2102
2103 @Override
2104 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002105 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 ActivityRecord r = getCallingRecordLocked(token);
2107 return r != null ? r.intent.getComponent() : null;
2108 }
2109 }
2110
2111 private ActivityRecord getCallingRecordLocked(IBinder token) {
2112 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2113 if (r == null) {
2114 return null;
2115 }
2116 return r.resultTo;
2117 }
2118
2119 @Override
2120 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002121 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122
2123 synchronized (mGlobalLock) {
2124 final long origId = Binder.clearCallingIdentity();
2125 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002126 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 } finally {
2128 Binder.restoreCallingIdentity(origId);
2129 }
2130 }
2131 }
2132
2133 /**
2134 * TODO: Add mController hook
2135 */
2136 @Override
2137 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002138 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002139
2140 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2141 synchronized (mGlobalLock) {
2142 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2143 false /* fromRecents */);
2144 }
2145 }
2146
2147 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2148 boolean fromRecents) {
2149
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002150 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151 Binder.getCallingUid(), -1, -1, "Task to front")) {
2152 SafeActivityOptions.abort(options);
2153 return;
2154 }
2155 final long origId = Binder.clearCallingIdentity();
2156 try {
2157 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2158 if (task == null) {
2159 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002160 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 return;
2162 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002163 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002165 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 return;
2167 }
2168 ActivityOptions realOptions = options != null
2169 ? options.getOptions(mStackSupervisor)
2170 : null;
2171 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2172 false /* forceNonResizable */);
2173
2174 final ActivityRecord topActivity = task.getTopActivity();
2175 if (topActivity != null) {
2176
2177 // We are reshowing a task, use a starting window to hide the initial draw delay
2178 // so the transition can start earlier.
2179 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2180 true /* taskSwitch */, fromRecents);
2181 }
2182 } finally {
2183 Binder.restoreCallingIdentity(origId);
2184 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 }
2186
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002187 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2188 int callingPid, int callingUid, String name) {
2189 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2190 return true;
2191 }
2192
2193 if (getRecentTasks().isCallerRecents(sourceUid)) {
2194 return true;
2195 }
2196
2197 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2198 if (perm == PackageManager.PERMISSION_GRANTED) {
2199 return true;
2200 }
2201 if (checkAllowAppSwitchUid(sourceUid)) {
2202 return true;
2203 }
2204
2205 // If the actual IPC caller is different from the logical source, then
2206 // also see if they are allowed to control app switches.
2207 if (callingUid != -1 && callingUid != sourceUid) {
2208 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2209 if (perm == PackageManager.PERMISSION_GRANTED) {
2210 return true;
2211 }
2212 if (checkAllowAppSwitchUid(callingUid)) {
2213 return true;
2214 }
2215 }
2216
2217 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2218 return false;
2219 }
2220
2221 private boolean checkAllowAppSwitchUid(int uid) {
2222 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2223 if (types != null) {
2224 for (int i = types.size() - 1; i >= 0; i--) {
2225 if (types.valueAt(i).intValue() == uid) {
2226 return true;
2227 }
2228 }
2229 }
2230 return false;
2231 }
2232
2233 @Override
2234 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2235 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2236 "setActivityController()");
2237 synchronized (mGlobalLock) {
2238 mController = controller;
2239 mControllerIsAMonkey = imAMonkey;
2240 Watchdog.getInstance().setActivityController(controller);
2241 }
2242 }
2243
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002244 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002245 synchronized (mGlobalLock) {
2246 return mController != null && mControllerIsAMonkey;
2247 }
2248 }
2249
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 @Override
2251 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2252 synchronized (mGlobalLock) {
2253 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2254 }
2255 }
2256
2257 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002258 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2259 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2260 }
2261
2262 @Override
2263 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2264 @WindowConfiguration.ActivityType int ignoreActivityType,
2265 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2266 final int callingUid = Binder.getCallingUid();
2267 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2268
2269 synchronized (mGlobalLock) {
2270 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2271
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002272 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002273 callingUid);
2274 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2275 ignoreWindowingMode, callingUid, allowed);
2276 }
2277
2278 return list;
2279 }
2280
2281 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002282 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2283 synchronized (mGlobalLock) {
2284 final long origId = Binder.clearCallingIdentity();
2285 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2286 if (r != null) {
2287 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2288 }
2289 Binder.restoreCallingIdentity(origId);
2290 }
2291 }
2292
2293 @Override
2294 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002295 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002296 ActivityStack stack = ActivityRecord.getStackLocked(token);
2297 if (stack != null) {
2298 return stack.willActivityBeVisibleLocked(token);
2299 }
2300 return false;
2301 }
2302 }
2303
2304 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002305 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002307 synchronized (mGlobalLock) {
2308 final long ident = Binder.clearCallingIdentity();
2309 try {
2310 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2311 if (task == null) {
2312 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2313 return;
2314 }
2315
2316 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2317 + " to stackId=" + stackId + " toTop=" + toTop);
2318
2319 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2320 if (stack == null) {
2321 throw new IllegalStateException(
2322 "moveTaskToStack: No stack for stackId=" + stackId);
2323 }
2324 if (!stack.isActivityTypeStandardOrUndefined()) {
2325 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2326 + taskId + " to stack " + stackId);
2327 }
2328 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002329 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2331 }
2332 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2333 "moveTaskToStack");
2334 } finally {
2335 Binder.restoreCallingIdentity(ident);
2336 }
2337 }
2338 }
2339
2340 @Override
2341 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2342 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002343 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002344
2345 final long ident = Binder.clearCallingIdentity();
2346 try {
2347 synchronized (mGlobalLock) {
2348 if (animate) {
2349 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2350 if (stack == null) {
2351 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2352 return;
2353 }
2354 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2355 throw new IllegalArgumentException("Stack: " + stackId
2356 + " doesn't support animated resize.");
2357 }
2358 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2359 animationDuration, false /* fromFullscreen */);
2360 } else {
2361 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2362 if (stack == null) {
2363 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2364 return;
2365 }
2366 mStackSupervisor.resizeStackLocked(stack, destBounds,
2367 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2368 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2369 }
2370 }
2371 } finally {
2372 Binder.restoreCallingIdentity(ident);
2373 }
2374 }
2375
2376 /**
2377 * Moves the specified task to the primary-split-screen stack.
2378 *
2379 * @param taskId Id of task to move.
2380 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2381 * exist already. See
2382 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2383 * and
2384 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2385 * @param toTop If the task and stack should be moved to the top.
2386 * @param animate Whether we should play an animation for the moving the task.
2387 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2388 * stack. Pass {@code null} to use default bounds.
2389 * @param showRecents If the recents activity should be shown on the other side of the task
2390 * going into split-screen mode.
2391 */
2392 @Override
2393 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2394 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002395 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002396 "setTaskWindowingModeSplitScreenPrimary()");
2397 synchronized (mGlobalLock) {
2398 final long ident = Binder.clearCallingIdentity();
2399 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002400 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2401 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402 if (task == null) {
2403 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2404 return false;
2405 }
2406 if (DEBUG_STACK) Slog.d(TAG_STACK,
2407 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2408 + " to createMode=" + createMode + " toTop=" + toTop);
2409 if (!task.isActivityTypeStandardOrUndefined()) {
2410 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2411 + " non-standard task " + taskId + " to split-screen windowing mode");
2412 }
2413
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002414 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002415 final int windowingMode = task.getWindowingMode();
2416 final ActivityStack stack = task.getStack();
2417 if (toTop) {
2418 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2419 }
2420 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2421 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2422 return windowingMode != task.getWindowingMode();
2423 } finally {
2424 Binder.restoreCallingIdentity(ident);
2425 }
2426 }
2427 }
2428
2429 /**
2430 * Removes stacks in the input windowing modes from the system if they are of activity type
2431 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2432 */
2433 @Override
2434 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002436 "removeStacksInWindowingModes()");
2437
2438 synchronized (mGlobalLock) {
2439 final long ident = Binder.clearCallingIdentity();
2440 try {
2441 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2442 } finally {
2443 Binder.restoreCallingIdentity(ident);
2444 }
2445 }
2446 }
2447
2448 @Override
2449 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002450 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002451 "removeStacksWithActivityTypes()");
2452
2453 synchronized (mGlobalLock) {
2454 final long ident = Binder.clearCallingIdentity();
2455 try {
2456 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2457 } finally {
2458 Binder.restoreCallingIdentity(ident);
2459 }
2460 }
2461 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002462
2463 @Override
2464 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2465 int userId) {
2466 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002467 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2468 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002469 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002470 final boolean detailed = checkGetTasksPermission(
2471 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2472 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002473 == PackageManager.PERMISSION_GRANTED;
2474
2475 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002476 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002477 callingUid);
2478 }
2479 }
2480
2481 @Override
2482 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002483 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002484 long ident = Binder.clearCallingIdentity();
2485 try {
2486 synchronized (mGlobalLock) {
2487 return mStackSupervisor.getAllStackInfosLocked();
2488 }
2489 } finally {
2490 Binder.restoreCallingIdentity(ident);
2491 }
2492 }
2493
2494 @Override
2495 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002497 long ident = Binder.clearCallingIdentity();
2498 try {
2499 synchronized (mGlobalLock) {
2500 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2501 }
2502 } finally {
2503 Binder.restoreCallingIdentity(ident);
2504 }
2505 }
2506
2507 @Override
2508 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002509 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 final long callingUid = Binder.getCallingUid();
2511 final long origId = Binder.clearCallingIdentity();
2512 try {
2513 synchronized (mGlobalLock) {
2514 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002515 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002516 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2517 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2518 }
2519 } finally {
2520 Binder.restoreCallingIdentity(origId);
2521 }
2522 }
2523
2524 @Override
2525 public void startLockTaskModeByToken(IBinder token) {
2526 synchronized (mGlobalLock) {
2527 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2528 if (r == null) {
2529 return;
2530 }
2531 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2532 }
2533 }
2534
2535 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002536 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002537 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 // This makes inner call to look as if it was initiated by system.
2539 long ident = Binder.clearCallingIdentity();
2540 try {
2541 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002542 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2543 MATCH_TASK_IN_STACKS_ONLY);
2544 if (task == null) {
2545 return;
2546 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002547
2548 // When starting lock task mode the stack must be in front and focused
2549 task.getStack().moveToFront("startSystemLockTaskMode");
2550 startLockTaskModeLocked(task, true /* isSystemCaller */);
2551 }
2552 } finally {
2553 Binder.restoreCallingIdentity(ident);
2554 }
2555 }
2556
2557 @Override
2558 public void stopLockTaskModeByToken(IBinder token) {
2559 synchronized (mGlobalLock) {
2560 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2561 if (r == null) {
2562 return;
2563 }
2564 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2565 }
2566 }
2567
2568 /**
2569 * This API should be called by SystemUI only when user perform certain action to dismiss
2570 * lock task mode. We should only dismiss pinned lock task mode in this case.
2571 */
2572 @Override
2573 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2576 }
2577
2578 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2579 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2580 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2581 return;
2582 }
2583
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002584 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002585 if (stack == null || task != stack.topTask()) {
2586 throw new IllegalArgumentException("Invalid task, not in foreground");
2587 }
2588
2589 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2590 // system or a specific app.
2591 // * System-initiated requests will only start the pinned mode (screen pinning)
2592 // * App-initiated requests
2593 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2594 // - will start the pinned mode, otherwise
2595 final int callingUid = Binder.getCallingUid();
2596 long ident = Binder.clearCallingIdentity();
2597 try {
2598 // When a task is locked, dismiss the pinned stack if it exists
2599 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2600
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002601 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002602 } finally {
2603 Binder.restoreCallingIdentity(ident);
2604 }
2605 }
2606
2607 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2608 final int callingUid = Binder.getCallingUid();
2609 long ident = Binder.clearCallingIdentity();
2610 try {
2611 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002612 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002613 }
2614 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2615 // task and jumping straight into a call in the case of emergency call back.
2616 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2617 if (tm != null) {
2618 tm.showInCallScreen(false);
2619 }
2620 } finally {
2621 Binder.restoreCallingIdentity(ident);
2622 }
2623 }
2624
2625 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002626 public void updateLockTaskPackages(int userId, String[] packages) {
2627 final int callingUid = Binder.getCallingUid();
2628 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2629 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2630 "updateLockTaskPackages()");
2631 }
2632 synchronized (this) {
2633 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2634 + Arrays.toString(packages));
2635 getLockTaskController().updateLockTaskPackages(userId, packages);
2636 }
2637 }
2638
2639 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002640 public boolean isInLockTaskMode() {
2641 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2642 }
2643
2644 @Override
2645 public int getLockTaskModeState() {
2646 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002647 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002648 }
2649 }
2650
2651 @Override
2652 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2653 synchronized (mGlobalLock) {
2654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2655 if (r != null) {
2656 r.setTaskDescription(td);
2657 final TaskRecord task = r.getTask();
2658 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002659 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660 }
2661 }
2662 }
2663
2664 @Override
2665 public Bundle getActivityOptions(IBinder token) {
2666 final long origId = Binder.clearCallingIdentity();
2667 try {
2668 synchronized (mGlobalLock) {
2669 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2670 if (r != null) {
2671 final ActivityOptions activityOptions = r.takeOptionsLocked();
2672 return activityOptions == null ? null : activityOptions.toBundle();
2673 }
2674 return null;
2675 }
2676 } finally {
2677 Binder.restoreCallingIdentity(origId);
2678 }
2679 }
2680
2681 @Override
2682 public List<IBinder> getAppTasks(String callingPackage) {
2683 int callingUid = Binder.getCallingUid();
2684 long ident = Binder.clearCallingIdentity();
2685 try {
2686 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002687 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002688 }
2689 } finally {
2690 Binder.restoreCallingIdentity(ident);
2691 }
2692 }
2693
2694 @Override
2695 public void finishVoiceTask(IVoiceInteractionSession session) {
2696 synchronized (mGlobalLock) {
2697 final long origId = Binder.clearCallingIdentity();
2698 try {
2699 // TODO: VI Consider treating local voice interactions and voice tasks
2700 // differently here
2701 mStackSupervisor.finishVoiceTask(session);
2702 } finally {
2703 Binder.restoreCallingIdentity(origId);
2704 }
2705 }
2706
2707 }
2708
2709 @Override
2710 public boolean isTopOfTask(IBinder token) {
2711 synchronized (mGlobalLock) {
2712 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002713 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002714 }
2715 }
2716
2717 @Override
2718 public void notifyLaunchTaskBehindComplete(IBinder token) {
2719 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2720 }
2721
2722 @Override
2723 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002724 mH.post(() -> {
2725 synchronized (mGlobalLock) {
2726 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002727 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002728 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002729 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002730 } catch (RemoteException e) {
2731 }
2732 }
2733 }
2734
2735 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 }
2737
2738 /** Called from an app when assist data is ready. */
2739 @Override
2740 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2741 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002742 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 synchronized (pae) {
2744 pae.result = extras;
2745 pae.structure = structure;
2746 pae.content = content;
2747 if (referrer != null) {
2748 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2749 }
2750 if (structure != null) {
2751 structure.setHomeActivity(pae.isHome);
2752 }
2753 pae.haveResult = true;
2754 pae.notifyAll();
2755 if (pae.intent == null && pae.receiver == null) {
2756 // Caller is just waiting for the result.
2757 return;
2758 }
2759 }
2760 // We are now ready to launch the assist activity.
2761 IAssistDataReceiver sendReceiver = null;
2762 Bundle sendBundle = null;
2763 synchronized (mGlobalLock) {
2764 buildAssistBundleLocked(pae, extras);
2765 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002766 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 if (!exists) {
2768 // Timed out.
2769 return;
2770 }
2771
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 // Caller wants result sent back to them.
2774 sendBundle = new Bundle();
2775 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2776 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2777 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2778 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2779 }
2780 }
2781 if (sendReceiver != null) {
2782 try {
2783 sendReceiver.onHandleAssistData(sendBundle);
2784 } catch (RemoteException e) {
2785 }
2786 return;
2787 }
2788
2789 final long ident = Binder.clearCallingIdentity();
2790 try {
2791 if (TextUtils.equals(pae.intent.getAction(),
2792 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2793 pae.intent.putExtras(pae.extras);
2794 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2795 } else {
2796 pae.intent.replaceExtras(pae.extras);
2797 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2798 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2799 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002800 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801
2802 try {
2803 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2804 } catch (ActivityNotFoundException e) {
2805 Slog.w(TAG, "No activity to handle assist action.", e);
2806 }
2807 }
2808 } finally {
2809 Binder.restoreCallingIdentity(ident);
2810 }
2811 }
2812
2813 @Override
2814 public int addAppTask(IBinder activityToken, Intent intent,
2815 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2816 final int callingUid = Binder.getCallingUid();
2817 final long callingIdent = Binder.clearCallingIdentity();
2818
2819 try {
2820 synchronized (mGlobalLock) {
2821 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2822 if (r == null) {
2823 throw new IllegalArgumentException("Activity does not exist; token="
2824 + activityToken);
2825 }
2826 ComponentName comp = intent.getComponent();
2827 if (comp == null) {
2828 throw new IllegalArgumentException("Intent " + intent
2829 + " must specify explicit component");
2830 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002831 if (thumbnail.getWidth() != mThumbnailWidth
2832 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 throw new IllegalArgumentException("Bad thumbnail size: got "
2834 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002835 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 }
2837 if (intent.getSelector() != null) {
2838 intent.setSelector(null);
2839 }
2840 if (intent.getSourceBounds() != null) {
2841 intent.setSourceBounds(null);
2842 }
2843 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2844 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2845 // The caller has added this as an auto-remove task... that makes no
2846 // sense, so turn off auto-remove.
2847 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2848 }
2849 }
2850 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2851 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2852 if (ainfo.applicationInfo.uid != callingUid) {
2853 throw new SecurityException(
2854 "Can't add task for another application: target uid="
2855 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2856 }
2857
2858 final ActivityStack stack = r.getStack();
2859 final TaskRecord task = stack.createTaskRecord(
2860 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2861 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002862 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863 // The app has too many tasks already and we can't add any more
2864 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2865 return INVALID_TASK_ID;
2866 }
2867 task.lastTaskDescription.copyFrom(description);
2868
2869 // TODO: Send the thumbnail to WM to store it.
2870
2871 return task.taskId;
2872 }
2873 } finally {
2874 Binder.restoreCallingIdentity(callingIdent);
2875 }
2876 }
2877
2878 @Override
2879 public Point getAppTaskThumbnailSize() {
2880 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002881 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 }
2883 }
2884
2885 @Override
2886 public void setTaskResizeable(int taskId, int resizeableMode) {
2887 synchronized (mGlobalLock) {
2888 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2889 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2890 if (task == null) {
2891 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2892 return;
2893 }
2894 task.setResizeMode(resizeableMode);
2895 }
2896 }
2897
2898 @Override
2899 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002900 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 long ident = Binder.clearCallingIdentity();
2902 try {
2903 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002904 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2905 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002906 if (task == null) {
2907 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2908 return;
2909 }
2910 // Place the task in the right stack if it isn't there already based on
2911 // the requested bounds.
2912 // The stack transition logic is:
2913 // - a null bounds on a freeform task moves that task to fullscreen
2914 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2915 // that task to freeform
2916 // - otherwise the task is not moved
2917 ActivityStack stack = task.getStack();
2918 if (!task.getWindowConfiguration().canResizeTask()) {
2919 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2920 }
2921 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2922 stack = stack.getDisplay().getOrCreateStack(
2923 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2924 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2925 stack = stack.getDisplay().getOrCreateStack(
2926 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2927 }
2928
2929 // Reparent the task to the right stack if necessary
2930 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2931 if (stack != task.getStack()) {
2932 // Defer resume until the task is resized below
2933 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2934 DEFER_RESUME, "resizeTask");
2935 preserveWindow = false;
2936 }
2937
2938 // After reparenting (which only resizes the task to the stack bounds), resize the
2939 // task to the actual bounds provided
2940 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2941 }
2942 } finally {
2943 Binder.restoreCallingIdentity(ident);
2944 }
2945 }
2946
2947 @Override
2948 public boolean releaseActivityInstance(IBinder token) {
2949 synchronized (mGlobalLock) {
2950 final long origId = Binder.clearCallingIdentity();
2951 try {
2952 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2953 if (r == null) {
2954 return false;
2955 }
2956 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2957 } finally {
2958 Binder.restoreCallingIdentity(origId);
2959 }
2960 }
2961 }
2962
2963 @Override
2964 public void releaseSomeActivities(IApplicationThread appInt) {
2965 synchronized (mGlobalLock) {
2966 final long origId = Binder.clearCallingIdentity();
2967 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002968 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2970 } finally {
2971 Binder.restoreCallingIdentity(origId);
2972 }
2973 }
2974 }
2975
2976 @Override
2977 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002978 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002979 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 != PackageManager.PERMISSION_GRANTED) {
2981 throw new SecurityException("Requires permission "
2982 + android.Manifest.permission.DEVICE_POWER);
2983 }
2984
2985 synchronized (mGlobalLock) {
2986 long ident = Binder.clearCallingIdentity();
2987 if (mKeyguardShown != keyguardShowing) {
2988 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002989 final Message msg = PooledLambda.obtainMessage(
2990 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
2991 keyguardShowing);
2992 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 }
2994 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002995 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002996 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 } finally {
2998 Binder.restoreCallingIdentity(ident);
2999 }
3000 }
3001
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003002 mH.post(() -> {
3003 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3004 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3005 }
3006 });
3007 }
3008
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003009 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 mH.post(() -> {
3011 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3012 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3013 }
3014 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003015 }
3016
3017 @Override
3018 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003019 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3020 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021
3022 final File passedIconFile = new File(filePath);
3023 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3024 passedIconFile.getName());
3025 if (!legitIconFile.getPath().equals(filePath)
3026 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3027 throw new IllegalArgumentException("Bad file path: " + filePath
3028 + " passed for userId " + userId);
3029 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003030 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 }
3032
3033 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003034 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3036 final ActivityOptions activityOptions = safeOptions != null
3037 ? safeOptions.getOptions(mStackSupervisor)
3038 : null;
3039 if (activityOptions == null
3040 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3041 || activityOptions.getCustomInPlaceResId() == 0) {
3042 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3043 "with valid animation");
3044 }
lumark588a3e82018-07-20 18:53:54 +08003045 // Get top display of front most application.
3046 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3047 if (focusedStack != null) {
3048 final DisplayWindowController dwc =
3049 focusedStack.getDisplay().getWindowContainerController();
3050 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3051 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3052 activityOptions.getCustomInPlaceResId());
3053 dwc.executeAppTransition();
3054 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003055 }
3056
3057 @Override
3058 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003059 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 synchronized (mGlobalLock) {
3061 final long ident = Binder.clearCallingIdentity();
3062 try {
3063 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3064 if (stack == null) {
3065 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3066 return;
3067 }
3068 if (!stack.isActivityTypeStandardOrUndefined()) {
3069 throw new IllegalArgumentException(
3070 "Removing non-standard stack is not allowed.");
3071 }
3072 mStackSupervisor.removeStack(stack);
3073 } finally {
3074 Binder.restoreCallingIdentity(ident);
3075 }
3076 }
3077 }
3078
3079 @Override
3080 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003081 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003082
3083 synchronized (mGlobalLock) {
3084 final long ident = Binder.clearCallingIdentity();
3085 try {
3086 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3087 + " to displayId=" + displayId);
3088 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
3089 } finally {
3090 Binder.restoreCallingIdentity(ident);
3091 }
3092 }
3093 }
3094
3095 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 public void exitFreeformMode(IBinder token) {
3097 synchronized (mGlobalLock) {
3098 long ident = Binder.clearCallingIdentity();
3099 try {
3100 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3101 if (r == null) {
3102 throw new IllegalArgumentException(
3103 "exitFreeformMode: No activity record matching token=" + token);
3104 }
3105
3106 final ActivityStack stack = r.getStack();
3107 if (stack == null || !stack.inFreeformWindowingMode()) {
3108 throw new IllegalStateException(
3109 "exitFreeformMode: You can only go fullscreen from freeform.");
3110 }
3111
3112 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3113 } finally {
3114 Binder.restoreCallingIdentity(ident);
3115 }
3116 }
3117 }
3118
3119 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3120 @Override
3121 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003124 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 }
3126
3127 /** Unregister a task stack listener so that it stops receiving callbacks. */
3128 @Override
3129 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003130 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003132 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 }
3134
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 @Override
3136 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3137 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3138 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3139 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3140 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3141 }
3142
3143 @Override
3144 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3145 IBinder activityToken, int flags) {
3146 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3147 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3148 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3149 }
3150
3151 @Override
3152 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3153 Bundle args) {
3154 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3155 true /* focused */, true /* newSessionId */, userHandle, args,
3156 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3157 }
3158
3159 @Override
3160 public Bundle getAssistContextExtras(int requestType) {
3161 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3162 null, null, true /* focused */, true /* newSessionId */,
3163 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3164 if (pae == null) {
3165 return null;
3166 }
3167 synchronized (pae) {
3168 while (!pae.haveResult) {
3169 try {
3170 pae.wait();
3171 } catch (InterruptedException e) {
3172 }
3173 }
3174 }
3175 synchronized (mGlobalLock) {
3176 buildAssistBundleLocked(pae, pae.result);
3177 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003178 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 }
3180 return pae.extras;
3181 }
3182
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003183 /**
3184 * Binder IPC calls go through the public entry point.
3185 * This can be called with or without the global lock held.
3186 */
3187 private static int checkCallingPermission(String permission) {
3188 return checkPermission(
3189 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3190 }
3191
3192 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003193 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003194 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3195 mAmInternal.enforceCallingPermission(permission, func);
3196 }
3197 }
3198
3199 @VisibleForTesting
3200 int checkGetTasksPermission(String permission, int pid, int uid) {
3201 return checkPermission(permission, pid, uid);
3202 }
3203
3204 static int checkPermission(String permission, int pid, int uid) {
3205 if (permission == null) {
3206 return PackageManager.PERMISSION_DENIED;
3207 }
3208 return checkComponentPermission(permission, pid, uid, -1, true);
3209 }
3210
Wale Ogunwale214f3482018-10-04 11:00:47 -07003211 public static int checkComponentPermission(String permission, int pid, int uid,
3212 int owningUid, boolean exported) {
3213 return ActivityManagerService.checkComponentPermission(
3214 permission, pid, uid, owningUid, exported);
3215 }
3216
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3218 if (getRecentTasks().isCallerRecents(callingUid)) {
3219 // Always allow the recents component to get tasks
3220 return true;
3221 }
3222
3223 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3224 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3225 if (!allowed) {
3226 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3227 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3228 // Temporary compatibility: some existing apps on the system image may
3229 // still be requesting the old permission and not switched to the new
3230 // one; if so, we'll still allow them full access. This means we need
3231 // to see if they are holding the old permission and are a system app.
3232 try {
3233 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3234 allowed = true;
3235 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3236 + " is using old GET_TASKS but privileged; allowing");
3237 }
3238 } catch (RemoteException e) {
3239 }
3240 }
3241 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3242 + " does not hold REAL_GET_TASKS; limiting output");
3243 }
3244 return allowed;
3245 }
3246
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3248 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3249 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3250 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003251 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003252 "enqueueAssistContext()");
3253
3254 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003255 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 if (activity == null) {
3257 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3258 return null;
3259 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003260 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3262 return null;
3263 }
3264 if (focused) {
3265 if (activityToken != null) {
3266 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3267 if (activity != caller) {
3268 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3269 + " is not current top " + activity);
3270 return null;
3271 }
3272 }
3273 } else {
3274 activity = ActivityRecord.forTokenLocked(activityToken);
3275 if (activity == null) {
3276 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3277 + " couldn't be found");
3278 return null;
3279 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003280 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3282 return null;
3283 }
3284 }
3285
3286 PendingAssistExtras pae;
3287 Bundle extras = new Bundle();
3288 if (args != null) {
3289 extras.putAll(args);
3290 }
3291 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003292 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293
3294 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3295 userHandle);
3296 pae.isHome = activity.isActivityTypeHome();
3297
3298 // Increment the sessionId if necessary
3299 if (newSessionId) {
3300 mViSessionId++;
3301 }
3302 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003303 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3304 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003306 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003307 } catch (RemoteException e) {
3308 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3309 return null;
3310 }
3311 return pae;
3312 }
3313 }
3314
3315 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3316 if (result != null) {
3317 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3318 }
3319 if (pae.hint != null) {
3320 pae.extras.putBoolean(pae.hint, true);
3321 }
3322 }
3323
3324 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3325 IAssistDataReceiver receiver;
3326 synchronized (mGlobalLock) {
3327 mPendingAssistExtras.remove(pae);
3328 receiver = pae.receiver;
3329 }
3330 if (receiver != null) {
3331 // Caller wants result sent back to them.
3332 Bundle sendBundle = new Bundle();
3333 // At least return the receiver extras
3334 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3335 try {
3336 pae.receiver.onHandleAssistData(sendBundle);
3337 } catch (RemoteException e) {
3338 }
3339 }
3340 }
3341
3342 public class PendingAssistExtras extends Binder implements Runnable {
3343 public final ActivityRecord activity;
3344 public boolean isHome;
3345 public final Bundle extras;
3346 public final Intent intent;
3347 public final String hint;
3348 public final IAssistDataReceiver receiver;
3349 public final int userHandle;
3350 public boolean haveResult = false;
3351 public Bundle result = null;
3352 public AssistStructure structure = null;
3353 public AssistContent content = null;
3354 public Bundle receiverExtras;
3355
3356 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3357 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3358 int _userHandle) {
3359 activity = _activity;
3360 extras = _extras;
3361 intent = _intent;
3362 hint = _hint;
3363 receiver = _receiver;
3364 receiverExtras = _receiverExtras;
3365 userHandle = _userHandle;
3366 }
3367
3368 @Override
3369 public void run() {
3370 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3371 synchronized (this) {
3372 haveResult = true;
3373 notifyAll();
3374 }
3375 pendingAssistExtrasTimedOut(this);
3376 }
3377 }
3378
3379 @Override
3380 public boolean isAssistDataAllowedOnCurrentActivity() {
3381 int userId;
3382 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003383 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3385 return false;
3386 }
3387
3388 final ActivityRecord activity = focusedStack.getTopActivity();
3389 if (activity == null) {
3390 return false;
3391 }
3392 userId = activity.userId;
3393 }
3394 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3395 }
3396
3397 @Override
3398 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3399 long ident = Binder.clearCallingIdentity();
3400 try {
3401 synchronized (mGlobalLock) {
3402 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003403 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 if (top != caller) {
3405 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3406 + " is not current top " + top);
3407 return false;
3408 }
3409 if (!top.nowVisible) {
3410 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3411 + " is not visible");
3412 return false;
3413 }
3414 }
3415 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3416 token);
3417 } finally {
3418 Binder.restoreCallingIdentity(ident);
3419 }
3420 }
3421
3422 @Override
3423 public boolean isRootVoiceInteraction(IBinder token) {
3424 synchronized (mGlobalLock) {
3425 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3426 if (r == null) {
3427 return false;
3428 }
3429 return r.rootVoiceInteraction;
3430 }
3431 }
3432
Wale Ogunwalef6733932018-06-27 05:14:34 -07003433 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3434 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3435 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3436 if (activityToCallback == null) return;
3437 activityToCallback.setVoiceSessionLocked(voiceSession);
3438
3439 // Inform the activity
3440 try {
3441 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3442 voiceInteractor);
3443 long token = Binder.clearCallingIdentity();
3444 try {
3445 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3446 } finally {
3447 Binder.restoreCallingIdentity(token);
3448 }
3449 // TODO: VI Should we cache the activity so that it's easier to find later
3450 // rather than scan through all the stacks and activities?
3451 } catch (RemoteException re) {
3452 activityToCallback.clearVoiceSessionLocked();
3453 // TODO: VI Should this terminate the voice session?
3454 }
3455 }
3456
3457 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3458 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3459 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3460 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3461 boolean wasRunningVoice = mRunningVoice != null;
3462 mRunningVoice = session;
3463 if (!wasRunningVoice) {
3464 mVoiceWakeLock.acquire();
3465 updateSleepIfNeededLocked();
3466 }
3467 }
3468 }
3469
3470 void finishRunningVoiceLocked() {
3471 if (mRunningVoice != null) {
3472 mRunningVoice = null;
3473 mVoiceWakeLock.release();
3474 updateSleepIfNeededLocked();
3475 }
3476 }
3477
3478 @Override
3479 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3480 synchronized (mGlobalLock) {
3481 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3482 if (keepAwake) {
3483 mVoiceWakeLock.acquire();
3484 } else {
3485 mVoiceWakeLock.release();
3486 }
3487 }
3488 }
3489 }
3490
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003491 @Override
3492 public ComponentName getActivityClassForToken(IBinder token) {
3493 synchronized (mGlobalLock) {
3494 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3495 if (r == null) {
3496 return null;
3497 }
3498 return r.intent.getComponent();
3499 }
3500 }
3501
3502 @Override
3503 public String getPackageForToken(IBinder token) {
3504 synchronized (mGlobalLock) {
3505 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3506 if (r == null) {
3507 return null;
3508 }
3509 return r.packageName;
3510 }
3511 }
3512
3513 @Override
3514 public void showLockTaskEscapeMessage(IBinder token) {
3515 synchronized (mGlobalLock) {
3516 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3517 if (r == null) {
3518 return;
3519 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003520 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 }
3522 }
3523
3524 @Override
3525 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003526 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 final long token = Binder.clearCallingIdentity();
3528 try {
3529 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003530 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003531 }
3532 } finally {
3533 Binder.restoreCallingIdentity(token);
3534 }
3535 }
3536
3537 /**
3538 * Try to place task to provided position. The final position might be different depending on
3539 * current user and stacks state. The task will be moved to target stack if it's currently in
3540 * different stack.
3541 */
3542 @Override
3543 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003544 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545 synchronized (mGlobalLock) {
3546 long ident = Binder.clearCallingIdentity();
3547 try {
3548 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3549 + taskId + " in stackId=" + stackId + " at position=" + position);
3550 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3551 if (task == null) {
3552 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3553 + taskId);
3554 }
3555
3556 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3557
3558 if (stack == null) {
3559 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3560 + stackId);
3561 }
3562 if (!stack.isActivityTypeStandardOrUndefined()) {
3563 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3564 + " the position of task " + taskId + " in/to non-standard stack");
3565 }
3566
3567 // TODO: Have the callers of this API call a separate reparent method if that is
3568 // what they intended to do vs. having this method also do reparenting.
3569 if (task.getStack() == stack) {
3570 // Change position in current stack.
3571 stack.positionChildAt(task, position);
3572 } else {
3573 // Reparent to new stack.
3574 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3575 !DEFER_RESUME, "positionTaskInStack");
3576 }
3577 } finally {
3578 Binder.restoreCallingIdentity(ident);
3579 }
3580 }
3581 }
3582
3583 @Override
3584 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3585 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3586 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3587 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3588 synchronized (mGlobalLock) {
3589 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3590 if (record == null) {
3591 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3592 + "found for: " + token);
3593 }
3594 record.setSizeConfigurations(horizontalSizeConfiguration,
3595 verticalSizeConfigurations, smallestSizeConfigurations);
3596 }
3597 }
3598
3599 /**
3600 * Dismisses split-screen multi-window mode.
3601 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3602 */
3603 @Override
3604 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003605 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3607 final long ident = Binder.clearCallingIdentity();
3608 try {
3609 synchronized (mGlobalLock) {
3610 final ActivityStack stack =
3611 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3612 if (stack == null) {
3613 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3614 return;
3615 }
3616
3617 if (toTop) {
3618 // Caller wants the current split-screen primary stack to be the top stack after
3619 // it goes fullscreen, so move it to the front.
3620 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003621 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 // In this case the current split-screen primary stack shouldn't be the top
3623 // stack after it goes fullscreen, but it current has focus, so we move the
3624 // focus to the top-most split-screen secondary stack next to it.
3625 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3626 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3627 if (otherStack != null) {
3628 otherStack.moveToFront("dismissSplitScreenMode_other");
3629 }
3630 }
3631
Evan Rosky10475742018-09-05 19:02:48 -07003632 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 }
3634 } finally {
3635 Binder.restoreCallingIdentity(ident);
3636 }
3637 }
3638
3639 /**
3640 * Dismisses Pip
3641 * @param animate True if the dismissal should be animated.
3642 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3643 * default animation duration should be used.
3644 */
3645 @Override
3646 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003647 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 final long ident = Binder.clearCallingIdentity();
3649 try {
3650 synchronized (mGlobalLock) {
3651 final PinnedActivityStack stack =
3652 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3653 if (stack == null) {
3654 Slog.w(TAG, "dismissPip: pinned stack not found.");
3655 return;
3656 }
3657 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3658 throw new IllegalArgumentException("Stack: " + stack
3659 + " doesn't support animated resize.");
3660 }
3661 if (animate) {
3662 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3663 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3664 } else {
3665 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3666 }
3667 }
3668 } finally {
3669 Binder.restoreCallingIdentity(ident);
3670 }
3671 }
3672
3673 @Override
3674 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003675 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003676 synchronized (mGlobalLock) {
3677 mSuppressResizeConfigChanges = suppress;
3678 }
3679 }
3680
3681 /**
3682 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3683 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3684 * activity and clearing the task at the same time.
3685 */
3686 @Override
3687 // TODO: API should just be about changing windowing modes...
3688 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003689 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003690 "moveTasksToFullscreenStack()");
3691 synchronized (mGlobalLock) {
3692 final long origId = Binder.clearCallingIdentity();
3693 try {
3694 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3695 if (stack != null){
3696 if (!stack.isActivityTypeStandardOrUndefined()) {
3697 throw new IllegalArgumentException(
3698 "You can't move tasks from non-standard stacks.");
3699 }
3700 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3701 }
3702 } finally {
3703 Binder.restoreCallingIdentity(origId);
3704 }
3705 }
3706 }
3707
3708 /**
3709 * Moves the top activity in the input stackId to the pinned stack.
3710 *
3711 * @param stackId Id of stack to move the top activity to pinned stack.
3712 * @param bounds Bounds to use for pinned stack.
3713 *
3714 * @return True if the top activity of the input stack was successfully moved to the pinned
3715 * stack.
3716 */
3717 @Override
3718 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003719 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003720 "moveTopActivityToPinnedStack()");
3721 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003722 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003723 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3724 + "Device doesn't support picture-in-picture mode");
3725 }
3726
3727 long ident = Binder.clearCallingIdentity();
3728 try {
3729 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3730 } finally {
3731 Binder.restoreCallingIdentity(ident);
3732 }
3733 }
3734 }
3735
3736 @Override
3737 public boolean isInMultiWindowMode(IBinder token) {
3738 final long origId = Binder.clearCallingIdentity();
3739 try {
3740 synchronized (mGlobalLock) {
3741 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3742 if (r == null) {
3743 return false;
3744 }
3745 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3746 return r.inMultiWindowMode();
3747 }
3748 } finally {
3749 Binder.restoreCallingIdentity(origId);
3750 }
3751 }
3752
3753 @Override
3754 public boolean isInPictureInPictureMode(IBinder token) {
3755 final long origId = Binder.clearCallingIdentity();
3756 try {
3757 synchronized (mGlobalLock) {
3758 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3759 }
3760 } finally {
3761 Binder.restoreCallingIdentity(origId);
3762 }
3763 }
3764
3765 private boolean isInPictureInPictureMode(ActivityRecord r) {
3766 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3767 || r.getStack().isInStackLocked(r) == null) {
3768 return false;
3769 }
3770
3771 // If we are animating to fullscreen then we have already dispatched the PIP mode
3772 // changed, so we should reflect that check here as well.
3773 final PinnedActivityStack stack = r.getStack();
3774 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3775 return !windowController.isAnimatingBoundsToFullscreen();
3776 }
3777
3778 @Override
3779 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3780 final long origId = Binder.clearCallingIdentity();
3781 try {
3782 synchronized (mGlobalLock) {
3783 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3784 "enterPictureInPictureMode", token, params);
3785
3786 // If the activity is already in picture in picture mode, then just return early
3787 if (isInPictureInPictureMode(r)) {
3788 return true;
3789 }
3790
3791 // Activity supports picture-in-picture, now check that we can enter PiP at this
3792 // point, if it is
3793 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3794 false /* beforeStopping */)) {
3795 return false;
3796 }
3797
3798 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003799 synchronized (mGlobalLock) {
3800 // Only update the saved args from the args that are set
3801 r.pictureInPictureArgs.copyOnlySet(params);
3802 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3803 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3804 // Adjust the source bounds by the insets for the transition down
3805 final Rect sourceBounds = new Rect(
3806 r.pictureInPictureArgs.getSourceRectHint());
3807 mStackSupervisor.moveActivityToPinnedStackLocked(
3808 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3809 final PinnedActivityStack stack = r.getStack();
3810 stack.setPictureInPictureAspectRatio(aspectRatio);
3811 stack.setPictureInPictureActions(actions);
3812 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3813 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3814 logPictureInPictureArgs(params);
3815 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 };
3817
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003818 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003819 // If the keyguard is showing or occluded, then try and dismiss it before
3820 // entering picture-in-picture (this will prompt the user to authenticate if the
3821 // device is currently locked).
3822 dismissKeyguard(token, new KeyguardDismissCallback() {
3823 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003824 public void onDismissSucceeded() {
3825 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003826 }
3827 }, null /* message */);
3828 } else {
3829 // Enter picture in picture immediately otherwise
3830 enterPipRunnable.run();
3831 }
3832 return true;
3833 }
3834 } finally {
3835 Binder.restoreCallingIdentity(origId);
3836 }
3837 }
3838
3839 @Override
3840 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3841 final long origId = Binder.clearCallingIdentity();
3842 try {
3843 synchronized (mGlobalLock) {
3844 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3845 "setPictureInPictureParams", token, params);
3846
3847 // Only update the saved args from the args that are set
3848 r.pictureInPictureArgs.copyOnlySet(params);
3849 if (r.inPinnedWindowingMode()) {
3850 // If the activity is already in picture-in-picture, update the pinned stack now
3851 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3852 // be used the next time the activity enters PiP
3853 final PinnedActivityStack stack = r.getStack();
3854 if (!stack.isAnimatingBoundsToFullscreen()) {
3855 stack.setPictureInPictureAspectRatio(
3856 r.pictureInPictureArgs.getAspectRatio());
3857 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3858 }
3859 }
3860 logPictureInPictureArgs(params);
3861 }
3862 } finally {
3863 Binder.restoreCallingIdentity(origId);
3864 }
3865 }
3866
3867 @Override
3868 public int getMaxNumPictureInPictureActions(IBinder token) {
3869 // Currently, this is a static constant, but later, we may change this to be dependent on
3870 // the context of the activity
3871 return 3;
3872 }
3873
3874 private void logPictureInPictureArgs(PictureInPictureParams params) {
3875 if (params.hasSetActions()) {
3876 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3877 params.getActions().size());
3878 }
3879 if (params.hasSetAspectRatio()) {
3880 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3881 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3882 MetricsLogger.action(lm);
3883 }
3884 }
3885
3886 /**
3887 * Checks the state of the system and the activity associated with the given {@param token} to
3888 * verify that picture-in-picture is supported for that activity.
3889 *
3890 * @return the activity record for the given {@param token} if all the checks pass.
3891 */
3892 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3893 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003894 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895 throw new IllegalStateException(caller
3896 + ": Device doesn't support picture-in-picture mode.");
3897 }
3898
3899 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3900 if (r == null) {
3901 throw new IllegalStateException(caller
3902 + ": Can't find activity for token=" + token);
3903 }
3904
3905 if (!r.supportsPictureInPicture()) {
3906 throw new IllegalStateException(caller
3907 + ": Current activity does not support picture-in-picture.");
3908 }
3909
3910 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003911 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 params.getAspectRatio())) {
3913 final float minAspectRatio = mContext.getResources().getFloat(
3914 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3915 final float maxAspectRatio = mContext.getResources().getFloat(
3916 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3917 throw new IllegalArgumentException(String.format(caller
3918 + ": Aspect ratio is too extreme (must be between %f and %f).",
3919 minAspectRatio, maxAspectRatio));
3920 }
3921
3922 // Truncate the number of actions if necessary
3923 params.truncateActions(getMaxNumPictureInPictureActions(token));
3924
3925 return r;
3926 }
3927
3928 @Override
3929 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003930 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 synchronized (mGlobalLock) {
3932 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3933 if (r == null) {
3934 throw new IllegalArgumentException("Activity does not exist; token="
3935 + activityToken);
3936 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003937 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 }
3939 }
3940
3941 @Override
3942 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3943 Rect tempDockedTaskInsetBounds,
3944 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003945 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 long ident = Binder.clearCallingIdentity();
3947 try {
3948 synchronized (mGlobalLock) {
3949 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3950 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3951 PRESERVE_WINDOWS);
3952 }
3953 } finally {
3954 Binder.restoreCallingIdentity(ident);
3955 }
3956 }
3957
3958 @Override
3959 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003960 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 final long ident = Binder.clearCallingIdentity();
3962 try {
3963 synchronized (mGlobalLock) {
3964 mStackSupervisor.setSplitScreenResizing(resizing);
3965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(ident);
3968 }
3969 }
3970
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003971 /**
3972 * Check that we have the features required for VR-related API calls, and throw an exception if
3973 * not.
3974 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003975 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003976 if (!mContext.getPackageManager().hasSystemFeature(
3977 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3978 throw new UnsupportedOperationException("VR mode not supported on this device!");
3979 }
3980 }
3981
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982 @Override
3983 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003984 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985
3986 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3987
3988 ActivityRecord r;
3989 synchronized (mGlobalLock) {
3990 r = ActivityRecord.isInStackLocked(token);
3991 }
3992
3993 if (r == null) {
3994 throw new IllegalArgumentException();
3995 }
3996
3997 int err;
3998 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3999 VrManagerInternal.NO_ERROR) {
4000 return err;
4001 }
4002
4003 // Clear the binder calling uid since this path may call moveToTask().
4004 final long callingId = Binder.clearCallingIdentity();
4005 try {
4006 synchronized (mGlobalLock) {
4007 r.requestedVrComponent = (enabled) ? packageName : null;
4008
4009 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004010 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004011 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 }
4013 return 0;
4014 }
4015 } finally {
4016 Binder.restoreCallingIdentity(callingId);
4017 }
4018 }
4019
4020 @Override
4021 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4022 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4023 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004024 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4026 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4027 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004028 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 || activity.voiceSession != null) {
4030 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4031 return;
4032 }
4033 if (activity.pendingVoiceInteractionStart) {
4034 Slog.w(TAG, "Pending start of voice interaction already.");
4035 return;
4036 }
4037 activity.pendingVoiceInteractionStart = true;
4038 }
4039 LocalServices.getService(VoiceInteractionManagerInternal.class)
4040 .startLocalVoiceInteraction(callingActivity, options);
4041 }
4042
4043 @Override
4044 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4045 LocalServices.getService(VoiceInteractionManagerInternal.class)
4046 .stopLocalVoiceInteraction(callingActivity);
4047 }
4048
4049 @Override
4050 public boolean supportsLocalVoiceInteraction() {
4051 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4052 .supportsLocalVoiceInteraction();
4053 }
4054
4055 /** Notifies all listeners when the pinned stack animation starts. */
4056 @Override
4057 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004058 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 }
4060
4061 /** Notifies all listeners when the pinned stack animation ends. */
4062 @Override
4063 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004064 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 }
4066
4067 @Override
4068 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004069 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004070 final long ident = Binder.clearCallingIdentity();
4071 try {
4072 synchronized (mGlobalLock) {
4073 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4074 }
4075 } finally {
4076 Binder.restoreCallingIdentity(ident);
4077 }
4078 }
4079
4080 @Override
4081 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004082 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083
4084 synchronized (mGlobalLock) {
4085 // Check if display is initialized in AM.
4086 if (!mStackSupervisor.isDisplayAdded(displayId)) {
4087 // Call might come when display is not yet added or has already been removed.
4088 if (DEBUG_CONFIGURATION) {
4089 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4090 + displayId);
4091 }
4092 return false;
4093 }
4094
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004095 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004096 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004097 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004098 }
4099
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004100 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004101 final Message msg = PooledLambda.obtainMessage(
4102 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4103 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004104 }
4105
4106 final long origId = Binder.clearCallingIdentity();
4107 try {
4108 if (values != null) {
4109 Settings.System.clearConfiguration(values);
4110 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004111 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004112 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4113 return mTmpUpdateConfigurationResult.changes != 0;
4114 } finally {
4115 Binder.restoreCallingIdentity(origId);
4116 }
4117 }
4118 }
4119
4120 @Override
4121 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004122 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123
4124 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004125 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004127 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004128 }
4129
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004130 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004131 final Message msg = PooledLambda.obtainMessage(
4132 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4133 DEFAULT_DISPLAY);
4134 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004135 }
4136
4137 final long origId = Binder.clearCallingIdentity();
4138 try {
4139 if (values != null) {
4140 Settings.System.clearConfiguration(values);
4141 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 UserHandle.USER_NULL, false /* deferResume */,
4144 mTmpUpdateConfigurationResult);
4145 return mTmpUpdateConfigurationResult.changes != 0;
4146 } finally {
4147 Binder.restoreCallingIdentity(origId);
4148 }
4149 }
4150 }
4151
4152 @Override
4153 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4154 CharSequence message) {
4155 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4158 }
4159 final long callingId = Binder.clearCallingIdentity();
4160 try {
4161 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004162 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 }
4164 } finally {
4165 Binder.restoreCallingIdentity(callingId);
4166 }
4167 }
4168
4169 @Override
4170 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004171 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 "cancelTaskWindowTransition()");
4173 final long ident = Binder.clearCallingIdentity();
4174 try {
4175 synchronized (mGlobalLock) {
4176 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4177 MATCH_TASK_IN_STACKS_ONLY);
4178 if (task == null) {
4179 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4180 return;
4181 }
4182 task.cancelWindowTransition();
4183 }
4184 } finally {
4185 Binder.restoreCallingIdentity(ident);
4186 }
4187 }
4188
4189 @Override
4190 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 final long ident = Binder.clearCallingIdentity();
4193 try {
4194 final TaskRecord task;
4195 synchronized (mGlobalLock) {
4196 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4197 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4198 if (task == null) {
4199 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4200 return null;
4201 }
4202 }
4203 // Don't call this while holding the lock as this operation might hit the disk.
4204 return task.getSnapshot(reducedResolution);
4205 } finally {
4206 Binder.restoreCallingIdentity(ident);
4207 }
4208 }
4209
4210 @Override
4211 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4212 synchronized (mGlobalLock) {
4213 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4214 if (r == null) {
4215 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4216 + token);
4217 return;
4218 }
4219 final long origId = Binder.clearCallingIdentity();
4220 try {
4221 r.setDisablePreviewScreenshots(disable);
4222 } finally {
4223 Binder.restoreCallingIdentity(origId);
4224 }
4225 }
4226 }
4227
4228 /** Return the user id of the last resumed activity. */
4229 @Override
4230 public @UserIdInt
4231 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004232 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4234 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004235 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004238 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 }
4240 }
4241
4242 @Override
4243 public void updateLockTaskFeatures(int userId, int flags) {
4244 final int callingUid = Binder.getCallingUid();
4245 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004246 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 "updateLockTaskFeatures()");
4248 }
4249 synchronized (mGlobalLock) {
4250 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4251 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004252 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 }
4254 }
4255
4256 @Override
4257 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4258 synchronized (mGlobalLock) {
4259 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4260 if (r == null) {
4261 return;
4262 }
4263 final long origId = Binder.clearCallingIdentity();
4264 try {
4265 r.setShowWhenLocked(showWhenLocked);
4266 } finally {
4267 Binder.restoreCallingIdentity(origId);
4268 }
4269 }
4270 }
4271
4272 @Override
4273 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4274 synchronized (mGlobalLock) {
4275 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4276 if (r == null) {
4277 return;
4278 }
4279 final long origId = Binder.clearCallingIdentity();
4280 try {
4281 r.setTurnScreenOn(turnScreenOn);
4282 } finally {
4283 Binder.restoreCallingIdentity(origId);
4284 }
4285 }
4286 }
4287
4288 @Override
4289 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004290 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004291 "registerRemoteAnimations");
4292 definition.setCallingPid(Binder.getCallingPid());
4293 synchronized (mGlobalLock) {
4294 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4295 if (r == null) {
4296 return;
4297 }
4298 final long origId = Binder.clearCallingIdentity();
4299 try {
4300 r.registerRemoteAnimations(definition);
4301 } finally {
4302 Binder.restoreCallingIdentity(origId);
4303 }
4304 }
4305 }
4306
4307 @Override
4308 public void registerRemoteAnimationForNextActivityStart(String packageName,
4309 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 "registerRemoteAnimationForNextActivityStart");
4312 adapter.setCallingPid(Binder.getCallingPid());
4313 synchronized (mGlobalLock) {
4314 final long origId = Binder.clearCallingIdentity();
4315 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004316 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 packageName, adapter);
4318 } finally {
4319 Binder.restoreCallingIdentity(origId);
4320 }
4321 }
4322 }
4323
4324 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4325 @Override
4326 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4327 synchronized (mGlobalLock) {
4328 final long origId = Binder.clearCallingIdentity();
4329 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004330 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004331 } finally {
4332 Binder.restoreCallingIdentity(origId);
4333 }
4334 }
4335 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004336
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004337 @Override
4338 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004339 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004340 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004341 final int pid = Binder.getCallingPid();
4342 final WindowProcessController wpc = mPidMap.get(pid);
4343 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004344 }
4345 }
4346
4347 @Override
4348 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004349 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004350 != PERMISSION_GRANTED) {
4351 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4352 + Binder.getCallingPid()
4353 + ", uid=" + Binder.getCallingUid()
4354 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4355 Slog.w(TAG, msg);
4356 throw new SecurityException(msg);
4357 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004358 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004359 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004360 final int pid = Binder.getCallingPid();
4361 final WindowProcessController proc = mPidMap.get(pid);
4362 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004363 }
4364 }
4365
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 @Override
4367 public void stopAppSwitches() {
4368 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4369 synchronized (mGlobalLock) {
4370 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4371 mDidAppSwitch = false;
4372 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4373 }
4374 }
4375
4376 @Override
4377 public void resumeAppSwitches() {
4378 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4379 synchronized (mGlobalLock) {
4380 // Note that we don't execute any pending app switches... we will
4381 // let those wait until either the timeout, or the next start
4382 // activity request.
4383 mAppSwitchesAllowedTime = 0;
4384 }
4385 }
4386
4387 void onStartActivitySetDidAppSwitch() {
4388 if (mDidAppSwitch) {
4389 // This is the second allowed switch since we stopped switches, so now just generally
4390 // allow switches. Use case:
4391 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4392 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4393 // anyone to switch again).
4394 mAppSwitchesAllowedTime = 0;
4395 } else {
4396 mDidAppSwitch = true;
4397 }
4398 }
4399
4400 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004401 boolean shouldDisableNonVrUiLocked() {
4402 return mVrController.shouldDisableNonVrUiLocked();
4403 }
4404
Wale Ogunwale53783742018-09-16 10:21:51 -07004405 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004406 // VR apps are expected to run in a main display. If an app is turning on VR for
4407 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4408 // fullscreen stack before enabling VR Mode.
4409 // TODO: The goal of this code is to keep the VR app on the main display. When the
4410 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4411 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4412 // option would be a better choice here.
4413 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4414 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4415 + " to main stack for VR");
4416 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4417 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4418 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4419 }
4420 mH.post(() -> {
4421 if (!mVrController.onVrModeChanged(r)) {
4422 return;
4423 }
4424 synchronized (mGlobalLock) {
4425 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4426 mWindowManager.disableNonVrUi(disableNonVrUi);
4427 if (disableNonVrUi) {
4428 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4429 // then remove the pinned stack.
4430 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4431 }
4432 }
4433 });
4434 }
4435
Wale Ogunwale53783742018-09-16 10:21:51 -07004436 @Override
4437 public int getPackageScreenCompatMode(String packageName) {
4438 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4439 synchronized (mGlobalLock) {
4440 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4441 }
4442 }
4443
4444 @Override
4445 public void setPackageScreenCompatMode(String packageName, int mode) {
4446 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4447 "setPackageScreenCompatMode");
4448 synchronized (mGlobalLock) {
4449 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4450 }
4451 }
4452
4453 @Override
4454 public boolean getPackageAskScreenCompat(String packageName) {
4455 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4456 synchronized (mGlobalLock) {
4457 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4458 }
4459 }
4460
4461 @Override
4462 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4463 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4464 "setPackageAskScreenCompat");
4465 synchronized (mGlobalLock) {
4466 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4467 }
4468 }
4469
Wale Ogunwale64258362018-10-16 15:13:37 -07004470 public static String relaunchReasonToString(int relaunchReason) {
4471 switch (relaunchReason) {
4472 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4473 return "window_resize";
4474 case RELAUNCH_REASON_FREE_RESIZE:
4475 return "free_resize";
4476 default:
4477 return null;
4478 }
4479 }
4480
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004481 ActivityStack getTopDisplayFocusedStack() {
4482 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004483 }
4484
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004485 /** Pokes the task persister. */
4486 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4487 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4488 }
4489
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004490 boolean isKeyguardLocked() {
4491 return mKeyguardController.isKeyguardLocked();
4492 }
4493
Wale Ogunwale31913b52018-10-13 08:29:31 -07004494 void dumpLastANRLocked(PrintWriter pw) {
4495 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4496 if (mLastANRState == null) {
4497 pw.println(" <no ANR has occurred since boot>");
4498 } else {
4499 pw.println(mLastANRState);
4500 }
4501 }
4502
4503 void dumpLastANRTracesLocked(PrintWriter pw) {
4504 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4505
4506 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4507 if (ArrayUtils.isEmpty(files)) {
4508 pw.println(" <no ANR has occurred since boot>");
4509 return;
4510 }
4511 // Find the latest file.
4512 File latest = null;
4513 for (File f : files) {
4514 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4515 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004516 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004517 }
4518 pw.print("File: ");
4519 pw.print(latest.getName());
4520 pw.println();
4521 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4522 String line;
4523 while ((line = in.readLine()) != null) {
4524 pw.println(line);
4525 }
4526 } catch (IOException e) {
4527 pw.print("Unable to read: ");
4528 pw.print(e);
4529 pw.println();
4530 }
4531 }
4532
4533 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4534 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4535 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4536 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4537 }
4538
4539 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4540 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4541 pw.println(header);
4542
4543 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4544 dumpPackage);
4545 boolean needSep = printedAnything;
4546
4547 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4548 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4549 " ResumedActivity: ");
4550 if (printed) {
4551 printedAnything = true;
4552 needSep = false;
4553 }
4554
4555 if (dumpPackage == null) {
4556 if (needSep) {
4557 pw.println();
4558 }
4559 printedAnything = true;
4560 mStackSupervisor.dump(pw, " ");
4561 }
4562
4563 if (!printedAnything) {
4564 pw.println(" (nothing)");
4565 }
4566 }
4567
4568 void dumpActivityContainersLocked(PrintWriter pw) {
4569 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4570 mStackSupervisor.dumpChildrenNames(pw, " ");
4571 pw.println(" ");
4572 }
4573
4574 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4575 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4576 getActivityStartController().dump(pw, "", dumpPackage);
4577 }
4578
4579 /**
4580 * There are three things that cmd can be:
4581 * - a flattened component name that matches an existing activity
4582 * - the cmd arg isn't the flattened component name of an existing activity:
4583 * dump all activity whose component contains the cmd as a substring
4584 * - A hex number of the ActivityRecord object instance.
4585 *
4586 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4587 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4588 */
4589 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4590 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4591 ArrayList<ActivityRecord> activities;
4592
4593 synchronized (mGlobalLock) {
4594 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4595 dumpFocusedStackOnly);
4596 }
4597
4598 if (activities.size() <= 0) {
4599 return false;
4600 }
4601
4602 String[] newArgs = new String[args.length - opti];
4603 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4604
4605 TaskRecord lastTask = null;
4606 boolean needSep = false;
4607 for (int i = activities.size() - 1; i >= 0; i--) {
4608 ActivityRecord r = activities.get(i);
4609 if (needSep) {
4610 pw.println();
4611 }
4612 needSep = true;
4613 synchronized (mGlobalLock) {
4614 final TaskRecord task = r.getTask();
4615 if (lastTask != task) {
4616 lastTask = task;
4617 pw.print("TASK "); pw.print(lastTask.affinity);
4618 pw.print(" id="); pw.print(lastTask.taskId);
4619 pw.print(" userId="); pw.println(lastTask.userId);
4620 if (dumpAll) {
4621 lastTask.dump(pw, " ");
4622 }
4623 }
4624 }
4625 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4626 }
4627 return true;
4628 }
4629
4630 /**
4631 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4632 * there is a thread associated with the activity.
4633 */
4634 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4635 final ActivityRecord r, String[] args, boolean dumpAll) {
4636 String innerPrefix = prefix + " ";
4637 synchronized (mGlobalLock) {
4638 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4639 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4640 pw.print(" pid=");
4641 if (r.hasProcess()) pw.println(r.app.getPid());
4642 else pw.println("(not running)");
4643 if (dumpAll) {
4644 r.dump(pw, innerPrefix);
4645 }
4646 }
4647 if (r.attachedToProcess()) {
4648 // flush anything that is already in the PrintWriter since the thread is going
4649 // to write to the file descriptor directly
4650 pw.flush();
4651 try {
4652 TransferPipe tp = new TransferPipe();
4653 try {
4654 r.app.getThread().dumpActivity(tp.getWriteFd(),
4655 r.appToken, innerPrefix, args);
4656 tp.go(fd);
4657 } finally {
4658 tp.kill();
4659 }
4660 } catch (IOException e) {
4661 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4662 } catch (RemoteException e) {
4663 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4664 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004665 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004666 }
4667
Wale Ogunwalef6733932018-06-27 05:14:34 -07004668 void writeSleepStateToProto(ProtoOutputStream proto) {
4669 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4670 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4671 st.toString());
4672 }
4673
4674 if (mRunningVoice != null) {
4675 final long vrToken = proto.start(
4676 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4677 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4678 mRunningVoice.toString());
4679 mVoiceWakeLock.writeToProto(
4680 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4681 proto.end(vrToken);
4682 }
4683
4684 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4685 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4686 mShuttingDown);
4687 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 }
4689
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004690 int getCurrentUserId() {
4691 return mAmInternal.getCurrentUserId();
4692 }
4693
4694 private void enforceNotIsolatedCaller(String caller) {
4695 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4696 throw new SecurityException("Isolated process not allowed to call " + caller);
4697 }
4698 }
4699
Wale Ogunwalef6733932018-06-27 05:14:34 -07004700 public Configuration getConfiguration() {
4701 Configuration ci;
4702 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004703 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004704 ci.userSetLocale = false;
4705 }
4706 return ci;
4707 }
4708
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004709 /**
4710 * Current global configuration information. Contains general settings for the entire system,
4711 * also corresponds to the merged configuration of the default display.
4712 */
4713 Configuration getGlobalConfiguration() {
4714 return mStackSupervisor.getConfiguration();
4715 }
4716
4717 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4718 boolean initLocale) {
4719 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4720 }
4721
4722 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4723 boolean initLocale, boolean deferResume) {
4724 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4725 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4726 UserHandle.USER_NULL, deferResume);
4727 }
4728
Wale Ogunwale59507092018-10-29 09:00:30 -07004729 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004730 final long origId = Binder.clearCallingIdentity();
4731 try {
4732 synchronized (mGlobalLock) {
4733 updateConfigurationLocked(values, null, false, true, userId,
4734 false /* deferResume */);
4735 }
4736 } finally {
4737 Binder.restoreCallingIdentity(origId);
4738 }
4739 }
4740
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4742 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4743 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4744 deferResume, null /* result */);
4745 }
4746
4747 /**
4748 * Do either or both things: (1) change the current configuration, and (2)
4749 * make sure the given activity is running with the (now) current
4750 * configuration. Returns true if the activity has been left running, or
4751 * false if <var>starting</var> is being destroyed to match the new
4752 * configuration.
4753 *
4754 * @param userId is only used when persistent parameter is set to true to persist configuration
4755 * for that particular user
4756 */
4757 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4758 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4759 ActivityTaskManagerService.UpdateConfigurationResult result) {
4760 int changes = 0;
4761 boolean kept = true;
4762
4763 if (mWindowManager != null) {
4764 mWindowManager.deferSurfaceLayout();
4765 }
4766 try {
4767 if (values != null) {
4768 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4769 deferResume);
4770 }
4771
4772 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4773 } finally {
4774 if (mWindowManager != null) {
4775 mWindowManager.continueSurfaceLayout();
4776 }
4777 }
4778
4779 if (result != null) {
4780 result.changes = changes;
4781 result.activityRelaunched = !kept;
4782 }
4783 return kept;
4784 }
4785
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004786 /** Update default (global) configuration and notify listeners about changes. */
4787 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4788 boolean persistent, int userId, boolean deferResume) {
4789 mTempConfig.setTo(getGlobalConfiguration());
4790 final int changes = mTempConfig.updateFrom(values);
4791 if (changes == 0) {
4792 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4793 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4794 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4795 // (even if there are no actual changes) to unfreeze the window.
4796 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4797 return 0;
4798 }
4799
4800 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4801 "Updating global configuration to: " + values);
4802
4803 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4804 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4805 values.colorMode,
4806 values.densityDpi,
4807 values.fontScale,
4808 values.hardKeyboardHidden,
4809 values.keyboard,
4810 values.keyboardHidden,
4811 values.mcc,
4812 values.mnc,
4813 values.navigation,
4814 values.navigationHidden,
4815 values.orientation,
4816 values.screenHeightDp,
4817 values.screenLayout,
4818 values.screenWidthDp,
4819 values.smallestScreenWidthDp,
4820 values.touchscreen,
4821 values.uiMode);
4822
4823
4824 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4825 final LocaleList locales = values.getLocales();
4826 int bestLocaleIndex = 0;
4827 if (locales.size() > 1) {
4828 if (mSupportedSystemLocales == null) {
4829 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4830 }
4831 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4832 }
4833 SystemProperties.set("persist.sys.locale",
4834 locales.get(bestLocaleIndex).toLanguageTag());
4835 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004836
4837 final Message m = PooledLambda.obtainMessage(
4838 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4839 locales.get(bestLocaleIndex));
4840 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004841 }
4842
Yunfan Chen75157d72018-07-27 14:47:21 +09004843 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004844
4845 // Update stored global config and notify everyone about the change.
4846 mStackSupervisor.onConfigurationChanged(mTempConfig);
4847
4848 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4849 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004850 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004851
4852 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004853 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004854
4855 AttributeCache ac = AttributeCache.instance();
4856 if (ac != null) {
4857 ac.updateConfiguration(mTempConfig);
4858 }
4859
4860 // Make sure all resources in our process are updated right now, so that anyone who is going
4861 // to retrieve resource values after we return will be sure to get the new ones. This is
4862 // especially important during boot, where the first config change needs to guarantee all
4863 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004864 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004865
4866 // We need another copy of global config because we're scheduling some calls instead of
4867 // running them in place. We need to be sure that object we send will be handled unchanged.
4868 final Configuration configCopy = new Configuration(mTempConfig);
4869 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004870 final Message msg = PooledLambda.obtainMessage(
4871 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4872 this, userId, configCopy);
4873 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004874 }
4875
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004876 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004877 final int pid = mPidMap.keyAt(i);
4878 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004879 if (DEBUG_CONFIGURATION) {
4880 Slog.v(TAG_CONFIGURATION, "Update process config of "
4881 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004882 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004883 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004884 }
4885
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004886 final Message msg = PooledLambda.obtainMessage(
4887 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4888 mAmInternal, changes, initLocale);
4889 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890
4891 // Override configuration of the default display duplicates global config, so we need to
4892 // update it also. This will also notify WindowManager about changes.
4893 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4894 DEFAULT_DISPLAY);
4895
4896 return changes;
4897 }
4898
4899 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4900 boolean deferResume, int displayId) {
4901 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4902 displayId, null /* result */);
4903 }
4904
4905 /**
4906 * Updates override configuration specific for the selected display. If no config is provided,
4907 * new one will be computed in WM based on current display info.
4908 */
4909 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4910 ActivityRecord starting, boolean deferResume, int displayId,
4911 ActivityTaskManagerService.UpdateConfigurationResult result) {
4912 int changes = 0;
4913 boolean kept = true;
4914
4915 if (mWindowManager != null) {
4916 mWindowManager.deferSurfaceLayout();
4917 }
4918 try {
4919 if (values != null) {
4920 if (displayId == DEFAULT_DISPLAY) {
4921 // Override configuration of the default display duplicates global config, so
4922 // we're calling global config update instead for default display. It will also
4923 // apply the correct override config.
4924 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4925 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4926 } else {
4927 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4928 }
4929 }
4930
4931 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4932 } finally {
4933 if (mWindowManager != null) {
4934 mWindowManager.continueSurfaceLayout();
4935 }
4936 }
4937
4938 if (result != null) {
4939 result.changes = changes;
4940 result.activityRelaunched = !kept;
4941 }
4942 return kept;
4943 }
4944
4945 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4946 int displayId) {
4947 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4948 final int changes = mTempConfig.updateFrom(values);
4949 if (changes != 0) {
4950 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4951 + mTempConfig + " for displayId=" + displayId);
4952 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4953
4954 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4955 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004956 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004957
Wale Ogunwale5c918702018-10-18 11:06:33 -07004958 // Post message to start process to avoid possible deadlock of calling into AMS with
4959 // the ATMS lock held.
4960 final Message msg = PooledLambda.obtainMessage(
4961 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4962 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4963 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004964 }
4965 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004966 return changes;
4967 }
4968
Wale Ogunwalef6733932018-06-27 05:14:34 -07004969 private void updateEventDispatchingLocked(boolean booted) {
4970 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4971 }
4972
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004973 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4974 final ContentResolver resolver = mContext.getContentResolver();
4975 Settings.System.putConfigurationForUser(resolver, config, userId);
4976 }
4977
4978 private void sendLocaleToMountDaemonMsg(Locale l) {
4979 try {
4980 IBinder service = ServiceManager.getService("mount");
4981 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4982 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
4983 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
4984 } catch (RemoteException e) {
4985 Log.e(TAG, "Error storing locale for decryption UI", e);
4986 }
4987 }
4988
Alison Cichowlas3e340502018-08-07 17:15:01 -04004989 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
4990 mStartActivitySources.remove(permissionToken);
4991 mExpiredStartAsCallerTokens.add(permissionToken);
4992 }
4993
4994 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
4995 mExpiredStartAsCallerTokens.remove(permissionToken);
4996 }
4997
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004998 boolean isActivityStartsLoggingEnabled() {
4999 return mAmInternal.isActivityStartsLoggingEnabled();
5000 }
5001
Wale Ogunwalef6733932018-06-27 05:14:34 -07005002 void enableScreenAfterBoot(boolean booted) {
5003 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5004 SystemClock.uptimeMillis());
5005 mWindowManager.enableScreenAfterBoot();
5006
5007 synchronized (mGlobalLock) {
5008 updateEventDispatchingLocked(booted);
5009 }
5010 }
5011
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005012 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5013 if (r == null || !r.hasProcess()) {
5014 return KEY_DISPATCHING_TIMEOUT_MS;
5015 }
5016 return getInputDispatchingTimeoutLocked(r.app);
5017 }
5018
5019 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005020 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005021 }
5022
Wale Ogunwalef6733932018-06-27 05:14:34 -07005023 /**
5024 * Decide based on the configuration whether we should show the ANR,
5025 * crash, etc dialogs. The idea is that if there is no affordance to
5026 * press the on-screen buttons, or the user experience would be more
5027 * greatly impacted than the crash itself, we shouldn't show the dialog.
5028 *
5029 * A thought: SystemUI might also want to get told about this, the Power
5030 * dialog / global actions also might want different behaviors.
5031 */
5032 private void updateShouldShowDialogsLocked(Configuration config) {
5033 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5034 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5035 && config.navigation == Configuration.NAVIGATION_NONAV);
5036 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5037 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5038 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5039 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5040 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5041 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5042 HIDE_ERROR_DIALOGS, 0) != 0;
5043 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5044 }
5045
5046 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5047 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5048 FONT_SCALE, 1.0f, userId);
5049
5050 synchronized (this) {
5051 if (getGlobalConfiguration().fontScale == scaleFactor) {
5052 return;
5053 }
5054
5055 final Configuration configuration
5056 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5057 configuration.fontScale = scaleFactor;
5058 updatePersistentConfiguration(configuration, userId);
5059 }
5060 }
5061
5062 // Actually is sleeping or shutting down or whatever else in the future
5063 // is an inactive state.
5064 boolean isSleepingOrShuttingDownLocked() {
5065 return isSleepingLocked() || mShuttingDown;
5066 }
5067
5068 boolean isSleepingLocked() {
5069 return mSleeping;
5070 }
5071
Riddle Hsu16567132018-08-16 21:37:47 +08005072 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005073 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5074 final TaskRecord task = r.getTask();
5075 if (task.isActivityTypeStandard()) {
5076 if (mCurAppTimeTracker != r.appTimeTracker) {
5077 // We are switching app tracking. Complete the current one.
5078 if (mCurAppTimeTracker != null) {
5079 mCurAppTimeTracker.stop();
5080 mH.obtainMessage(
5081 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5082 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
5083 mCurAppTimeTracker = null;
5084 }
5085 if (r.appTimeTracker != null) {
5086 mCurAppTimeTracker = r.appTimeTracker;
5087 startTimeTrackingFocusedActivityLocked();
5088 }
5089 } else {
5090 startTimeTrackingFocusedActivityLocked();
5091 }
5092 } else {
5093 r.appTimeTracker = null;
5094 }
5095 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5096 // TODO: Probably not, because we don't want to resume voice on switching
5097 // back to this activity
5098 if (task.voiceInteractor != null) {
5099 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5100 } else {
5101 finishRunningVoiceLocked();
5102
5103 if (mLastResumedActivity != null) {
5104 final IVoiceInteractionSession session;
5105
5106 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5107 if (lastResumedActivityTask != null
5108 && lastResumedActivityTask.voiceSession != null) {
5109 session = lastResumedActivityTask.voiceSession;
5110 } else {
5111 session = mLastResumedActivity.voiceSession;
5112 }
5113
5114 if (session != null) {
5115 // We had been in a voice interaction session, but now focused has
5116 // move to something different. Just finish the session, we can't
5117 // return to it and retain the proper state and synchronization with
5118 // the voice interaction service.
5119 finishVoiceTask(session);
5120 }
5121 }
5122 }
5123
5124 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5125 mAmInternal.sendForegroundProfileChanged(r.userId);
5126 }
5127 updateResumedAppTrace(r);
5128 mLastResumedActivity = r;
5129
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005130 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005131
5132 applyUpdateLockStateLocked(r);
5133 applyUpdateVrModeLocked(r);
5134
5135 EventLogTags.writeAmSetResumedActivity(
5136 r == null ? -1 : r.userId,
5137 r == null ? "NULL" : r.shortComponentName,
5138 reason);
5139 }
5140
5141 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5142 synchronized (mGlobalLock) {
5143 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5144 updateSleepIfNeededLocked();
5145 return token;
5146 }
5147 }
5148
5149 void updateSleepIfNeededLocked() {
5150 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5151 final boolean wasSleeping = mSleeping;
5152 boolean updateOomAdj = false;
5153
5154 if (!shouldSleep) {
5155 // If wasSleeping is true, we need to wake up activity manager state from when
5156 // we started sleeping. In either case, we need to apply the sleep tokens, which
5157 // will wake up stacks or put them to sleep as appropriate.
5158 if (wasSleeping) {
5159 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005160 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5161 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005162 startTimeTrackingFocusedActivityLocked();
5163 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5164 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5165 }
5166 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5167 if (wasSleeping) {
5168 updateOomAdj = true;
5169 }
5170 } else if (!mSleeping && shouldSleep) {
5171 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005172 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5173 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005174 if (mCurAppTimeTracker != null) {
5175 mCurAppTimeTracker.stop();
5176 }
5177 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5178 mStackSupervisor.goingToSleepLocked();
5179 updateResumedAppTrace(null /* resumed */);
5180 updateOomAdj = true;
5181 }
5182 if (updateOomAdj) {
5183 mH.post(mAmInternal::updateOomAdj);
5184 }
5185 }
5186
5187 void updateOomAdj() {
5188 mH.post(mAmInternal::updateOomAdj);
5189 }
5190
Wale Ogunwale53783742018-09-16 10:21:51 -07005191 void updateCpuStats() {
5192 mH.post(mAmInternal::updateCpuStats);
5193 }
5194
5195 void updateUsageStats(ActivityRecord component, boolean resumed) {
5196 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5197 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5198 mH.sendMessage(m);
5199 }
5200
5201 void setBooting(boolean booting) {
5202 mAmInternal.setBooting(booting);
5203 }
5204
5205 boolean isBooting() {
5206 return mAmInternal.isBooting();
5207 }
5208
5209 void setBooted(boolean booted) {
5210 mAmInternal.setBooted(booted);
5211 }
5212
5213 boolean isBooted() {
5214 return mAmInternal.isBooted();
5215 }
5216
5217 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5218 mH.post(() -> {
5219 if (finishBooting) {
5220 mAmInternal.finishBooting();
5221 }
5222 if (enableScreen) {
5223 mInternal.enableScreenAfterBoot(isBooted());
5224 }
5225 });
5226 }
5227
5228 void setHeavyWeightProcess(ActivityRecord root) {
5229 mHeavyWeightProcess = root.app;
5230 final Message m = PooledLambda.obtainMessage(
5231 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5232 root.app, root.intent, root.userId);
5233 mH.sendMessage(m);
5234 }
5235
5236 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5237 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5238 return;
5239 }
5240
5241 mHeavyWeightProcess = null;
5242 final Message m = PooledLambda.obtainMessage(
5243 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5244 proc.mUserId);
5245 mH.sendMessage(m);
5246 }
5247
5248 private void cancelHeavyWeightProcessNotification(int userId) {
5249 final INotificationManager inm = NotificationManager.getService();
5250 if (inm == null) {
5251 return;
5252 }
5253 try {
5254 inm.cancelNotificationWithTag("android", null,
5255 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5256 } catch (RuntimeException e) {
5257 Slog.w(TAG, "Error canceling notification for service", e);
5258 } catch (RemoteException e) {
5259 }
5260
5261 }
5262
5263 private void postHeavyWeightProcessNotification(
5264 WindowProcessController proc, Intent intent, int userId) {
5265 if (proc == null) {
5266 return;
5267 }
5268
5269 final INotificationManager inm = NotificationManager.getService();
5270 if (inm == null) {
5271 return;
5272 }
5273
5274 try {
5275 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5276 String text = mContext.getString(R.string.heavy_weight_notification,
5277 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5278 Notification notification =
5279 new Notification.Builder(context,
5280 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5281 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5282 .setWhen(0)
5283 .setOngoing(true)
5284 .setTicker(text)
5285 .setColor(mContext.getColor(
5286 com.android.internal.R.color.system_notification_accent_color))
5287 .setContentTitle(text)
5288 .setContentText(
5289 mContext.getText(R.string.heavy_weight_notification_detail))
5290 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5291 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5292 new UserHandle(userId)))
5293 .build();
5294 try {
5295 inm.enqueueNotificationWithTag("android", "android", null,
5296 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5297 } catch (RuntimeException e) {
5298 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5299 } catch (RemoteException e) {
5300 }
5301 } catch (PackageManager.NameNotFoundException e) {
5302 Slog.w(TAG, "Unable to create context for heavy notification", e);
5303 }
5304
5305 }
5306
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005307 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5308 IBinder token, String resultWho, int requestCode, Intent[] intents,
5309 String[] resolvedTypes, int flags, Bundle bOptions) {
5310
5311 ActivityRecord activity = null;
5312 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5313 activity = ActivityRecord.isInStackLocked(token);
5314 if (activity == null) {
5315 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5316 return null;
5317 }
5318 if (activity.finishing) {
5319 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5320 return null;
5321 }
5322 }
5323
5324 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5325 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5326 bOptions);
5327 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5328 if (noCreate) {
5329 return rec;
5330 }
5331 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5332 if (activity.pendingResults == null) {
5333 activity.pendingResults = new HashSet<>();
5334 }
5335 activity.pendingResults.add(rec.ref);
5336 }
5337 return rec;
5338 }
5339
Andrii Kulian52d255c2018-07-13 11:32:19 -07005340 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005341 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005342 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005343 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5344 mCurAppTimeTracker.start(resumedActivity.packageName);
5345 }
5346 }
5347
5348 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5349 if (mTracedResumedActivity != null) {
5350 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5351 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5352 }
5353 if (resumed != null) {
5354 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5355 constructResumedTraceName(resumed.packageName), 0);
5356 }
5357 mTracedResumedActivity = resumed;
5358 }
5359
5360 private String constructResumedTraceName(String packageName) {
5361 return "focused app: " + packageName;
5362 }
5363
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005364 /** Applies latest configuration and/or visibility updates if needed. */
5365 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5366 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005367 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005368 // mainStack is null during startup.
5369 if (mainStack != null) {
5370 if (changes != 0 && starting == null) {
5371 // If the configuration changed, and the caller is not already
5372 // in the process of starting an activity, then find the top
5373 // activity to check if its configuration needs to change.
5374 starting = mainStack.topRunningActivityLocked();
5375 }
5376
5377 if (starting != null) {
5378 kept = starting.ensureActivityConfiguration(changes,
5379 false /* preserveWindow */);
5380 // And we need to make sure at this point that all other activities
5381 // are made visible with the correct configuration.
5382 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5383 !PRESERVE_WINDOWS);
5384 }
5385 }
5386
5387 return kept;
5388 }
5389
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005390 void scheduleAppGcsLocked() {
5391 mH.post(() -> mAmInternal.scheduleAppGcs());
5392 }
5393
Wale Ogunwale53783742018-09-16 10:21:51 -07005394 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5395 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5396 }
5397
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005398 /**
5399 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5400 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5401 * on demand.
5402 */
5403 IPackageManager getPackageManager() {
5404 return AppGlobals.getPackageManager();
5405 }
5406
5407 PackageManagerInternal getPackageManagerInternalLocked() {
5408 if (mPmInternal == null) {
5409 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5410 }
5411 return mPmInternal;
5412 }
5413
Wale Ogunwale008163e2018-07-23 23:11:08 -07005414 AppWarnings getAppWarningsLocked() {
5415 return mAppWarnings;
5416 }
5417
Wale Ogunwale214f3482018-10-04 11:00:47 -07005418 Intent getHomeIntent() {
5419 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5420 intent.setComponent(mTopComponent);
5421 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5422 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5423 intent.addCategory(Intent.CATEGORY_HOME);
5424 }
5425 return intent;
5426 }
5427
Wale Ogunwale214f3482018-10-04 11:00:47 -07005428 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5429 if (info == null) return null;
5430 ApplicationInfo newInfo = new ApplicationInfo(info);
5431 newInfo.initForUser(userId);
5432 return newInfo;
5433 }
5434
Wale Ogunwale9c103022018-10-18 07:44:54 -07005435 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005436 if (uid == SYSTEM_UID) {
5437 // The system gets to run in any process. If there are multiple processes with the same
5438 // uid, just pick the first (this should never happen).
5439 final SparseArray<WindowProcessController> procs =
5440 mProcessNames.getMap().get(processName);
5441 if (procs == null) return null;
5442 final int procCount = procs.size();
5443 for (int i = 0; i < procCount; i++) {
5444 final int procUid = procs.keyAt(i);
5445 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5446 // Don't use an app process or different user process for system component.
5447 continue;
5448 }
5449 return procs.valueAt(i);
5450 }
5451 }
5452
5453 return mProcessNames.get(processName, uid);
5454 }
5455
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005456 WindowProcessController getProcessController(IApplicationThread thread) {
5457 if (thread == null) {
5458 return null;
5459 }
5460
5461 final IBinder threadBinder = thread.asBinder();
5462 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5463 for (int i = pmap.size()-1; i >= 0; i--) {
5464 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5465 for (int j = procs.size() - 1; j >= 0; j--) {
5466 final WindowProcessController proc = procs.valueAt(j);
5467 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5468 return proc;
5469 }
5470 }
5471 }
5472
5473 return null;
5474 }
5475
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005476 int getUidStateLocked(int uid) {
5477 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5478 }
5479
Wale Ogunwale9de19442018-10-18 19:05:03 -07005480 /**
5481 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5482 * the whitelist
5483 */
5484 String getPendingTempWhitelistTagForUidLocked(int uid) {
5485 return mPendingTempWhitelist.get(uid);
5486 }
5487
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005488 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5489 if (true || Build.IS_USER) {
5490 return;
5491 }
5492
5493 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5494 StrictMode.allowThreadDiskWrites();
5495 try {
5496 File tracesDir = new File("/data/anr");
5497 File tracesFile = null;
5498 try {
5499 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5500
5501 StringBuilder sb = new StringBuilder();
5502 Time tobj = new Time();
5503 tobj.set(System.currentTimeMillis());
5504 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5505 sb.append(": ");
5506 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5507 sb.append(" since ");
5508 sb.append(msg);
5509 FileOutputStream fos = new FileOutputStream(tracesFile);
5510 fos.write(sb.toString().getBytes());
5511 if (app == null) {
5512 fos.write("\n*** No application process!".getBytes());
5513 }
5514 fos.close();
5515 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5516 } catch (IOException e) {
5517 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5518 return;
5519 }
5520
5521 if (app != null && app.getPid() > 0) {
5522 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5523 firstPids.add(app.getPid());
5524 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5525 }
5526
5527 File lastTracesFile = null;
5528 File curTracesFile = null;
5529 for (int i=9; i>=0; i--) {
5530 String name = String.format(Locale.US, "slow%02d.txt", i);
5531 curTracesFile = new File(tracesDir, name);
5532 if (curTracesFile.exists()) {
5533 if (lastTracesFile != null) {
5534 curTracesFile.renameTo(lastTracesFile);
5535 } else {
5536 curTracesFile.delete();
5537 }
5538 }
5539 lastTracesFile = curTracesFile;
5540 }
5541 tracesFile.renameTo(curTracesFile);
5542 } finally {
5543 StrictMode.setThreadPolicy(oldPolicy);
5544 }
5545 }
5546
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005547 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005549
5550
Wale Ogunwale98875612018-10-12 07:53:02 -07005551 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5552 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005554 public H() {
5555 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005556 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557
5558 @Override
5559 public void handleMessage(Message msg) {
5560 switch (msg.what) {
5561 case REPORT_TIME_TRACKER_MSG: {
5562 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5563 tracker.deliverResult(mContext);
5564 } break;
5565 }
5566 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005567 }
5568
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005569 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005571
5572 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005573 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005574 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005575
5576 @Override
5577 public void handleMessage(Message msg) {
5578 switch (msg.what) {
5579 case DISMISS_DIALOG_UI_MSG: {
5580 final Dialog d = (Dialog) msg.obj;
5581 d.dismiss();
5582 break;
5583 }
5584 }
5585 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005586 }
5587
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005588 final class LocalService extends ActivityTaskManagerInternal {
5589 @Override
5590 public SleepToken acquireSleepToken(String tag, int displayId) {
5591 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005593 }
5594
5595 @Override
5596 public ComponentName getHomeActivityForUser(int userId) {
5597 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005598 ActivityRecord homeActivity =
5599 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005600 return homeActivity == null ? null : homeActivity.realActivity;
5601 }
5602 }
5603
5604 @Override
5605 public void onLocalVoiceInteractionStarted(IBinder activity,
5606 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5607 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005608 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005609 }
5610 }
5611
5612 @Override
5613 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5614 synchronized (mGlobalLock) {
5615 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5616 reasons, timestamp);
5617 }
5618 }
5619
5620 @Override
5621 public void notifyAppTransitionFinished() {
5622 synchronized (mGlobalLock) {
5623 mStackSupervisor.notifyAppTransitionDone();
5624 }
5625 }
5626
5627 @Override
5628 public void notifyAppTransitionCancelled() {
5629 synchronized (mGlobalLock) {
5630 mStackSupervisor.notifyAppTransitionDone();
5631 }
5632 }
5633
5634 @Override
5635 public List<IBinder> getTopVisibleActivities() {
5636 synchronized (mGlobalLock) {
5637 return mStackSupervisor.getTopVisibleActivities();
5638 }
5639 }
5640
5641 @Override
5642 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5643 synchronized (mGlobalLock) {
5644 mStackSupervisor.setDockedStackMinimized(minimized);
5645 }
5646 }
5647
5648 @Override
5649 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5650 Bundle bOptions) {
5651 Preconditions.checkNotNull(intents, "intents");
5652 final String[] resolvedTypes = new String[intents.length];
5653
5654 // UID of the package on user userId.
5655 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5656 // packageUid may not be initialized.
5657 int packageUid = 0;
5658 final long ident = Binder.clearCallingIdentity();
5659
5660 try {
5661 for (int i = 0; i < intents.length; i++) {
5662 resolvedTypes[i] =
5663 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5664 }
5665
5666 packageUid = AppGlobals.getPackageManager().getPackageUid(
5667 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5668 } catch (RemoteException e) {
5669 // Shouldn't happen.
5670 } finally {
5671 Binder.restoreCallingIdentity(ident);
5672 }
5673
5674 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005675 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005676 packageUid, packageName,
5677 intents, resolvedTypes, null /* resultTo */,
5678 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005679 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005680 }
5681 }
5682
5683 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005684 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5685 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5686 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5687 synchronized (mGlobalLock) {
5688 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5689 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5690 originatingPendingIntent);
5691 }
5692 }
5693
5694 @Override
5695 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5696 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5697 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5698 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5699 PendingIntentRecord originatingPendingIntent) {
5700 synchronized (mGlobalLock) {
5701 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5702 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5703 requestCode, startFlags, options, userId, inTask, reason,
5704 validateIncomingUser, originatingPendingIntent);
5705 }
5706 }
5707
5708 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005709 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5710 Intent intent, Bundle options, int userId) {
5711 return ActivityTaskManagerService.this.startActivityAsUser(
5712 caller, callerPacakge, intent,
5713 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5714 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5715 false /*validateIncomingUser*/);
5716 }
5717
5718 @Override
lumark588a3e82018-07-20 18:53:54 +08005719 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005720 synchronized (mGlobalLock) {
5721
5722 // We might change the visibilities here, so prepare an empty app transition which
5723 // might be overridden later if we actually change visibilities.
lumark588a3e82018-07-20 18:53:54 +08005724 final DisplayWindowController dwc = mStackSupervisor.getActivityDisplay(displayId)
5725 .getWindowContainerController();
5726 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005727 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005728 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005729 }
5730 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5731
5732 // If there was a transition set already we don't want to interfere with it as we
5733 // might be starting it too early.
5734 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005735 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005736 }
5737 }
5738 if (callback != null) {
5739 callback.run();
5740 }
5741 }
5742
5743 @Override
5744 public void notifyKeyguardTrustedChanged() {
5745 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005746 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005747 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5748 }
5749 }
5750 }
5751
5752 /**
5753 * Called after virtual display Id is updated by
5754 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5755 * {@param vrVr2dDisplayId}.
5756 */
5757 @Override
5758 public void setVr2dDisplayId(int vr2dDisplayId) {
5759 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5760 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005761 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005762 }
5763 }
5764
5765 @Override
5766 public void setFocusedActivity(IBinder token) {
5767 synchronized (mGlobalLock) {
5768 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5769 if (r == null) {
5770 throw new IllegalArgumentException(
5771 "setFocusedActivity: No activity record matching token=" + token);
5772 }
Louis Chang19443452018-10-09 12:10:21 +08005773 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005774 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005775 }
5776 }
5777 }
5778
5779 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005780 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005781 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
5783
5784 @Override
5785 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005786 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005787 }
5788
5789 @Override
5790 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005791 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005792 }
5793
5794 @Override
5795 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5796 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5797 }
5798
5799 @Override
5800 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005801 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005802 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005803
5804 @Override
5805 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5806 synchronized (mGlobalLock) {
5807 mActiveVoiceInteractionServiceComponent = component;
5808 }
5809 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005810
5811 @Override
5812 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5813 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5814 return;
5815 }
5816 synchronized (mGlobalLock) {
5817 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5818 if (types == null) {
5819 if (uid < 0) {
5820 return;
5821 }
5822 types = new ArrayMap<>();
5823 mAllowAppSwitchUids.put(userId, types);
5824 }
5825 if (uid < 0) {
5826 types.remove(type);
5827 } else {
5828 types.put(type, uid);
5829 }
5830 }
5831 }
5832
5833 @Override
5834 public void onUserStopped(int userId) {
5835 synchronized (mGlobalLock) {
5836 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5837 mAllowAppSwitchUids.remove(userId);
5838 }
5839 }
5840
5841 @Override
5842 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5843 synchronized (mGlobalLock) {
5844 return ActivityTaskManagerService.this.isGetTasksAllowed(
5845 caller, callingPid, callingUid);
5846 }
5847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005848
5849 @Override
5850 public void onProcessAdded(WindowProcessController proc) {
5851 synchronized (mGlobalLock) {
5852 mProcessNames.put(proc.mName, proc.mUid, proc);
5853 }
5854 }
5855
5856 @Override
5857 public void onProcessRemoved(String name, int uid) {
5858 synchronized (mGlobalLock) {
5859 mProcessNames.remove(name, uid);
5860 }
5861 }
5862
5863 @Override
5864 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5865 synchronized (mGlobalLock) {
5866 if (proc == mHomeProcess) {
5867 mHomeProcess = null;
5868 }
5869 if (proc == mPreviousProcess) {
5870 mPreviousProcess = null;
5871 }
5872 }
5873 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005874
5875 @Override
5876 public int getTopProcessState() {
5877 synchronized (mGlobalLock) {
5878 return mTopProcessState;
5879 }
5880 }
5881
5882 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005883 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5884 synchronized (mGlobalLock) {
5885 return proc == mHeavyWeightProcess;
5886 }
5887 }
5888
5889 @Override
5890 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5891 synchronized (mGlobalLock) {
5892 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5893 }
5894 }
5895
5896 @Override
5897 public void finishHeavyWeightApp() {
5898 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005899 if (mHeavyWeightProcess != null) {
5900 mHeavyWeightProcess.finishActivities();
5901 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005902 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5903 mHeavyWeightProcess);
5904 }
5905 }
5906
5907 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005908 public boolean isSleeping() {
5909 synchronized (mGlobalLock) {
5910 return isSleepingLocked();
5911 }
5912 }
5913
5914 @Override
5915 public boolean isShuttingDown() {
5916 synchronized (mGlobalLock) {
5917 return mShuttingDown;
5918 }
5919 }
5920
5921 @Override
5922 public boolean shuttingDown(boolean booted, int timeout) {
5923 synchronized (mGlobalLock) {
5924 mShuttingDown = true;
5925 mStackSupervisor.prepareForShutdownLocked();
5926 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005927 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005928 return mStackSupervisor.shutdownLocked(timeout);
5929 }
5930 }
5931
5932 @Override
5933 public void enableScreenAfterBoot(boolean booted) {
5934 synchronized (mGlobalLock) {
5935 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5936 SystemClock.uptimeMillis());
5937 mWindowManager.enableScreenAfterBoot();
5938 updateEventDispatchingLocked(booted);
5939 }
5940 }
5941
5942 @Override
5943 public boolean showStrictModeViolationDialog() {
5944 synchronized (mGlobalLock) {
5945 return mShowDialogs && !mSleeping && !mShuttingDown;
5946 }
5947 }
5948
5949 @Override
5950 public void showSystemReadyErrorDialogsIfNeeded() {
5951 synchronized (mGlobalLock) {
5952 try {
5953 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5954 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5955 + " data partition or your device will be unstable.");
5956 mUiHandler.post(() -> {
5957 if (mShowDialogs) {
5958 AlertDialog d = new BaseErrorDialog(mUiContext);
5959 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5960 d.setCancelable(false);
5961 d.setTitle(mUiContext.getText(R.string.android_system_label));
5962 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5963 d.setButton(DialogInterface.BUTTON_POSITIVE,
5964 mUiContext.getText(R.string.ok),
5965 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5966 d.show();
5967 }
5968 });
5969 }
5970 } catch (RemoteException e) {
5971 }
5972
5973 if (!Build.isBuildConsistent()) {
5974 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5975 mUiHandler.post(() -> {
5976 if (mShowDialogs) {
5977 AlertDialog d = new BaseErrorDialog(mUiContext);
5978 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5979 d.setCancelable(false);
5980 d.setTitle(mUiContext.getText(R.string.android_system_label));
5981 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5982 d.setButton(DialogInterface.BUTTON_POSITIVE,
5983 mUiContext.getText(R.string.ok),
5984 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5985 d.show();
5986 }
5987 });
5988 }
5989 }
5990 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005991
5992 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005993 public void onProcessMapped(int pid, WindowProcessController proc) {
5994 synchronized (mGlobalLock) {
5995 mPidMap.put(pid, proc);
5996 }
5997 }
5998
5999 @Override
6000 public void onProcessUnMapped(int pid) {
6001 synchronized (mGlobalLock) {
6002 mPidMap.remove(pid);
6003 }
6004 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006005
6006 @Override
6007 public void onPackageDataCleared(String name) {
6008 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006009 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006010 mAppWarnings.onPackageDataCleared(name);
6011 }
6012 }
6013
6014 @Override
6015 public void onPackageUninstalled(String name) {
6016 synchronized (mGlobalLock) {
6017 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006018 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006019 }
6020 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006021
6022 @Override
6023 public void onPackageAdded(String name, boolean replacing) {
6024 synchronized (mGlobalLock) {
6025 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6026 }
6027 }
6028
6029 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006030 public void onPackageReplaced(ApplicationInfo aInfo) {
6031 synchronized (mGlobalLock) {
6032 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
6033 }
6034 }
6035
6036 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006037 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6038 synchronized (mGlobalLock) {
6039 return compatibilityInfoForPackageLocked(ai);
6040 }
6041 }
6042
Yunfan Chen75157d72018-07-27 14:47:21 +09006043 /**
6044 * Set the corresponding display information for the process global configuration. To be
6045 * called when we need to show IME on a different display.
6046 *
6047 * @param pid The process id associated with the IME window.
6048 * @param displayId The ID of the display showing the IME.
6049 */
6050 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006051 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006052 if (pid == MY_PID || pid < 0) {
6053 if (DEBUG_CONFIGURATION) {
6054 Slog.w(TAG,
6055 "Trying to update display configuration for system/invalid process.");
6056 }
6057 return;
6058 }
6059 mH.post(() -> {
6060 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006061 final ActivityDisplay activityDisplay =
6062 mStackSupervisor.getActivityDisplay(displayId);
6063 if (activityDisplay == null) {
6064 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006065 if (DEBUG_CONFIGURATION) {
6066 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006067 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006068 }
6069 return;
6070 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006071 final WindowProcessController process = mPidMap.get(pid);
6072 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006073 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006074 Slog.w(TAG, "Trying to update display configuration for invalid "
6075 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006076 }
6077 return;
6078 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006079 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006080 }
6081 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006082
Yunfan Chen75157d72018-07-27 14:47:21 +09006083 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006084
6085 @Override
6086 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6087 int requestCode, int resultCode, Intent data) {
6088 synchronized (mGlobalLock) {
6089 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6090 if (r != null && r.getStack() != null) {
6091 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6092 resultCode, data);
6093 }
6094 }
6095 }
6096
6097 @Override
6098 public void clearPendingResultForActivity(IBinder activityToken,
6099 WeakReference<PendingIntentRecord> pir) {
6100 synchronized (mGlobalLock) {
6101 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6102 if (r != null && r.pendingResults != null) {
6103 r.pendingResults.remove(pir);
6104 }
6105 }
6106 }
6107
6108 @Override
6109 public IIntentSender getIntentSender(int type, String packageName,
6110 int callingUid, int userId, IBinder token, String resultWho,
6111 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6112 Bundle bOptions) {
6113 synchronized (mGlobalLock) {
6114 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6115 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6116 }
6117 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006118
6119 @Override
6120 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6121 synchronized (mGlobalLock) {
6122 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6123 if (r == null) {
6124 return null;
6125 }
6126 if (r.mServiceConnectionsHolder == null) {
6127 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6128 ActivityTaskManagerService.this, r);
6129 }
6130
6131 return r.mServiceConnectionsHolder;
6132 }
6133 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006134
6135 @Override
6136 public Intent getHomeIntent() {
6137 synchronized (mGlobalLock) {
6138 return ActivityTaskManagerService.this.getHomeIntent();
6139 }
6140 }
6141
6142 @Override
6143 public boolean startHomeActivity(int userId, String reason) {
6144 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006145 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6146 }
6147 }
6148
6149 @Override
6150 public boolean startHomeOnAllDisplays(int userId, String reason) {
6151 synchronized (mGlobalLock) {
6152 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006153 }
6154 }
6155
6156 @Override
6157 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6158 synchronized (mGlobalLock) {
6159 if (mFactoryTest == FACTORY_TEST_OFF) {
6160 return false;
6161 }
6162 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6163 && wpc.mName.equals(mTopComponent.getPackageName())) {
6164 return true;
6165 }
6166 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6167 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6168 }
6169 }
6170
6171 @Override
6172 public void updateTopComponentForFactoryTest() {
6173 synchronized (mGlobalLock) {
6174 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6175 return;
6176 }
6177 final ResolveInfo ri = mContext.getPackageManager()
6178 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6179 final CharSequence errorMsg;
6180 if (ri != null) {
6181 final ActivityInfo ai = ri.activityInfo;
6182 final ApplicationInfo app = ai.applicationInfo;
6183 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6184 mTopAction = Intent.ACTION_FACTORY_TEST;
6185 mTopData = null;
6186 mTopComponent = new ComponentName(app.packageName, ai.name);
6187 errorMsg = null;
6188 } else {
6189 errorMsg = mContext.getResources().getText(
6190 com.android.internal.R.string.factorytest_not_system);
6191 }
6192 } else {
6193 errorMsg = mContext.getResources().getText(
6194 com.android.internal.R.string.factorytest_no_action);
6195 }
6196 if (errorMsg == null) {
6197 return;
6198 }
6199
6200 mTopAction = null;
6201 mTopData = null;
6202 mTopComponent = null;
6203 mUiHandler.post(() -> {
6204 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6205 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006206 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006207 });
6208 }
6209 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006210
6211 @Override
6212 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6213 Runnable finishInstrumentationCallback) {
6214 synchronized (mGlobalLock) {
6215 // Remove this application's activities from active lists.
6216 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6217
6218 wpc.clearRecentTasks();
6219 wpc.clearActivities();
6220
6221 if (wpc.isInstrumenting()) {
6222 finishInstrumentationCallback.run();
6223 }
6224
6225 mWindowManager.deferSurfaceLayout();
6226 try {
6227 if (!restarting && hasVisibleActivities
6228 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6229 // If there was nothing to resume, and we are not already restarting this
6230 // process, but there is a visible activity that is hosted by the process...
6231 // then make sure all visible activities are running, taking care of
6232 // restarting this process.
6233 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6234 }
6235 } finally {
6236 mWindowManager.continueSurfaceLayout();
6237 }
6238 }
6239 }
6240
6241 @Override
6242 public void closeSystemDialogs(String reason) {
6243 enforceNotIsolatedCaller("closeSystemDialogs");
6244
6245 final int pid = Binder.getCallingPid();
6246 final int uid = Binder.getCallingUid();
6247 final long origId = Binder.clearCallingIdentity();
6248 try {
6249 synchronized (mGlobalLock) {
6250 // Only allow this from foreground processes, so that background
6251 // applications can't abuse it to prevent system UI from being shown.
6252 if (uid >= FIRST_APPLICATION_UID) {
6253 final WindowProcessController proc = mPidMap.get(pid);
6254 if (!proc.isPerceptible()) {
6255 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6256 + " from background process " + proc);
6257 return;
6258 }
6259 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006260 mWindowManager.closeSystemDialogs(reason);
6261
6262 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006263 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006264 // Call into AM outside the synchronized block.
6265 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006266 } finally {
6267 Binder.restoreCallingIdentity(origId);
6268 }
6269 }
6270
6271 @Override
6272 public void cleanupDisabledPackageComponents(
6273 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6274 synchronized (mGlobalLock) {
6275 // Clean-up disabled activities.
6276 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6277 packageName, disabledClasses, true, false, userId) && booted) {
6278 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6279 mStackSupervisor.scheduleIdleLocked();
6280 }
6281
6282 // Clean-up disabled tasks
6283 getRecentTasks().cleanupDisabledPackageTasksLocked(
6284 packageName, disabledClasses, userId);
6285 }
6286 }
6287
6288 @Override
6289 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6290 int userId) {
6291 synchronized (mGlobalLock) {
6292
6293 boolean didSomething =
6294 getActivityStartController().clearPendingActivityLaunches(packageName);
6295 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6296 null, doit, evenPersistent, userId);
6297 return didSomething;
6298 }
6299 }
6300
6301 @Override
6302 public void resumeTopActivities(boolean scheduleIdle) {
6303 synchronized (mGlobalLock) {
6304 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6305 if (scheduleIdle) {
6306 mStackSupervisor.scheduleIdleLocked();
6307 }
6308 }
6309 }
6310
6311 @Override
6312 public void preBindApplication(WindowProcessController wpc) {
6313 synchronized (mGlobalLock) {
6314 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6315 }
6316 }
6317
6318 @Override
6319 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6320 synchronized (mGlobalLock) {
6321 return mStackSupervisor.attachApplicationLocked(wpc);
6322 }
6323 }
6324
6325 @Override
6326 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6327 try {
6328 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6329 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6330 }
6331 } catch (RemoteException ex) {
6332 throw new SecurityException("Fail to check is caller a privileged app", ex);
6333 }
6334
6335 synchronized (mGlobalLock) {
6336 final long ident = Binder.clearCallingIdentity();
6337 try {
6338 if (mAmInternal.shouldConfirmCredentials(userId)) {
6339 if (mKeyguardController.isKeyguardLocked()) {
6340 // Showing launcher to avoid user entering credential twice.
6341 startHomeActivity(currentUserId, "notifyLockedProfile");
6342 }
6343 mStackSupervisor.lockAllProfileTasks(userId);
6344 }
6345 } finally {
6346 Binder.restoreCallingIdentity(ident);
6347 }
6348 }
6349 }
6350
6351 @Override
6352 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6353 mAmInternal.enforceCallingPermission(
6354 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6355
6356 synchronized (mGlobalLock) {
6357 final long ident = Binder.clearCallingIdentity();
6358 try {
6359 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6360 FLAG_ACTIVITY_TASK_ON_HOME);
6361 ActivityOptions activityOptions = options != null
6362 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006363 final ActivityRecord homeActivity =
6364 mStackSupervisor.getDefaultDisplayHomeActivity();
6365 if (homeActivity != null) {
6366 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6367 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006368 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6369 UserHandle.CURRENT);
6370 } finally {
6371 Binder.restoreCallingIdentity(ident);
6372 }
6373 }
6374 }
6375
6376 @Override
6377 public void writeActivitiesToProto(ProtoOutputStream proto) {
6378 synchronized (mGlobalLock) {
6379 // The output proto of "activity --proto activities"
6380 // is ActivityManagerServiceDumpActivitiesProto
6381 mStackSupervisor.writeToProto(proto,
6382 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6383 }
6384 }
6385
6386 @Override
6387 public void saveANRState(String reason) {
6388 synchronized (mGlobalLock) {
6389 final StringWriter sw = new StringWriter();
6390 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6391 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6392 if (reason != null) {
6393 pw.println(" Reason: " + reason);
6394 }
6395 pw.println();
6396 getActivityStartController().dump(pw, " ", null);
6397 pw.println();
6398 pw.println("-------------------------------------------------------------------------------");
6399 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6400 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6401 "" /* header */);
6402 pw.println();
6403 pw.close();
6404
6405 mLastANRState = sw.toString();
6406 }
6407 }
6408
6409 @Override
6410 public void clearSavedANRState() {
6411 synchronized (mGlobalLock) {
6412 mLastANRState = null;
6413 }
6414 }
6415
6416 @Override
6417 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6418 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6419 synchronized (mGlobalLock) {
6420 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6421 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6422 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6423 dumpLastANRLocked(pw);
6424 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6425 dumpLastANRTracesLocked(pw);
6426 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6427 dumpActivityStarterLocked(pw, dumpPackage);
6428 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6429 dumpActivityContainersLocked(pw);
6430 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6431 if (getRecentTasks() != null) {
6432 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6433 }
6434 }
6435 }
6436 }
6437
6438 @Override
6439 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6440 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6441 int wakefulness) {
6442 synchronized (mGlobalLock) {
6443 if (mHomeProcess != null && (dumpPackage == null
6444 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6445 if (needSep) {
6446 pw.println();
6447 needSep = false;
6448 }
6449 pw.println(" mHomeProcess: " + mHomeProcess);
6450 }
6451 if (mPreviousProcess != null && (dumpPackage == null
6452 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6453 if (needSep) {
6454 pw.println();
6455 needSep = false;
6456 }
6457 pw.println(" mPreviousProcess: " + mPreviousProcess);
6458 }
6459 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6460 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6461 StringBuilder sb = new StringBuilder(128);
6462 sb.append(" mPreviousProcessVisibleTime: ");
6463 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6464 pw.println(sb);
6465 }
6466 if (mHeavyWeightProcess != null && (dumpPackage == null
6467 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6468 if (needSep) {
6469 pw.println();
6470 needSep = false;
6471 }
6472 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6473 }
6474 if (dumpPackage == null) {
6475 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6476 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6477 }
6478 if (dumpAll) {
6479 if (dumpPackage == null) {
6480 pw.println(" mConfigWillChange: "
6481 + getTopDisplayFocusedStack().mConfigWillChange);
6482 }
6483 if (mCompatModePackages.getPackages().size() > 0) {
6484 boolean printed = false;
6485 for (Map.Entry<String, Integer> entry
6486 : mCompatModePackages.getPackages().entrySet()) {
6487 String pkg = entry.getKey();
6488 int mode = entry.getValue();
6489 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6490 continue;
6491 }
6492 if (!printed) {
6493 pw.println(" mScreenCompatPackages:");
6494 printed = true;
6495 }
6496 pw.println(" " + pkg + ": " + mode);
6497 }
6498 }
6499 }
6500
6501 if (dumpPackage == null) {
6502 pw.println(" mWakefulness="
6503 + PowerManagerInternal.wakefulnessToString(wakefulness));
6504 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6505 if (mRunningVoice != null) {
6506 pw.println(" mRunningVoice=" + mRunningVoice);
6507 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6508 }
6509 pw.println(" mSleeping=" + mSleeping);
6510 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6511 pw.println(" mVrController=" + mVrController);
6512 }
6513 if (mCurAppTimeTracker != null) {
6514 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6515 }
6516 if (mAllowAppSwitchUids.size() > 0) {
6517 boolean printed = false;
6518 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6519 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6520 for (int j = 0; j < types.size(); j++) {
6521 if (dumpPackage == null ||
6522 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6523 if (needSep) {
6524 pw.println();
6525 needSep = false;
6526 }
6527 if (!printed) {
6528 pw.println(" mAllowAppSwitchUids:");
6529 printed = true;
6530 }
6531 pw.print(" User ");
6532 pw.print(mAllowAppSwitchUids.keyAt(i));
6533 pw.print(": Type ");
6534 pw.print(types.keyAt(j));
6535 pw.print(" = ");
6536 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6537 pw.println();
6538 }
6539 }
6540 }
6541 }
6542 if (dumpPackage == null) {
6543 if (mController != null) {
6544 pw.println(" mController=" + mController
6545 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6546 }
6547 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6548 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6549 }
6550
6551 return needSep;
6552 }
6553 }
6554
6555 @Override
6556 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6557 synchronized (mGlobalLock) {
6558 if (dumpPackage == null) {
6559 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6560 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6561 writeSleepStateToProto(proto);
6562 if (mController != null) {
6563 final long token = proto.start(CONTROLLER);
6564 proto.write(CONTROLLER, mController.toString());
6565 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6566 proto.end(token);
6567 }
6568 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6569 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6570 }
6571
6572 if (mHomeProcess != null && (dumpPackage == null
6573 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006574 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006575 }
6576
6577 if (mPreviousProcess != null && (dumpPackage == null
6578 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006579 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006580 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6581 }
6582
6583 if (mHeavyWeightProcess != null && (dumpPackage == null
6584 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006585 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006586 }
6587
6588 for (Map.Entry<String, Integer> entry
6589 : mCompatModePackages.getPackages().entrySet()) {
6590 String pkg = entry.getKey();
6591 int mode = entry.getValue();
6592 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6593 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6594 proto.write(PACKAGE, pkg);
6595 proto.write(MODE, mode);
6596 proto.end(compatToken);
6597 }
6598 }
6599
6600 if (mCurAppTimeTracker != null) {
6601 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6602 }
6603
6604 }
6605 }
6606
6607 @Override
6608 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6609 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6610 boolean dumpFocusedStackOnly) {
6611 synchronized (mGlobalLock) {
6612 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6613 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6614 }
6615 }
6616
6617 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006618 public void dumpForOom(PrintWriter pw) {
6619 synchronized (mGlobalLock) {
6620 pw.println(" mHomeProcess: " + mHomeProcess);
6621 pw.println(" mPreviousProcess: " + mPreviousProcess);
6622 if (mHeavyWeightProcess != null) {
6623 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6624 }
6625 }
6626 }
6627
6628 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006629 public boolean canGcNow() {
6630 synchronized (mGlobalLock) {
6631 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6632 }
6633 }
6634
6635 @Override
6636 public WindowProcessController getTopApp() {
6637 synchronized (mGlobalLock) {
6638 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6639 return top != null ? top.app : null;
6640 }
6641 }
6642
6643 @Override
6644 public void rankTaskLayersIfNeeded() {
6645 synchronized (mGlobalLock) {
6646 if (mStackSupervisor != null) {
6647 mStackSupervisor.rankTaskLayersIfNeeded();
6648 }
6649 }
6650 }
6651
6652 @Override
6653 public void scheduleDestroyAllActivities(String reason) {
6654 synchronized (mGlobalLock) {
6655 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6656 }
6657 }
6658
6659 @Override
6660 public void removeUser(int userId) {
6661 synchronized (mGlobalLock) {
6662 mStackSupervisor.removeUserLocked(userId);
6663 }
6664 }
6665
6666 @Override
6667 public boolean switchUser(int userId, UserState userState) {
6668 synchronized (mGlobalLock) {
6669 return mStackSupervisor.switchUserLocked(userId, userState);
6670 }
6671 }
6672
6673 @Override
6674 public void onHandleAppCrash(WindowProcessController wpc) {
6675 synchronized (mGlobalLock) {
6676 mStackSupervisor.handleAppCrashLocked(wpc);
6677 }
6678 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006679
6680 @Override
6681 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6682 synchronized (mGlobalLock) {
6683 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6684 }
6685 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006686
6687 @Override
6688 public void onUidActive(int uid, int procState) {
6689 synchronized (mGlobalLock) {
6690 mActiveUids.put(uid, procState);
6691 }
6692 }
6693
6694 @Override
6695 public void onUidInactive(int uid) {
6696 synchronized (mGlobalLock) {
6697 mActiveUids.remove(uid);
6698 }
6699 }
6700
6701 @Override
6702 public void onActiveUidsCleared() {
6703 synchronized (mGlobalLock) {
6704 mActiveUids.clear();
6705 }
6706 }
6707
6708 @Override
6709 public void onUidProcStateChanged(int uid, int procState) {
6710 synchronized (mGlobalLock) {
6711 if (mActiveUids.get(uid) != null) {
6712 mActiveUids.put(uid, procState);
6713 }
6714 }
6715 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006716
6717 @Override
6718 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6719 synchronized (mGlobalLock) {
6720 mPendingTempWhitelist.put(uid, tag);
6721 }
6722 }
6723
6724 @Override
6725 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6726 synchronized (mGlobalLock) {
6727 mPendingTempWhitelist.remove(uid);
6728 }
6729 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006730
6731 @Override
6732 public boolean handleAppCrashInActivityController(String processName, int pid,
6733 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6734 Runnable killCrashingAppCallback) {
6735 synchronized (mGlobalLock) {
6736 if (mController == null) {
6737 return false;
6738 }
6739
6740 try {
6741 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6742 stackTrace)) {
6743 killCrashingAppCallback.run();
6744 return true;
6745 }
6746 } catch (RemoteException e) {
6747 mController = null;
6748 Watchdog.getInstance().setActivityController(null);
6749 }
6750 return false;
6751 }
6752 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006753
6754 @Override
6755 public void removeRecentTasksByPackageName(String packageName, int userId) {
6756 synchronized (mGlobalLock) {
6757 mRecentTasks.removeTasksByPackageName(packageName, userId);
6758 }
6759 }
6760
6761 @Override
6762 public void cleanupRecentTasksForUser(int userId) {
6763 synchronized (mGlobalLock) {
6764 mRecentTasks.cleanupLocked(userId);
6765 }
6766 }
6767
6768 @Override
6769 public void loadRecentTasksForUser(int userId) {
6770 synchronized (mGlobalLock) {
6771 mRecentTasks.loadUserRecentsLocked(userId);
6772 }
6773 }
6774
6775 @Override
6776 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6777 synchronized (mGlobalLock) {
6778 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6779 }
6780 }
6781
6782 @Override
6783 public void flushRecentTasks() {
6784 mRecentTasks.flush();
6785 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006786
6787 @Override
6788 public WindowProcessController getHomeProcess() {
6789 synchronized (mGlobalLock) {
6790 return mHomeProcess;
6791 }
6792 }
6793
6794 @Override
6795 public WindowProcessController getPreviousProcess() {
6796 synchronized (mGlobalLock) {
6797 return mPreviousProcess;
6798 }
6799 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006800
6801 @Override
6802 public void clearLockedTasks(String reason) {
6803 synchronized (mGlobalLock) {
6804 getLockTaskController().clearLockedTasks(reason);
6805 }
6806 }
6807
6808 @Override
6809 public void updateUserConfiguration() {
6810 synchronized (mGlobalLock) {
6811 final Configuration configuration = new Configuration(getGlobalConfiguration());
6812 final int currentUserId = mAmInternal.getCurrentUserId();
6813 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6814 configuration, currentUserId, Settings.System.canWrite(mContext));
6815 updateConfigurationLocked(configuration, null /* starting */,
6816 false /* initLocale */, false /* persistent */, currentUserId,
6817 false /* deferResume */);
6818 }
6819 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006820
6821 @Override
6822 public boolean canShowErrorDialogs() {
6823 synchronized (mGlobalLock) {
6824 return mShowDialogs && !mSleeping && !mShuttingDown
6825 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6826 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6827 mAmInternal.getCurrentUserId())
6828 && !(UserManager.isDeviceInDemoMode(mContext)
6829 && mAmInternal.getCurrentUser().isDemo());
6830 }
6831 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006832
6833 @Override
6834 public void setProfileApp(String profileApp) {
6835 synchronized (mGlobalLock) {
6836 mProfileApp = profileApp;
6837 }
6838 }
6839
6840 @Override
6841 public void setProfileProc(WindowProcessController wpc) {
6842 synchronized (mGlobalLock) {
6843 mProfileProc = wpc;
6844 }
6845 }
6846
6847 @Override
6848 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6849 synchronized (mGlobalLock) {
6850 mProfilerInfo = profilerInfo;
6851 }
6852 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006853 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04006854}