blob: 86c5d4d1726dd5d01b423a1f808bd042602c5f27 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Wale Ogunwale59507092018-10-29 09:00:30 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
86 .PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
89 .MODE;
90import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
91 .PACKAGE;
92import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
93import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070094import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
95import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
96import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
116import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
117import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800119import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
120import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700121import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
122import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800123import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
124import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800125import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
126import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
127import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.annotation.Nullable;
132import android.annotation.UserIdInt;
133import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700134import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700135import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.ActivityOptions;
137import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700138import android.app.ActivityThread;
139import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700141import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700142import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700143import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.IApplicationThread;
145import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800193import android.os.Looper;
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 Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700277import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700279import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700280import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400282import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700285import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Map;
287import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288
289/**
290 * System service for managing activities and their containers (task, stacks, displays,... ).
291 *
292 * {@hide}
293 */
294public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700295 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700297 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
298 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
299 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
300 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
301 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700302 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700307 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 /** Used to indicate that an app transition should be animated. */
310 static final boolean ANIMATE = true;
311
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700312 /** Hardware-reported OpenGLES version. */
313 final int GL_ES_VERSION;
314
Wale Ogunwale31913b52018-10-13 08:29:31 -0700315 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
316 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
317 public static final String DUMP_LASTANR_CMD = "lastanr" ;
318 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
319 public static final String DUMP_STARTER_CMD = "starter" ;
320 public static final String DUMP_CONTAINERS_CMD = "containers" ;
321 public static final String DUMP_RECENTS_CMD = "recents" ;
322 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
323
Wale Ogunwale64258362018-10-16 15:13:37 -0700324 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
325 public static final int RELAUNCH_REASON_NONE = 0;
326 /** This activity is being relaunched due to windowing mode change. */
327 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
328 /** This activity is being relaunched due to a free-resize operation. */
329 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
330
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700331 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700332
Wale Ogunwalef6733932018-06-27 05:14:34 -0700333 /**
334 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
335 * change at runtime. Use mContext for non-UI purposes.
336 */
337 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700338 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700339 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700342 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700343 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800344 @VisibleForTesting
345 final 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 Ogunwaled32da472018-11-16 07:19:28 -0800355 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700356 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700357 private UserManagerService mUserManager;
358 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700359 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700360 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
361 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700362 /** All processes currently running that might have a window organized by name. */
363 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700364 /** All processes we currently have running mapped by pid */
365 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700366 /** This is the process holding what we currently consider to be the "home" activity. */
367 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700368 /** The currently running heavy-weight process, if any. */
369 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700370 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700371 /**
372 * This is the process holding the activity the user last visited that is in a different process
373 * from the one they are currently in.
374 */
375 WindowProcessController mPreviousProcess;
376 /** The time at which the previous process was last visible. */
377 long mPreviousProcessVisibleTime;
378
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700379 /** List of intents that were used to start the most recent tasks. */
380 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700381 /** State of external calls telling us if the device is awake or asleep. */
382 private boolean mKeyguardShown = false;
383
384 // Wrapper around VoiceInteractionServiceManager
385 private AssistUtils mAssistUtils;
386
387 // VoiceInteraction session ID that changes for each new request except when
388 // being called for multi-window assist in a single session.
389 private int mViSessionId = 1000;
390
391 // How long to wait in getAssistContextExtras for the activity and foreground services
392 // to respond with the result.
393 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
394
395 // How long top wait when going through the modern assist (which doesn't need to block
396 // on getting this result before starting to launch its UI).
397 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
398
399 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
400 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
401
Alison Cichowlas3e340502018-08-07 17:15:01 -0400402 // Permission tokens are used to temporarily granted a trusted app the ability to call
403 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
404 // showing any appropriate error messages to the user.
405 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
406 10 * MINUTE_IN_MILLIS;
407
408 // How long before the service actually expires a token. This is slightly longer than
409 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
410 // expiration exception.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
412 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
413
414 // How long the service will remember expired tokens, for the purpose of providing error
415 // messaging when a client uses an expired token.
416 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
417 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
418
419 // Activity tokens of system activities that are delegating their call to
420 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
421 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
422
423 // Permission tokens that have expired, but we remember for error reporting.
424 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700426 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
427
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700428 // Keeps track of the active voice interaction service component, notified from
429 // VoiceInteractionManagerService
430 ComponentName mActiveVoiceInteractionServiceComponent;
431
Wale Ogunwalee2172292018-10-25 10:11:10 -0700432 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700433 KeyguardController mKeyguardController;
434 private final ClientLifecycleManager mLifecycleManager;
435 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700436 /** The controller for all operations related to locktask. */
437 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700438 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700440 boolean mSuppressResizeConfigChanges;
441
442 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
443 new UpdateConfigurationResult();
444
445 static final class UpdateConfigurationResult {
446 // Configuration changes that were updated.
447 int changes;
448 // If the activity was relaunched to match the new configuration.
449 boolean activityRelaunched;
450
451 void reset() {
452 changes = 0;
453 activityRelaunched = false;
454 }
455 }
456
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700457 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700458 private int mConfigurationSeq;
459 // To cache the list of supported system locales
460 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700461
462 /**
463 * Temp object used when global and/or display override configuration is updated. It is also
464 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
465 * anyone...
466 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700467 private Configuration mTempConfig = new Configuration();
468
Wale Ogunwalef6733932018-06-27 05:14:34 -0700469 /** Temporary to avoid allocations. */
470 final StringBuilder mStringBuilder = new StringBuilder(256);
471
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700472 // Amount of time after a call to stopAppSwitches() during which we will
473 // prevent further untrusted switches from happening.
474 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
475
476 /**
477 * The time at which we will allow normal application switches again,
478 * after a call to {@link #stopAppSwitches()}.
479 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700480 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 /**
482 * This is set to true after the first switch after mAppSwitchesAllowedTime
483 * is set; any switches after that will clear the time.
484 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700485 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486
487 IActivityController mController = null;
488 boolean mControllerIsAMonkey = false;
489
Wale Ogunwale214f3482018-10-04 11:00:47 -0700490 final int mFactoryTest;
491
492 /** Used to control how we initialize the service. */
493 ComponentName mTopComponent;
494 String mTopAction = Intent.ACTION_MAIN;
495 String mTopData;
496
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800497 /** Profiling app information. */
498 String mProfileApp = null;
499 WindowProcessController mProfileProc = null;
500 ProfilerInfo mProfilerInfo = null;
501
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700503 * Dump of the activity state at the time of the last ANR. Cleared after
504 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
505 */
506 String mLastANRState;
507
508 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509 * Used to retain an update lock when the foreground activity is in
510 * immersive mode.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
514 /**
515 * Packages that are being allowed to perform unrestricted app switches. Mapping is
516 * User -> Type -> uid.
517 */
518 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
519
520 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700521 private int mThumbnailWidth;
522 private int mThumbnailHeight;
523 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700524
525 /**
526 * Flag that indicates if multi-window is enabled.
527 *
528 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
529 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
530 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
531 * At least one of the forms of multi-window must be enabled in order for this flag to be
532 * initialized to 'true'.
533 *
534 * @see #mSupportsSplitScreenMultiWindow
535 * @see #mSupportsFreeformWindowManagement
536 * @see #mSupportsPictureInPicture
537 * @see #mSupportsMultiDisplay
538 */
539 boolean mSupportsMultiWindow;
540 boolean mSupportsSplitScreenMultiWindow;
541 boolean mSupportsFreeformWindowManagement;
542 boolean mSupportsPictureInPicture;
543 boolean mSupportsMultiDisplay;
544 boolean mForceResizableActivities;
545
546 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
547
548 // VR Vr2d Display Id.
549 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700550
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 /**
552 * Set while we are wanting to sleep, to prevent any
553 * activities from being started/resumed.
554 *
555 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
556 *
557 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
558 * while in the sleep state until there is a pending transition out of sleep, in which case
559 * mSleeping is set to false, and remains false while awake.
560 *
561 * Whether mSleeping can quickly toggled between true/false without the device actually
562 * display changing states is undefined.
563 */
564 private boolean mSleeping = false;
565
566 /**
567 * The process state used for processes that are running the top activities.
568 * This changes between TOP and TOP_SLEEPING to following mSleeping.
569 */
570 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
571
572 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
573 // automatically. Important for devices without direct input devices.
574 private boolean mShowDialogs = true;
575
576 /** Set if we are shutting down the system, similar to sleeping. */
577 boolean mShuttingDown = false;
578
579 /**
580 * We want to hold a wake lock while running a voice interaction session, since
581 * this may happen with the screen off and we need to keep the CPU running to
582 * be able to continue to interact with the user.
583 */
584 PowerManager.WakeLock mVoiceWakeLock;
585
586 /**
587 * Set while we are running a voice interaction. This overrides sleeping while it is active.
588 */
589 IVoiceInteractionSession mRunningVoice;
590
591 /**
592 * The last resumed activity. This is identical to the current resumed activity most
593 * of the time but could be different when we're pausing one activity before we resume
594 * another activity.
595 */
596 ActivityRecord mLastResumedActivity;
597
598 /**
599 * The activity that is currently being traced as the active resumed activity.
600 *
601 * @see #updateResumedAppTrace
602 */
603 private @Nullable ActivityRecord mTracedResumedActivity;
604
605 /** If non-null, we are tracking the time the user spends in the currently focused app. */
606 AppTimeTracker mCurAppTimeTracker;
607
Wale Ogunwale008163e2018-07-23 23:11:08 -0700608 private AppWarnings mAppWarnings;
609
Wale Ogunwale53783742018-09-16 10:21:51 -0700610 /**
611 * Packages that the user has asked to have run in screen size
612 * compatibility mode instead of filling the screen.
613 */
614 CompatModePackages mCompatModePackages;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 private FontScaleSettingObserver mFontScaleSettingObserver;
617
618 private final class FontScaleSettingObserver extends ContentObserver {
619 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
620 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
621
622 public FontScaleSettingObserver() {
623 super(mH);
624 final ContentResolver resolver = mContext.getContentResolver();
625 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
626 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
627 UserHandle.USER_ALL);
628 }
629
630 @Override
631 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
632 if (mFontScaleUri.equals(uri)) {
633 updateFontScaleIfNeeded(userId);
634 } else if (mHideErrorDialogsUri.equals(uri)) {
635 synchronized (mGlobalLock) {
636 updateShouldShowDialogsLocked(getGlobalConfiguration());
637 }
638 }
639 }
640 }
641
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700642 ActivityTaskManagerService(Context context) {
643 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700644 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700645 mSystemThread = ActivityThread.currentActivityThread();
646 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700647 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800648 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700649 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700650 }
651
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700652 public void onSystemReady() {
653 synchronized (mGlobalLock) {
654 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
655 PackageManager.FEATURE_CANT_SAVE_STATE);
656 mAssistUtils = new AssistUtils(mContext);
657 mVrController.onSystemReady();
658 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700659 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700660 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700661 }
662
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700663 public void onInitPowerManagement() {
664 synchronized (mGlobalLock) {
665 mStackSupervisor.initPowerManagement();
666 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
667 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
668 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
669 mVoiceWakeLock.setReferenceCounted(false);
670 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 }
672
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700673 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700674 mFontScaleSettingObserver = new FontScaleSettingObserver();
675 }
676
Wale Ogunwale59507092018-10-29 09:00:30 -0700677 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700678 final boolean freeformWindowManagement =
679 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
680 || Settings.Global.getInt(
681 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
682
683 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
684 final boolean supportsPictureInPicture = supportsMultiWindow &&
685 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
686 final boolean supportsSplitScreenMultiWindow =
687 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
688 final boolean supportsMultiDisplay = mContext.getPackageManager()
689 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700690 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
691 final boolean forceResizable = Settings.Global.getInt(
692 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700693 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700694
695 // Transfer any global setting for forcing RTL layout, into a System Property
696 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
697
698 final Configuration configuration = new Configuration();
699 Settings.System.getConfiguration(resolver, configuration);
700 if (forceRtl) {
701 // This will take care of setting the correct layout direction flags
702 configuration.setLayoutDirection(configuration.locale);
703 }
704
705 synchronized (mGlobalLock) {
706 mForceResizableActivities = forceResizable;
707 final boolean multiWindowFormEnabled = freeformWindowManagement
708 || supportsSplitScreenMultiWindow
709 || supportsPictureInPicture
710 || supportsMultiDisplay;
711 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
712 mSupportsMultiWindow = true;
713 mSupportsFreeformWindowManagement = freeformWindowManagement;
714 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
715 mSupportsPictureInPicture = supportsPictureInPicture;
716 mSupportsMultiDisplay = supportsMultiDisplay;
717 } else {
718 mSupportsMultiWindow = false;
719 mSupportsFreeformWindowManagement = false;
720 mSupportsSplitScreenMultiWindow = false;
721 mSupportsPictureInPicture = false;
722 mSupportsMultiDisplay = false;
723 }
724 mWindowManager.setForceResizableTasks(mForceResizableActivities);
725 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700726 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
727 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728 // This happens before any activities are started, so we can change global configuration
729 // in-place.
730 updateConfigurationLocked(configuration, null, true);
731 final Configuration globalConfig = getGlobalConfiguration();
732 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
733
734 // Load resources only after the current configuration has been set.
735 final Resources res = mContext.getResources();
736 mThumbnailWidth = res.getDimensionPixelSize(
737 com.android.internal.R.dimen.thumbnail_width);
738 mThumbnailHeight = res.getDimensionPixelSize(
739 com.android.internal.R.dimen.thumbnail_height);
740
741 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
742 mFullscreenThumbnailScale = (float) res
743 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
744 (float) globalConfig.screenWidthDp;
745 } else {
746 mFullscreenThumbnailScale = res.getFraction(
747 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
748 }
749 }
750 }
751
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800752 public WindowManagerGlobalLock getGlobalLock() {
753 return mGlobalLock;
754 }
755
Riddle Hsud93a6c42018-11-29 21:50:06 +0800756 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
757 Looper looper) {
758 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700759 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700760 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700761 final File systemDir = SystemServiceManager.ensureSystemDir();
762 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
763 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700764 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700765
766 mTempConfig.setToDefaults();
767 mTempConfig.setLocales(LocaleList.getDefault());
768 mConfigurationSeq = mTempConfig.seq = 1;
769 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800770 mRootActivityContainer = new RootActivityContainer(this);
771 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700772
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700773 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700775 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700776 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700777 mRecentTasks = createRecentTasks();
778 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700780 mKeyguardController = mStackSupervisor.getKeyguardController();
781 }
782
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700783 public void onActivityManagerInternalAdded() {
784 synchronized (mGlobalLock) {
785 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
786 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
787 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700788 }
789
Yunfan Chen75157d72018-07-27 14:47:21 +0900790 int increaseConfigurationSeqLocked() {
791 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
792 return mConfigurationSeq;
793 }
794
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700795 protected ActivityStackSupervisor createStackSupervisor() {
796 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
797 supervisor.initialize();
798 return supervisor;
799 }
800
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700801 public void setWindowManager(WindowManagerService wm) {
802 synchronized (mGlobalLock) {
803 mWindowManager = wm;
804 mLockTaskController.setWindowManager(wm);
805 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800806 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700807 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
811 synchronized (mGlobalLock) {
812 mUsageStatsInternal = usageStatsManager;
813 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700814 }
815
Wale Ogunwalef6733932018-06-27 05:14:34 -0700816 UserManagerService getUserManager() {
817 if (mUserManager == null) {
818 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
819 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
820 }
821 return mUserManager;
822 }
823
824 AppOpsService getAppOpsService() {
825 if (mAppOpsService == null) {
826 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
827 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
828 }
829 return mAppOpsService;
830 }
831
832 boolean hasUserRestriction(String restriction, int userId) {
833 return getUserManager().hasUserRestriction(restriction, userId);
834 }
835
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700836 protected RecentTasks createRecentTasks() {
837 return new RecentTasks(this, mStackSupervisor);
838 }
839
840 RecentTasks getRecentTasks() {
841 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700842 }
843
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700844 ClientLifecycleManager getLifecycleManager() {
845 return mLifecycleManager;
846 }
847
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700848 ActivityStartController getActivityStartController() {
849 return mActivityStartController;
850 }
851
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700852 TaskChangeNotificationController getTaskChangeNotificationController() {
853 return mTaskChangeNotificationController;
854 }
855
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700856 LockTaskController getLockTaskController() {
857 return mLockTaskController;
858 }
859
Yunfan Chen75157d72018-07-27 14:47:21 +0900860 /**
861 * Return the global configuration used by the process corresponding to the input pid. This is
862 * usually the global configuration with some overrides specific to that process.
863 */
864 Configuration getGlobalConfigurationForCallingPid() {
865 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800866 return getGlobalConfigurationForPid(pid);
867 }
868
869 /**
870 * Return the global configuration used by the process corresponding to the given pid.
871 */
872 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900873 if (pid == MY_PID || pid < 0) {
874 return getGlobalConfiguration();
875 }
876 synchronized (mGlobalLock) {
877 final WindowProcessController app = mPidMap.get(pid);
878 return app != null ? app.getConfiguration() : getGlobalConfiguration();
879 }
880 }
881
882 /**
883 * Return the device configuration info used by the process corresponding to the input pid.
884 * The value is consistent with the global configuration for the process.
885 */
886 @Override
887 public ConfigurationInfo getDeviceConfigurationInfo() {
888 ConfigurationInfo config = new ConfigurationInfo();
889 synchronized (mGlobalLock) {
890 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
891 config.reqTouchScreen = globalConfig.touchscreen;
892 config.reqKeyboardType = globalConfig.keyboard;
893 config.reqNavigation = globalConfig.navigation;
894 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
895 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
896 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
897 }
898 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
899 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
900 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
901 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700902 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900903 }
904 return config;
905 }
906
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700907 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700908 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700909 }
910
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700911 public static final class Lifecycle extends SystemService {
912 private final ActivityTaskManagerService mService;
913
914 public Lifecycle(Context context) {
915 super(context);
916 mService = new ActivityTaskManagerService(context);
917 }
918
919 @Override
920 public void onStart() {
921 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700922 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700923 }
924
Garfield Tan891146c2018-10-09 12:14:00 -0700925 @Override
926 public void onUnlockUser(int userId) {
927 synchronized (mService.getGlobalLock()) {
928 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
929 }
930 }
931
932 @Override
933 public void onCleanupUser(int userId) {
934 synchronized (mService.getGlobalLock()) {
935 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
936 }
937 }
938
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700939 public ActivityTaskManagerService getService() {
940 return mService;
941 }
942 }
943
944 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700945 public final int startActivity(IApplicationThread caller, String callingPackage,
946 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
947 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
948 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
949 resultWho, requestCode, startFlags, profilerInfo, bOptions,
950 UserHandle.getCallingUserId());
951 }
952
953 @Override
954 public final int startActivities(IApplicationThread caller, String callingPackage,
955 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
956 int userId) {
957 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700958 enforceNotIsolatedCaller(reason);
959 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700960 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700961 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100962 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
963 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700964 }
965
966 @Override
967 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
968 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
969 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
970 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
971 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
972 true /*validateIncomingUser*/);
973 }
974
975 int startActivityAsUser(IApplicationThread caller, String callingPackage,
976 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
977 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
978 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700979 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700981 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700982 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
983
984 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700985 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 .setCaller(caller)
987 .setCallingPackage(callingPackage)
988 .setResolvedType(resolvedType)
989 .setResultTo(resultTo)
990 .setResultWho(resultWho)
991 .setRequestCode(requestCode)
992 .setStartFlags(startFlags)
993 .setProfilerInfo(profilerInfo)
994 .setActivityOptions(bOptions)
995 .setMayWait(userId)
996 .execute();
997
998 }
999
1000 @Override
1001 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1002 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001003 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1004 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001005 // Refuse possible leaked file descriptors
1006 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1007 throw new IllegalArgumentException("File descriptors passed in Intent");
1008 }
1009
1010 if (!(target instanceof PendingIntentRecord)) {
1011 throw new IllegalArgumentException("Bad PendingIntent object");
1012 }
1013
1014 PendingIntentRecord pir = (PendingIntentRecord)target;
1015
1016 synchronized (mGlobalLock) {
1017 // If this is coming from the currently resumed activity, it is
1018 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001019 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 if (stack.mResumedActivity != null &&
1021 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001022 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 }
1024 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001025 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1031 Bundle bOptions) {
1032 // Refuse possible leaked file descriptors
1033 if (intent != null && intent.hasFileDescriptors()) {
1034 throw new IllegalArgumentException("File descriptors passed in Intent");
1035 }
1036 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1037
1038 synchronized (mGlobalLock) {
1039 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1040 if (r == null) {
1041 SafeActivityOptions.abort(options);
1042 return false;
1043 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001044 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // The caller is not running... d'oh!
1046 SafeActivityOptions.abort(options);
1047 return false;
1048 }
1049 intent = new Intent(intent);
1050 // The caller is not allowed to change the data.
1051 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1052 // And we are resetting to find the next component...
1053 intent.setComponent(null);
1054
1055 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1056
1057 ActivityInfo aInfo = null;
1058 try {
1059 List<ResolveInfo> resolves =
1060 AppGlobals.getPackageManager().queryIntentActivities(
1061 intent, r.resolvedType,
1062 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1063 UserHandle.getCallingUserId()).getList();
1064
1065 // Look for the original activity in the list...
1066 final int N = resolves != null ? resolves.size() : 0;
1067 for (int i=0; i<N; i++) {
1068 ResolveInfo rInfo = resolves.get(i);
1069 if (rInfo.activityInfo.packageName.equals(r.packageName)
1070 && rInfo.activityInfo.name.equals(r.info.name)) {
1071 // We found the current one... the next matching is
1072 // after it.
1073 i++;
1074 if (i<N) {
1075 aInfo = resolves.get(i).activityInfo;
1076 }
1077 if (debug) {
1078 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1079 + "/" + r.info.name);
1080 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1081 ? "null" : aInfo.packageName + "/" + aInfo.name));
1082 }
1083 break;
1084 }
1085 }
1086 } catch (RemoteException e) {
1087 }
1088
1089 if (aInfo == null) {
1090 // Nobody who is next!
1091 SafeActivityOptions.abort(options);
1092 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1093 return false;
1094 }
1095
1096 intent.setComponent(new ComponentName(
1097 aInfo.applicationInfo.packageName, aInfo.name));
1098 intent.setFlags(intent.getFlags()&~(
1099 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1100 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1101 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1102 FLAG_ACTIVITY_NEW_TASK));
1103
1104 // Okay now we need to start the new activity, replacing the currently running activity.
1105 // This is a little tricky because we want to start the new one as if the current one is
1106 // finished, but not finish the current one first so that there is no flicker.
1107 // And thus...
1108 final boolean wasFinishing = r.finishing;
1109 r.finishing = true;
1110
1111 // Propagate reply information over to the new activity.
1112 final ActivityRecord resultTo = r.resultTo;
1113 final String resultWho = r.resultWho;
1114 final int requestCode = r.requestCode;
1115 r.resultTo = null;
1116 if (resultTo != null) {
1117 resultTo.removeResultsLocked(r, resultWho, requestCode);
1118 }
1119
1120 final long origId = Binder.clearCallingIdentity();
1121 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001122 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 .setResolvedType(r.resolvedType)
1126 .setActivityInfo(aInfo)
1127 .setResultTo(resultTo != null ? resultTo.appToken : null)
1128 .setResultWho(resultWho)
1129 .setRequestCode(requestCode)
1130 .setCallingPid(-1)
1131 .setCallingUid(r.launchedFromUid)
1132 .setCallingPackage(r.launchedFromPackage)
1133 .setRealCallingPid(-1)
1134 .setRealCallingUid(r.launchedFromUid)
1135 .setActivityOptions(options)
1136 .execute();
1137 Binder.restoreCallingIdentity(origId);
1138
1139 r.finishing = wasFinishing;
1140 if (res != ActivityManager.START_SUCCESS) {
1141 return false;
1142 }
1143 return true;
1144 }
1145 }
1146
1147 @Override
1148 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1149 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1150 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1151 final WaitResult res = new WaitResult();
1152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001153 enforceNotIsolatedCaller("startActivityAndWait");
1154 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1155 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001156 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001157 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001158 .setCaller(caller)
1159 .setCallingPackage(callingPackage)
1160 .setResolvedType(resolvedType)
1161 .setResultTo(resultTo)
1162 .setResultWho(resultWho)
1163 .setRequestCode(requestCode)
1164 .setStartFlags(startFlags)
1165 .setActivityOptions(bOptions)
1166 .setMayWait(userId)
1167 .setProfilerInfo(profilerInfo)
1168 .setWaitResult(res)
1169 .execute();
1170 }
1171 return res;
1172 }
1173
1174 @Override
1175 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1176 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1177 int startFlags, Configuration config, Bundle bOptions, int userId) {
1178 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001179 enforceNotIsolatedCaller("startActivityWithConfig");
1180 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1181 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001183 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001184 .setCaller(caller)
1185 .setCallingPackage(callingPackage)
1186 .setResolvedType(resolvedType)
1187 .setResultTo(resultTo)
1188 .setResultWho(resultWho)
1189 .setRequestCode(requestCode)
1190 .setStartFlags(startFlags)
1191 .setGlobalConfiguration(config)
1192 .setActivityOptions(bOptions)
1193 .setMayWait(userId)
1194 .execute();
1195 }
1196 }
1197
Alison Cichowlas3e340502018-08-07 17:15:01 -04001198
1199 @Override
1200 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1201 int callingUid = Binder.getCallingUid();
1202 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1203 throw new SecurityException("Only the system process can request a permission token, "
1204 + "received request from uid: " + callingUid);
1205 }
1206 IBinder permissionToken = new Binder();
1207 synchronized (mGlobalLock) {
1208 mStartActivitySources.put(permissionToken, delegatorToken);
1209 }
1210
1211 Message expireMsg = PooledLambda.obtainMessage(
1212 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1213 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1214
1215 Message forgetMsg = PooledLambda.obtainMessage(
1216 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1217 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1218
1219 return permissionToken;
1220 }
1221
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 @Override
1223 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1224 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001225 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1226 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001228 // permission grants) as any app that may launch one of your own activities. So we only
1229 // allow this in two cases:
1230 // 1) The caller is an activity that is part of the core framework, and then only when it
1231 // is running as the system.
1232 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1233 // can only be requested by a system activity, which may then delegate this call to
1234 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 final ActivityRecord sourceRecord;
1236 final int targetUid;
1237 final String targetPackage;
1238 final boolean isResolver;
1239 synchronized (mGlobalLock) {
1240 if (resultTo == null) {
1241 throw new SecurityException("Must be called from an activity");
1242 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001243 final IBinder sourceToken;
1244 if (permissionToken != null) {
1245 // To even attempt to use a permissionToken, an app must also have this signature
1246 // permission.
1247 mAmInternal.enforceCallingPermission(
1248 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1249 "startActivityAsCaller");
1250 // If called with a permissionToken, we want the sourceRecord from the delegator
1251 // activity that requested this token.
1252 sourceToken = mStartActivitySources.remove(permissionToken);
1253 if (sourceToken == null) {
1254 // Invalid permissionToken, check if it recently expired.
1255 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1256 throw new SecurityException("Called with expired permission token: "
1257 + permissionToken);
1258 } else {
1259 throw new SecurityException("Called with invalid permission token: "
1260 + permissionToken);
1261 }
1262 }
1263 } else {
1264 // This method was called directly by the source.
1265 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267
Wale Ogunwaled32da472018-11-16 07:19:28 -08001268 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269 if (sourceRecord == null) {
1270 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 }
1272 if (sourceRecord.app == null) {
1273 throw new SecurityException("Called without a process attached to activity");
1274 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001275
1276 // Whether called directly or from a delegate, the source activity must be from the
1277 // android package.
1278 if (!sourceRecord.info.packageName.equals("android")) {
1279 throw new SecurityException("Must be called from an activity that is "
1280 + "declared in the android package");
1281 }
1282
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001283 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 // This is still okay, as long as this activity is running under the
1285 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001286 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001288 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 + " must be system uid or original calling uid "
1290 + sourceRecord.launchedFromUid);
1291 }
1292 }
1293 if (ignoreTargetSecurity) {
1294 if (intent.getComponent() == null) {
1295 throw new SecurityException(
1296 "Component must be specified with ignoreTargetSecurity");
1297 }
1298 if (intent.getSelector() != null) {
1299 throw new SecurityException(
1300 "Selector not allowed with ignoreTargetSecurity");
1301 }
1302 }
1303 targetUid = sourceRecord.launchedFromUid;
1304 targetPackage = sourceRecord.launchedFromPackage;
1305 isResolver = sourceRecord.isResolverOrChildActivity();
1306 }
1307
1308 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001309 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 }
1311
1312 // TODO: Switch to user app stacks here.
1313 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001314 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001315 .setCallingUid(targetUid)
1316 .setCallingPackage(targetPackage)
1317 .setResolvedType(resolvedType)
1318 .setResultTo(resultTo)
1319 .setResultWho(resultWho)
1320 .setRequestCode(requestCode)
1321 .setStartFlags(startFlags)
1322 .setActivityOptions(bOptions)
1323 .setMayWait(userId)
1324 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1325 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1326 .execute();
1327 } catch (SecurityException e) {
1328 // XXX need to figure out how to propagate to original app.
1329 // A SecurityException here is generally actually a fault of the original
1330 // calling activity (such as a fairly granting permissions), so propagate it
1331 // back to them.
1332 /*
1333 StringBuilder msg = new StringBuilder();
1334 msg.append("While launching");
1335 msg.append(intent.toString());
1336 msg.append(": ");
1337 msg.append(e.getMessage());
1338 */
1339 throw e;
1340 }
1341 }
1342
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001343 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1344 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1345 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1346 }
1347
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 @Override
1349 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1350 Intent intent, String resolvedType, IVoiceInteractionSession session,
1351 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1352 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 if (session == null || interactor == null) {
1355 throw new NullPointerException("null session or interactor");
1356 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001357 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001359 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 .setCallingUid(callingUid)
1361 .setCallingPackage(callingPackage)
1362 .setResolvedType(resolvedType)
1363 .setVoiceSession(session)
1364 .setVoiceInteractor(interactor)
1365 .setStartFlags(startFlags)
1366 .setProfilerInfo(profilerInfo)
1367 .setActivityOptions(bOptions)
1368 .setMayWait(userId)
1369 .execute();
1370 }
1371
1372 @Override
1373 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1374 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001375 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1376 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(callingUid)
1380 .setCallingPackage(callingPackage)
1381 .setResolvedType(resolvedType)
1382 .setActivityOptions(bOptions)
1383 .setMayWait(userId)
1384 .execute();
1385 }
1386
1387 @Override
1388 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1389 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001390 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 final int callingPid = Binder.getCallingPid();
1392 final long origId = Binder.clearCallingIdentity();
1393 try {
1394 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001395 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1396 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397
1398 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1400 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1402 recentsUid, assistDataReceiver);
1403 }
1404 } finally {
1405 Binder.restoreCallingIdentity(origId);
1406 }
1407 }
1408
1409 @Override
1410 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 "startActivityFromRecents()");
1413
1414 final int callingPid = Binder.getCallingPid();
1415 final int callingUid = Binder.getCallingUid();
1416 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1417 final long origId = Binder.clearCallingIdentity();
1418 try {
1419 synchronized (mGlobalLock) {
1420 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1421 safeOptions);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(origId);
1425 }
1426 }
1427
1428 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001429 * Public API to check if the client is allowed to start an activity on specified display.
1430 *
1431 * If the target display is private or virtual, some restrictions will apply.
1432 *
1433 * @param displayId Target display id.
1434 * @param intent Intent used to launch the activity.
1435 * @param resolvedType The MIME type of the intent.
1436 * @param userId The id of the user for whom the call is made.
1437 * @return {@code true} if a call to start an activity on the target display should succeed and
1438 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1439 */
1440 @Override
1441 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1442 String resolvedType, int userId) {
1443 final int callingUid = Binder.getCallingUid();
1444 final int callingPid = Binder.getCallingPid();
1445 final long origId = Binder.clearCallingIdentity();
1446
1447 try {
1448 // Collect information about the target of the Intent.
1449 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1450 0 /* startFlags */, null /* profilerInfo */, userId,
1451 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1452 UserHandle.USER_NULL));
1453 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1454
1455 synchronized (mGlobalLock) {
1456 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1457 aInfo);
1458 }
1459 } finally {
1460 Binder.restoreCallingIdentity(origId);
1461 }
1462 }
1463
1464 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 * This is the internal entry point for handling Activity.finish().
1466 *
1467 * @param token The Binder token referencing the Activity we want to finish.
1468 * @param resultCode Result code, if any, from this Activity.
1469 * @param resultData Result data (Intent), if any, from this Activity.
1470 * @param finishTask Whether to finish the task associated with this Activity.
1471 *
1472 * @return Returns true if the activity successfully finished, or false if it is still running.
1473 */
1474 @Override
1475 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1476 int finishTask) {
1477 // Refuse possible leaked file descriptors
1478 if (resultData != null && resultData.hasFileDescriptors()) {
1479 throw new IllegalArgumentException("File descriptors passed in Intent");
1480 }
1481
1482 synchronized (mGlobalLock) {
1483 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1484 if (r == null) {
1485 return true;
1486 }
1487 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001488 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 ActivityRecord rootR = tr.getRootActivity();
1490 if (rootR == null) {
1491 Slog.w(TAG, "Finishing task with all activities already finished");
1492 }
1493 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1494 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001495 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 return false;
1497 }
1498
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1500 // We should consolidate.
1501 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001503 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 if (next != null) {
1505 // ask watcher if this is allowed
1506 boolean resumeOK = true;
1507 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 Watchdog.getInstance().setActivityController(null);
1512 }
1513
1514 if (!resumeOK) {
1515 Slog.i(TAG, "Not finishing activity because controller resumed");
1516 return false;
1517 }
1518 }
1519 }
1520 final long origId = Binder.clearCallingIdentity();
1521 try {
1522 boolean res;
1523 final boolean finishWithRootActivity =
1524 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1525 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1526 || (finishWithRootActivity && r == rootR)) {
1527 // If requested, remove the task that is associated to this activity only if it
1528 // was the root activity in the task. The result code and data is ignored
1529 // because we don't support returning them across task boundaries. Also, to
1530 // keep backwards compatibility we remove the task from recents when finishing
1531 // task with root activity.
1532 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1533 finishWithRootActivity, "finish-activity");
1534 if (!res) {
1535 Slog.i(TAG, "Removing task failed to finish activity");
1536 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001537 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001538 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 } else {
1540 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1541 resultData, "app-request", true);
1542 if (!res) {
1543 Slog.i(TAG, "Failed to finish by app-request");
1544 }
1545 }
1546 return res;
1547 } finally {
1548 Binder.restoreCallingIdentity(origId);
1549 }
1550 }
1551 }
1552
1553 @Override
1554 public boolean finishActivityAffinity(IBinder token) {
1555 synchronized (mGlobalLock) {
1556 final long origId = Binder.clearCallingIdentity();
1557 try {
1558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1559 if (r == null) {
1560 return false;
1561 }
1562
1563 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1564 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001565 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001566 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 return false;
1568 }
1569 return task.getStack().finishActivityAffinityLocked(r);
1570 } finally {
1571 Binder.restoreCallingIdentity(origId);
1572 }
1573 }
1574 }
1575
1576 @Override
1577 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1578 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001579 try {
1580 WindowProcessController proc = null;
1581 synchronized (mGlobalLock) {
1582 ActivityStack stack = ActivityRecord.getStackLocked(token);
1583 if (stack == null) {
1584 return;
1585 }
1586 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1587 false /* fromTimeout */, false /* processPausingActivities */, config);
1588 if (r != null) {
1589 proc = r.app;
1590 }
1591 if (stopProfiling && proc != null) {
1592 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 }
1594 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001595 } finally {
1596 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 }
1599
1600 @Override
1601 public final void activityResumed(IBinder token) {
1602 final long origId = Binder.clearCallingIdentity();
1603 synchronized (mGlobalLock) {
1604 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001605 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 }
1607 Binder.restoreCallingIdentity(origId);
1608 }
1609
1610 @Override
1611 public final void activityPaused(IBinder token) {
1612 final long origId = Binder.clearCallingIdentity();
1613 synchronized (mGlobalLock) {
1614 ActivityStack stack = ActivityRecord.getStackLocked(token);
1615 if (stack != null) {
1616 stack.activityPausedLocked(token, false);
1617 }
1618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityStopped(IBinder token, Bundle icicle,
1624 PersistableBundle persistentState, CharSequence description) {
1625 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1626
1627 // Refuse possible leaked file descriptors
1628 if (icicle != null && icicle.hasFileDescriptors()) {
1629 throw new IllegalArgumentException("File descriptors passed in Bundle");
1630 }
1631
1632 final long origId = Binder.clearCallingIdentity();
1633
1634 synchronized (mGlobalLock) {
1635 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1636 if (r != null) {
1637 r.activityStoppedLocked(icicle, persistentState, description);
1638 }
1639 }
1640
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001641 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642
1643 Binder.restoreCallingIdentity(origId);
1644 }
1645
1646 @Override
1647 public final void activityDestroyed(IBinder token) {
1648 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1649 synchronized (mGlobalLock) {
1650 ActivityStack stack = ActivityRecord.getStackLocked(token);
1651 if (stack != null) {
1652 stack.activityDestroyedLocked(token, "activityDestroyed");
1653 }
1654 }
1655 }
1656
1657 @Override
1658 public final void activityRelaunched(IBinder token) {
1659 final long origId = Binder.clearCallingIdentity();
1660 synchronized (mGlobalLock) {
1661 mStackSupervisor.activityRelaunchedLocked(token);
1662 }
1663 Binder.restoreCallingIdentity(origId);
1664 }
1665
1666 public final void activitySlept(IBinder token) {
1667 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1668
1669 final long origId = Binder.clearCallingIdentity();
1670
1671 synchronized (mGlobalLock) {
1672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1673 if (r != null) {
1674 mStackSupervisor.activitySleptLocked(r);
1675 }
1676 }
1677
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680
1681 @Override
1682 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1683 synchronized (mGlobalLock) {
1684 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r == null) {
1686 return;
1687 }
1688 final long origId = Binder.clearCallingIdentity();
1689 try {
1690 r.setRequestedOrientation(requestedOrientation);
1691 } finally {
1692 Binder.restoreCallingIdentity(origId);
1693 }
1694 }
1695 }
1696
1697 @Override
1698 public int getRequestedOrientation(IBinder token) {
1699 synchronized (mGlobalLock) {
1700 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1701 if (r == null) {
1702 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1703 }
1704 return r.getRequestedOrientation();
1705 }
1706 }
1707
1708 @Override
1709 public void setImmersive(IBinder token, boolean immersive) {
1710 synchronized (mGlobalLock) {
1711 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1712 if (r == null) {
1713 throw new IllegalArgumentException();
1714 }
1715 r.immersive = immersive;
1716
1717 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001718 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001720 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 }
1722 }
1723 }
1724
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001725 void applyUpdateLockStateLocked(ActivityRecord r) {
1726 // Modifications to the UpdateLock state are done on our handler, outside
1727 // the activity manager's locks. The new state is determined based on the
1728 // state *now* of the relevant activity record. The object is passed to
1729 // the handler solely for logging detail, not to be consulted/modified.
1730 final boolean nextState = r != null && r.immersive;
1731 mH.post(() -> {
1732 if (mUpdateLock.isHeld() != nextState) {
1733 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1734 "Applying new update lock state '" + nextState + "' for " + r);
1735 if (nextState) {
1736 mUpdateLock.acquire();
1737 } else {
1738 mUpdateLock.release();
1739 }
1740 }
1741 });
1742 }
1743
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 @Override
1745 public boolean isImmersive(IBinder token) {
1746 synchronized (mGlobalLock) {
1747 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1748 if (r == null) {
1749 throw new IllegalArgumentException();
1750 }
1751 return r.immersive;
1752 }
1753 }
1754
1755 @Override
1756 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001759 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 return (r != null) ? r.immersive : false;
1761 }
1762 }
1763
1764 @Override
1765 public void overridePendingTransition(IBinder token, String packageName,
1766 int enterAnim, int exitAnim) {
1767 synchronized (mGlobalLock) {
1768 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1769 if (self == null) {
1770 return;
1771 }
1772
1773 final long origId = Binder.clearCallingIdentity();
1774
1775 if (self.isState(
1776 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001777 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001778 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
1780
1781 Binder.restoreCallingIdentity(origId);
1782 }
1783 }
1784
1785 @Override
1786 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001787 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001789 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 if (r == null) {
1791 return ActivityManager.COMPAT_MODE_UNKNOWN;
1792 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001793 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001794 }
1795 }
1796
1797 @Override
1798 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001801 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001803 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 if (r == null) {
1805 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1806 return;
1807 }
1808 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001809 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 }
1811 }
1812
1813 @Override
1814 public int getLaunchedFromUid(IBinder activityToken) {
1815 ActivityRecord srec;
1816 synchronized (mGlobalLock) {
1817 srec = ActivityRecord.forTokenLocked(activityToken);
1818 }
1819 if (srec == null) {
1820 return -1;
1821 }
1822 return srec.launchedFromUid;
1823 }
1824
1825 @Override
1826 public String getLaunchedFromPackage(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return null;
1833 }
1834 return srec.launchedFromPackage;
1835 }
1836
1837 @Override
1838 public boolean convertFromTranslucent(IBinder token) {
1839 final long origId = Binder.clearCallingIdentity();
1840 try {
1841 synchronized (mGlobalLock) {
1842 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1843 if (r == null) {
1844 return false;
1845 }
1846 final boolean translucentChanged = r.changeWindowTranslucency(true);
1847 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001848 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001850 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 return translucentChanged;
1852 }
1853 } finally {
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856 }
1857
1858 @Override
1859 public boolean convertToTranslucent(IBinder token, Bundle options) {
1860 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1861 final long origId = Binder.clearCallingIdentity();
1862 try {
1863 synchronized (mGlobalLock) {
1864 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1865 if (r == null) {
1866 return false;
1867 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001868 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 int index = task.mActivities.lastIndexOf(r);
1870 if (index > 0) {
1871 ActivityRecord under = task.mActivities.get(index - 1);
1872 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1873 }
1874 final boolean translucentChanged = r.changeWindowTranslucency(false);
1875 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001876 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001878 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001879 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 return translucentChanged;
1881 }
1882 } finally {
1883 Binder.restoreCallingIdentity(origId);
1884 }
1885 }
1886
1887 @Override
1888 public void notifyActivityDrawn(IBinder token) {
1889 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1890 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001891 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001893 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 }
1895 }
1896 }
1897
1898 @Override
1899 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1900 synchronized (mGlobalLock) {
1901 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1902 if (r == null) {
1903 return;
1904 }
1905 r.reportFullyDrawnLocked(restoredFromBundle);
1906 }
1907 }
1908
1909 @Override
1910 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1911 synchronized (mGlobalLock) {
1912 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1913 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1914 return stack.mDisplayId;
1915 }
1916 return DEFAULT_DISPLAY;
1917 }
1918 }
1919
1920 @Override
1921 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 long ident = Binder.clearCallingIdentity();
1924 try {
1925 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001926 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001928 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 return null;
1931 }
1932 } finally {
1933 Binder.restoreCallingIdentity(ident);
1934 }
1935 }
1936
1937 @Override
1938 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1941 final long callingId = Binder.clearCallingIdentity();
1942 try {
1943 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001944 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 if (stack == null) {
1946 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1947 return;
1948 }
1949 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001950 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001951 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 }
1953 }
1954 } finally {
1955 Binder.restoreCallingIdentity(callingId);
1956 }
1957 }
1958
1959 @Override
1960 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1963 final long callingId = Binder.clearCallingIdentity();
1964 try {
1965 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001966 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001967 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001968 if (task == null) {
1969 return;
1970 }
1971 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001972 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001973 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 }
1975 }
1976 } finally {
1977 Binder.restoreCallingIdentity(callingId);
1978 }
1979 }
1980
1981 @Override
1982 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001983 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001984 synchronized (mGlobalLock) {
1985 final long ident = Binder.clearCallingIdentity();
1986 try {
1987 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1988 "remove-task");
1989 } finally {
1990 Binder.restoreCallingIdentity(ident);
1991 }
1992 }
1993 }
1994
1995 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001996 public void removeAllVisibleRecentTasks() {
1997 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1998 synchronized (mGlobalLock) {
1999 final long ident = Binder.clearCallingIdentity();
2000 try {
2001 getRecentTasks().removeAllVisibleTasks();
2002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
2005 }
2006 }
2007
2008 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2010 synchronized (mGlobalLock) {
2011 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2012 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002013 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 }
2015 }
2016 return false;
2017 }
2018
2019 @Override
2020 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2021 Intent resultData) {
2022
2023 synchronized (mGlobalLock) {
2024 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2025 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002026 return r.getActivityStack().navigateUpToLocked(
2027 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 return false;
2030 }
2031 }
2032
2033 /**
2034 * Attempts to move a task backwards in z-order (the order of activities within the task is
2035 * unchanged).
2036 *
2037 * There are several possible results of this call:
2038 * - if the task is locked, then we will show the lock toast
2039 * - if there is a task behind the provided task, then that task is made visible and resumed as
2040 * this task is moved to the back
2041 * - otherwise, if there are no other tasks in the stack:
2042 * - if this task is in the pinned stack, then we remove the stack completely, which will
2043 * have the effect of moving the task to the top or bottom of the fullscreen stack
2044 * (depending on whether it is visible)
2045 * - otherwise, we simply return home and hide this task
2046 *
2047 * @param token A reference to the activity we wish to move
2048 * @param nonRoot If false then this only works if the activity is the root
2049 * of a task; if true it will work for any activity in a task.
2050 * @return Returns true if the move completed, false if not.
2051 */
2052 @Override
2053 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 synchronized (mGlobalLock) {
2056 final long origId = Binder.clearCallingIdentity();
2057 try {
2058 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 if (task != null) {
2061 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(origId);
2065 }
2066 }
2067 return false;
2068 }
2069
2070 @Override
2071 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 long ident = Binder.clearCallingIdentity();
2074 Rect rect = new Rect();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2079 if (task == null) {
2080 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2081 return rect;
2082 }
2083 if (task.getStack() != null) {
2084 // Return the bounds from window manager since it will be adjusted for various
2085 // things like the presense of a docked stack for tasks that aren't resizeable.
2086 task.getWindowContainerBounds(rect);
2087 } else {
2088 // Task isn't in window manager yet since it isn't associated with a stack.
2089 // Return the persist value from activity manager
2090 if (!task.matchParentBounds()) {
2091 rect.set(task.getBounds());
2092 } else if (task.mLastNonFullscreenBounds != null) {
2093 rect.set(task.mLastNonFullscreenBounds);
2094 }
2095 }
2096 }
2097 } finally {
2098 Binder.restoreCallingIdentity(ident);
2099 }
2100 return rect;
2101 }
2102
2103 @Override
2104 public ActivityManager.TaskDescription getTaskDescription(int id) {
2105 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002106 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002108 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2110 if (tr != null) {
2111 return tr.lastTaskDescription;
2112 }
2113 }
2114 return null;
2115 }
2116
2117 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002118 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2119 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2120 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2121 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2122 return;
2123 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002124 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002125 synchronized (mGlobalLock) {
2126 final long ident = Binder.clearCallingIdentity();
2127 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002128 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002129 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 if (task == null) {
2131 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2132 return;
2133 }
2134
2135 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2136 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2137
2138 if (!task.isActivityTypeStandardOrUndefined()) {
2139 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2140 + " non-standard task " + taskId + " to windowing mode="
2141 + windowingMode);
2142 }
2143
2144 final ActivityStack stack = task.getStack();
2145 if (toTop) {
2146 stack.moveToFront("setTaskWindowingMode", task);
2147 }
2148 stack.setWindowingMode(windowingMode);
2149 } finally {
2150 Binder.restoreCallingIdentity(ident);
2151 }
2152 }
2153 }
2154
2155 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 ActivityRecord r = getCallingRecordLocked(token);
2159 return r != null ? r.info.packageName : null;
2160 }
2161 }
2162
2163 @Override
2164 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002165 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 ActivityRecord r = getCallingRecordLocked(token);
2167 return r != null ? r.intent.getComponent() : null;
2168 }
2169 }
2170
2171 private ActivityRecord getCallingRecordLocked(IBinder token) {
2172 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2173 if (r == null) {
2174 return null;
2175 }
2176 return r.resultTo;
2177 }
2178
2179 @Override
2180 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002181 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182
2183 synchronized (mGlobalLock) {
2184 final long origId = Binder.clearCallingIdentity();
2185 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002186 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002187 } finally {
2188 Binder.restoreCallingIdentity(origId);
2189 }
2190 }
2191 }
2192
2193 /**
2194 * TODO: Add mController hook
2195 */
2196 @Override
2197 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002198 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199
2200 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2201 synchronized (mGlobalLock) {
2202 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2203 false /* fromRecents */);
2204 }
2205 }
2206
2207 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2208 boolean fromRecents) {
2209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 Binder.getCallingUid(), -1, -1, "Task to front")) {
2212 SafeActivityOptions.abort(options);
2213 return;
2214 }
2215 final long origId = Binder.clearCallingIdentity();
2216 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002217 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 if (task == null) {
2219 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002220 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 return;
2222 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002223 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002225 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 return;
2227 }
2228 ActivityOptions realOptions = options != null
2229 ? options.getOptions(mStackSupervisor)
2230 : null;
2231 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2232 false /* forceNonResizable */);
2233
2234 final ActivityRecord topActivity = task.getTopActivity();
2235 if (topActivity != null) {
2236
2237 // We are reshowing a task, use a starting window to hide the initial draw delay
2238 // so the transition can start earlier.
2239 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2240 true /* taskSwitch */, fromRecents);
2241 }
2242 } finally {
2243 Binder.restoreCallingIdentity(origId);
2244 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 }
2246
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2248 int callingPid, int callingUid, String name) {
2249 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2250 return true;
2251 }
2252
2253 if (getRecentTasks().isCallerRecents(sourceUid)) {
2254 return true;
2255 }
2256
2257 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2258 if (perm == PackageManager.PERMISSION_GRANTED) {
2259 return true;
2260 }
2261 if (checkAllowAppSwitchUid(sourceUid)) {
2262 return true;
2263 }
2264
2265 // If the actual IPC caller is different from the logical source, then
2266 // also see if they are allowed to control app switches.
2267 if (callingUid != -1 && callingUid != sourceUid) {
2268 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2269 if (perm == PackageManager.PERMISSION_GRANTED) {
2270 return true;
2271 }
2272 if (checkAllowAppSwitchUid(callingUid)) {
2273 return true;
2274 }
2275 }
2276
2277 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2278 return false;
2279 }
2280
2281 private boolean checkAllowAppSwitchUid(int uid) {
2282 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2283 if (types != null) {
2284 for (int i = types.size() - 1; i >= 0; i--) {
2285 if (types.valueAt(i).intValue() == uid) {
2286 return true;
2287 }
2288 }
2289 }
2290 return false;
2291 }
2292
2293 @Override
2294 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2295 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2296 "setActivityController()");
2297 synchronized (mGlobalLock) {
2298 mController = controller;
2299 mControllerIsAMonkey = imAMonkey;
2300 Watchdog.getInstance().setActivityController(controller);
2301 }
2302 }
2303
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002304 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 synchronized (mGlobalLock) {
2306 return mController != null && mControllerIsAMonkey;
2307 }
2308 }
2309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 @Override
2311 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2312 synchronized (mGlobalLock) {
2313 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2314 }
2315 }
2316
2317 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002318 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2319 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2320 }
2321
2322 @Override
2323 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2324 @WindowConfiguration.ActivityType int ignoreActivityType,
2325 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2326 final int callingUid = Binder.getCallingUid();
2327 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2328
2329 synchronized (mGlobalLock) {
2330 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002332 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002334 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 ignoreWindowingMode, callingUid, allowed);
2336 }
2337
2338 return list;
2339 }
2340
2341 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002342 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2343 synchronized (mGlobalLock) {
2344 final long origId = Binder.clearCallingIdentity();
2345 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2346 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002347 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348 }
2349 Binder.restoreCallingIdentity(origId);
2350 }
2351 }
2352
2353 @Override
2354 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002355 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 ActivityStack stack = ActivityRecord.getStackLocked(token);
2357 if (stack != null) {
2358 return stack.willActivityBeVisibleLocked(token);
2359 }
2360 return false;
2361 }
2362 }
2363
2364 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002365 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 synchronized (mGlobalLock) {
2368 final long ident = Binder.clearCallingIdentity();
2369 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002370 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002371 if (task == null) {
2372 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2373 return;
2374 }
2375
2376 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2377 + " to stackId=" + stackId + " toTop=" + toTop);
2378
Wale Ogunwaled32da472018-11-16 07:19:28 -08002379 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002380 if (stack == null) {
2381 throw new IllegalStateException(
2382 "moveTaskToStack: No stack for stackId=" + stackId);
2383 }
2384 if (!stack.isActivityTypeStandardOrUndefined()) {
2385 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2386 + taskId + " to stack " + stackId);
2387 }
2388 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002389 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002390 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2391 }
2392 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2393 "moveTaskToStack");
2394 } finally {
2395 Binder.restoreCallingIdentity(ident);
2396 }
2397 }
2398 }
2399
2400 @Override
2401 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2402 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002403 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002404
2405 final long ident = Binder.clearCallingIdentity();
2406 try {
2407 synchronized (mGlobalLock) {
2408 if (animate) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002409 final PinnedActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002410 if (stack == null) {
2411 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2412 return;
2413 }
2414 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2415 throw new IllegalArgumentException("Stack: " + stackId
2416 + " doesn't support animated resize.");
2417 }
2418 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2419 animationDuration, false /* fromFullscreen */);
2420 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002421 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 if (stack == null) {
2423 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2424 return;
2425 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002426 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002427 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2428 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2429 }
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(ident);
2433 }
2434 }
2435
2436 /**
2437 * Moves the specified task to the primary-split-screen stack.
2438 *
2439 * @param taskId Id of task to move.
2440 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2441 * exist already. See
2442 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2443 * and
2444 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2445 * @param toTop If the task and stack should be moved to the top.
2446 * @param animate Whether we should play an animation for the moving the task.
2447 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2448 * stack. Pass {@code null} to use default bounds.
2449 * @param showRecents If the recents activity should be shown on the other side of the task
2450 * going into split-screen mode.
2451 */
2452 @Override
2453 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2454 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002456 "setTaskWindowingModeSplitScreenPrimary()");
2457 synchronized (mGlobalLock) {
2458 final long ident = Binder.clearCallingIdentity();
2459 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002460 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002461 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002462 if (task == null) {
2463 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2464 return false;
2465 }
2466 if (DEBUG_STACK) Slog.d(TAG_STACK,
2467 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2468 + " to createMode=" + createMode + " toTop=" + toTop);
2469 if (!task.isActivityTypeStandardOrUndefined()) {
2470 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2471 + " non-standard task " + taskId + " to split-screen windowing mode");
2472 }
2473
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002474 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002475 final int windowingMode = task.getWindowingMode();
2476 final ActivityStack stack = task.getStack();
2477 if (toTop) {
2478 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2479 }
2480 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002481 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2482 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002483 return windowingMode != task.getWindowingMode();
2484 } finally {
2485 Binder.restoreCallingIdentity(ident);
2486 }
2487 }
2488 }
2489
2490 /**
2491 * Removes stacks in the input windowing modes from the system if they are of activity type
2492 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2493 */
2494 @Override
2495 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 "removeStacksInWindowingModes()");
2498
2499 synchronized (mGlobalLock) {
2500 final long ident = Binder.clearCallingIdentity();
2501 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002502 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
2506 }
2507 }
2508
2509 @Override
2510 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002511 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002512 "removeStacksWithActivityTypes()");
2513
2514 synchronized (mGlobalLock) {
2515 final long ident = Binder.clearCallingIdentity();
2516 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002517 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002518 } finally {
2519 Binder.restoreCallingIdentity(ident);
2520 }
2521 }
2522 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523
2524 @Override
2525 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2526 int userId) {
2527 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002528 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2529 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002531 final boolean detailed = checkGetTasksPermission(
2532 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2533 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 == PackageManager.PERMISSION_GRANTED;
2535
2536 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002537 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 callingUid);
2539 }
2540 }
2541
2542 @Override
2543 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002545 long ident = Binder.clearCallingIdentity();
2546 try {
2547 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002549 }
2550 } finally {
2551 Binder.restoreCallingIdentity(ident);
2552 }
2553 }
2554
2555 @Override
2556 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 long ident = Binder.clearCallingIdentity();
2559 try {
2560 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002561 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 }
2563 } finally {
2564 Binder.restoreCallingIdentity(ident);
2565 }
2566 }
2567
2568 @Override
2569 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002571 final long callingUid = Binder.getCallingUid();
2572 final long origId = Binder.clearCallingIdentity();
2573 try {
2574 synchronized (mGlobalLock) {
2575 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002576 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2578 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2579 }
2580 } finally {
2581 Binder.restoreCallingIdentity(origId);
2582 }
2583 }
2584
2585 @Override
2586 public void startLockTaskModeByToken(IBinder token) {
2587 synchronized (mGlobalLock) {
2588 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2589 if (r == null) {
2590 return;
2591 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002592 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 }
2594 }
2595
2596 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002597 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 // This makes inner call to look as if it was initiated by system.
2600 long ident = Binder.clearCallingIdentity();
2601 try {
2602 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002603 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002604 MATCH_TASK_IN_STACKS_ONLY);
2605 if (task == null) {
2606 return;
2607 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608
2609 // When starting lock task mode the stack must be in front and focused
2610 task.getStack().moveToFront("startSystemLockTaskMode");
2611 startLockTaskModeLocked(task, true /* isSystemCaller */);
2612 }
2613 } finally {
2614 Binder.restoreCallingIdentity(ident);
2615 }
2616 }
2617
2618 @Override
2619 public void stopLockTaskModeByToken(IBinder token) {
2620 synchronized (mGlobalLock) {
2621 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2622 if (r == null) {
2623 return;
2624 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002625 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002626 }
2627 }
2628
2629 /**
2630 * This API should be called by SystemUI only when user perform certain action to dismiss
2631 * lock task mode. We should only dismiss pinned lock task mode in this case.
2632 */
2633 @Override
2634 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002635 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002636 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2637 }
2638
2639 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2640 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2641 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2642 return;
2643 }
2644
Wale Ogunwaled32da472018-11-16 07:19:28 -08002645 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 if (stack == null || task != stack.topTask()) {
2647 throw new IllegalArgumentException("Invalid task, not in foreground");
2648 }
2649
2650 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2651 // system or a specific app.
2652 // * System-initiated requests will only start the pinned mode (screen pinning)
2653 // * App-initiated requests
2654 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2655 // - will start the pinned mode, otherwise
2656 final int callingUid = Binder.getCallingUid();
2657 long ident = Binder.clearCallingIdentity();
2658 try {
2659 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002660 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002662 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 } finally {
2664 Binder.restoreCallingIdentity(ident);
2665 }
2666 }
2667
2668 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2669 final int callingUid = Binder.getCallingUid();
2670 long ident = Binder.clearCallingIdentity();
2671 try {
2672 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002673 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 }
2675 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2676 // task and jumping straight into a call in the case of emergency call back.
2677 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2678 if (tm != null) {
2679 tm.showInCallScreen(false);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
2685
2686 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002687 public void updateLockTaskPackages(int userId, String[] packages) {
2688 final int callingUid = Binder.getCallingUid();
2689 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2690 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2691 "updateLockTaskPackages()");
2692 }
2693 synchronized (this) {
2694 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2695 + Arrays.toString(packages));
2696 getLockTaskController().updateLockTaskPackages(userId, packages);
2697 }
2698 }
2699
2700 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 public boolean isInLockTaskMode() {
2702 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2703 }
2704
2705 @Override
2706 public int getLockTaskModeState() {
2707 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002708 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 }
2710 }
2711
2712 @Override
2713 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2714 synchronized (mGlobalLock) {
2715 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2716 if (r != null) {
2717 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002718 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002719 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002720 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 }
2722 }
2723 }
2724
2725 @Override
2726 public Bundle getActivityOptions(IBinder token) {
2727 final long origId = Binder.clearCallingIdentity();
2728 try {
2729 synchronized (mGlobalLock) {
2730 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2731 if (r != null) {
2732 final ActivityOptions activityOptions = r.takeOptionsLocked();
2733 return activityOptions == null ? null : activityOptions.toBundle();
2734 }
2735 return null;
2736 }
2737 } finally {
2738 Binder.restoreCallingIdentity(origId);
2739 }
2740 }
2741
2742 @Override
2743 public List<IBinder> getAppTasks(String callingPackage) {
2744 int callingUid = Binder.getCallingUid();
2745 long ident = Binder.clearCallingIdentity();
2746 try {
2747 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002748 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002749 }
2750 } finally {
2751 Binder.restoreCallingIdentity(ident);
2752 }
2753 }
2754
2755 @Override
2756 public void finishVoiceTask(IVoiceInteractionSession session) {
2757 synchronized (mGlobalLock) {
2758 final long origId = Binder.clearCallingIdentity();
2759 try {
2760 // TODO: VI Consider treating local voice interactions and voice tasks
2761 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002762 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 } finally {
2764 Binder.restoreCallingIdentity(origId);
2765 }
2766 }
2767
2768 }
2769
2770 @Override
2771 public boolean isTopOfTask(IBinder token) {
2772 synchronized (mGlobalLock) {
2773 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002774 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 }
2776 }
2777
2778 @Override
2779 public void notifyLaunchTaskBehindComplete(IBinder token) {
2780 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2781 }
2782
2783 @Override
2784 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002785 mH.post(() -> {
2786 synchronized (mGlobalLock) {
2787 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002788 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002789 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002790 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002791 } catch (RemoteException e) {
2792 }
2793 }
2794 }
2795
2796 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798
2799 /** Called from an app when assist data is ready. */
2800 @Override
2801 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2802 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 synchronized (pae) {
2805 pae.result = extras;
2806 pae.structure = structure;
2807 pae.content = content;
2808 if (referrer != null) {
2809 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2810 }
2811 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002812 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002813 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2814 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 structure.setHomeActivity(pae.isHome);
2816 }
2817 pae.haveResult = true;
2818 pae.notifyAll();
2819 if (pae.intent == null && pae.receiver == null) {
2820 // Caller is just waiting for the result.
2821 return;
2822 }
2823 }
2824 // We are now ready to launch the assist activity.
2825 IAssistDataReceiver sendReceiver = null;
2826 Bundle sendBundle = null;
2827 synchronized (mGlobalLock) {
2828 buildAssistBundleLocked(pae, extras);
2829 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002830 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002831 if (!exists) {
2832 // Timed out.
2833 return;
2834 }
2835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002836 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 // Caller wants result sent back to them.
2838 sendBundle = new Bundle();
2839 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2840 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2841 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2842 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2843 }
2844 }
2845 if (sendReceiver != null) {
2846 try {
2847 sendReceiver.onHandleAssistData(sendBundle);
2848 } catch (RemoteException e) {
2849 }
2850 return;
2851 }
2852
2853 final long ident = Binder.clearCallingIdentity();
2854 try {
2855 if (TextUtils.equals(pae.intent.getAction(),
2856 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2857 pae.intent.putExtras(pae.extras);
2858 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2859 } else {
2860 pae.intent.replaceExtras(pae.extras);
2861 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2862 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2863 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002864 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865
2866 try {
2867 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2868 } catch (ActivityNotFoundException e) {
2869 Slog.w(TAG, "No activity to handle assist action.", e);
2870 }
2871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(ident);
2874 }
2875 }
2876
2877 @Override
2878 public int addAppTask(IBinder activityToken, Intent intent,
2879 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2880 final int callingUid = Binder.getCallingUid();
2881 final long callingIdent = Binder.clearCallingIdentity();
2882
2883 try {
2884 synchronized (mGlobalLock) {
2885 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2886 if (r == null) {
2887 throw new IllegalArgumentException("Activity does not exist; token="
2888 + activityToken);
2889 }
2890 ComponentName comp = intent.getComponent();
2891 if (comp == null) {
2892 throw new IllegalArgumentException("Intent " + intent
2893 + " must specify explicit component");
2894 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002895 if (thumbnail.getWidth() != mThumbnailWidth
2896 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 throw new IllegalArgumentException("Bad thumbnail size: got "
2898 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002899 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 }
2901 if (intent.getSelector() != null) {
2902 intent.setSelector(null);
2903 }
2904 if (intent.getSourceBounds() != null) {
2905 intent.setSourceBounds(null);
2906 }
2907 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2908 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2909 // The caller has added this as an auto-remove task... that makes no
2910 // sense, so turn off auto-remove.
2911 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2912 }
2913 }
2914 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2915 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2916 if (ainfo.applicationInfo.uid != callingUid) {
2917 throw new SecurityException(
2918 "Can't add task for another application: target uid="
2919 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2920 }
2921
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002922 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002926 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 // The app has too many tasks already and we can't add any more
2928 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2929 return INVALID_TASK_ID;
2930 }
2931 task.lastTaskDescription.copyFrom(description);
2932
2933 // TODO: Send the thumbnail to WM to store it.
2934
2935 return task.taskId;
2936 }
2937 } finally {
2938 Binder.restoreCallingIdentity(callingIdent);
2939 }
2940 }
2941
2942 @Override
2943 public Point getAppTaskThumbnailSize() {
2944 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002945 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 }
2948
2949 @Override
2950 public void setTaskResizeable(int taskId, int resizeableMode) {
2951 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002952 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2954 if (task == null) {
2955 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2956 return;
2957 }
2958 task.setResizeMode(resizeableMode);
2959 }
2960 }
2961
2962 @Override
2963 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002964 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 long ident = Binder.clearCallingIdentity();
2966 try {
2967 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002968 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002969 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 if (task == null) {
2971 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2972 return;
2973 }
2974 // Place the task in the right stack if it isn't there already based on
2975 // the requested bounds.
2976 // The stack transition logic is:
2977 // - a null bounds on a freeform task moves that task to fullscreen
2978 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2979 // that task to freeform
2980 // - otherwise the task is not moved
2981 ActivityStack stack = task.getStack();
2982 if (!task.getWindowConfiguration().canResizeTask()) {
2983 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2984 }
2985 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2986 stack = stack.getDisplay().getOrCreateStack(
2987 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2988 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2989 stack = stack.getDisplay().getOrCreateStack(
2990 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2991 }
2992
2993 // Reparent the task to the right stack if necessary
2994 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2995 if (stack != task.getStack()) {
2996 // Defer resume until the task is resized below
2997 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2998 DEFER_RESUME, "resizeTask");
2999 preserveWindow = false;
3000 }
3001
3002 // After reparenting (which only resizes the task to the stack bounds), resize the
3003 // task to the actual bounds provided
3004 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3005 }
3006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
3009 }
3010
3011 @Override
3012 public boolean releaseActivityInstance(IBinder token) {
3013 synchronized (mGlobalLock) {
3014 final long origId = Binder.clearCallingIdentity();
3015 try {
3016 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3017 if (r == null) {
3018 return false;
3019 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003020 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 } finally {
3022 Binder.restoreCallingIdentity(origId);
3023 }
3024 }
3025 }
3026
3027 @Override
3028 public void releaseSomeActivities(IApplicationThread appInt) {
3029 synchronized (mGlobalLock) {
3030 final long origId = Binder.clearCallingIdentity();
3031 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003032 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003033 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 } finally {
3035 Binder.restoreCallingIdentity(origId);
3036 }
3037 }
3038 }
3039
3040 @Override
3041 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003042 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003043 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 != PackageManager.PERMISSION_GRANTED) {
3045 throw new SecurityException("Requires permission "
3046 + android.Manifest.permission.DEVICE_POWER);
3047 }
3048
3049 synchronized (mGlobalLock) {
3050 long ident = Binder.clearCallingIdentity();
3051 if (mKeyguardShown != keyguardShowing) {
3052 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003053 final Message msg = PooledLambda.obtainMessage(
3054 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3055 keyguardShowing);
3056 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003057 }
3058 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003059 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003060 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 } finally {
3062 Binder.restoreCallingIdentity(ident);
3063 }
3064 }
3065
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003066 mH.post(() -> {
3067 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3068 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3069 }
3070 });
3071 }
3072
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003073 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 mH.post(() -> {
3075 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3076 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3077 }
3078 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 }
3080
3081 @Override
3082 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003083 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3084 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085
3086 final File passedIconFile = new File(filePath);
3087 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3088 passedIconFile.getName());
3089 if (!legitIconFile.getPath().equals(filePath)
3090 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3091 throw new IllegalArgumentException("Bad file path: " + filePath
3092 + " passed for userId " + userId);
3093 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003094 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 }
3096
3097 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3100 final ActivityOptions activityOptions = safeOptions != null
3101 ? safeOptions.getOptions(mStackSupervisor)
3102 : null;
3103 if (activityOptions == null
3104 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3105 || activityOptions.getCustomInPlaceResId() == 0) {
3106 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3107 "with valid animation");
3108 }
lumark588a3e82018-07-20 18:53:54 +08003109 // Get top display of front most application.
3110 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3111 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003112 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3113 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3114 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003115 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003116 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003117 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 }
3119
3120 @Override
3121 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 synchronized (mGlobalLock) {
3124 final long ident = Binder.clearCallingIdentity();
3125 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003126 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 if (stack == null) {
3128 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3129 return;
3130 }
3131 if (!stack.isActivityTypeStandardOrUndefined()) {
3132 throw new IllegalArgumentException(
3133 "Removing non-standard stack is not allowed.");
3134 }
3135 mStackSupervisor.removeStack(stack);
3136 } finally {
3137 Binder.restoreCallingIdentity(ident);
3138 }
3139 }
3140 }
3141
3142 @Override
3143 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003144 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145
3146 synchronized (mGlobalLock) {
3147 final long ident = Binder.clearCallingIdentity();
3148 try {
3149 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3150 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003151 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 } finally {
3153 Binder.restoreCallingIdentity(ident);
3154 }
3155 }
3156 }
3157
3158 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 public void exitFreeformMode(IBinder token) {
3160 synchronized (mGlobalLock) {
3161 long ident = Binder.clearCallingIdentity();
3162 try {
3163 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3164 if (r == null) {
3165 throw new IllegalArgumentException(
3166 "exitFreeformMode: No activity record matching token=" + token);
3167 }
3168
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 if (stack == null || !stack.inFreeformWindowingMode()) {
3171 throw new IllegalStateException(
3172 "exitFreeformMode: You can only go fullscreen from freeform.");
3173 }
3174
3175 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3176 } finally {
3177 Binder.restoreCallingIdentity(ident);
3178 }
3179 }
3180 }
3181
3182 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3183 @Override
3184 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003185 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003187 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 }
3189
3190 /** Unregister a task stack listener so that it stops receiving callbacks. */
3191 @Override
3192 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003193 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003195 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 @Override
3199 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3200 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3201 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3202 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3203 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3204 }
3205
3206 @Override
3207 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3208 IBinder activityToken, int flags) {
3209 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3210 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3211 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3212 }
3213
3214 @Override
3215 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3216 Bundle args) {
3217 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3218 true /* focused */, true /* newSessionId */, userHandle, args,
3219 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3220 }
3221
3222 @Override
3223 public Bundle getAssistContextExtras(int requestType) {
3224 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3225 null, null, true /* focused */, true /* newSessionId */,
3226 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3227 if (pae == null) {
3228 return null;
3229 }
3230 synchronized (pae) {
3231 while (!pae.haveResult) {
3232 try {
3233 pae.wait();
3234 } catch (InterruptedException e) {
3235 }
3236 }
3237 }
3238 synchronized (mGlobalLock) {
3239 buildAssistBundleLocked(pae, pae.result);
3240 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 }
3243 return pae.extras;
3244 }
3245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003246 /**
3247 * Binder IPC calls go through the public entry point.
3248 * This can be called with or without the global lock held.
3249 */
3250 private static int checkCallingPermission(String permission) {
3251 return checkPermission(
3252 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3253 }
3254
3255 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003256 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003257 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3258 mAmInternal.enforceCallingPermission(permission, func);
3259 }
3260 }
3261
3262 @VisibleForTesting
3263 int checkGetTasksPermission(String permission, int pid, int uid) {
3264 return checkPermission(permission, pid, uid);
3265 }
3266
3267 static int checkPermission(String permission, int pid, int uid) {
3268 if (permission == null) {
3269 return PackageManager.PERMISSION_DENIED;
3270 }
3271 return checkComponentPermission(permission, pid, uid, -1, true);
3272 }
3273
Wale Ogunwale214f3482018-10-04 11:00:47 -07003274 public static int checkComponentPermission(String permission, int pid, int uid,
3275 int owningUid, boolean exported) {
3276 return ActivityManagerService.checkComponentPermission(
3277 permission, pid, uid, owningUid, exported);
3278 }
3279
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3281 if (getRecentTasks().isCallerRecents(callingUid)) {
3282 // Always allow the recents component to get tasks
3283 return true;
3284 }
3285
3286 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3287 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3288 if (!allowed) {
3289 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3290 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3291 // Temporary compatibility: some existing apps on the system image may
3292 // still be requesting the old permission and not switched to the new
3293 // one; if so, we'll still allow them full access. This means we need
3294 // to see if they are holding the old permission and are a system app.
3295 try {
3296 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3297 allowed = true;
3298 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3299 + " is using old GET_TASKS but privileged; allowing");
3300 }
3301 } catch (RemoteException e) {
3302 }
3303 }
3304 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3305 + " does not hold REAL_GET_TASKS; limiting output");
3306 }
3307 return allowed;
3308 }
3309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3311 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3312 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3313 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 "enqueueAssistContext()");
3316
3317 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003318 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 if (activity == null) {
3320 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3321 return null;
3322 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003323 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3325 return null;
3326 }
3327 if (focused) {
3328 if (activityToken != null) {
3329 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3330 if (activity != caller) {
3331 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3332 + " is not current top " + activity);
3333 return null;
3334 }
3335 }
3336 } else {
3337 activity = ActivityRecord.forTokenLocked(activityToken);
3338 if (activity == null) {
3339 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3340 + " couldn't be found");
3341 return null;
3342 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003343 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3345 return null;
3346 }
3347 }
3348
3349 PendingAssistExtras pae;
3350 Bundle extras = new Bundle();
3351 if (args != null) {
3352 extras.putAll(args);
3353 }
3354 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003355 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356
3357 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3358 userHandle);
3359 pae.isHome = activity.isActivityTypeHome();
3360
3361 // Increment the sessionId if necessary
3362 if (newSessionId) {
3363 mViSessionId++;
3364 }
3365 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003366 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3367 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 } catch (RemoteException e) {
3371 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3372 return null;
3373 }
3374 return pae;
3375 }
3376 }
3377
3378 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3379 if (result != null) {
3380 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3381 }
3382 if (pae.hint != null) {
3383 pae.extras.putBoolean(pae.hint, true);
3384 }
3385 }
3386
3387 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3388 IAssistDataReceiver receiver;
3389 synchronized (mGlobalLock) {
3390 mPendingAssistExtras.remove(pae);
3391 receiver = pae.receiver;
3392 }
3393 if (receiver != null) {
3394 // Caller wants result sent back to them.
3395 Bundle sendBundle = new Bundle();
3396 // At least return the receiver extras
3397 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3398 try {
3399 pae.receiver.onHandleAssistData(sendBundle);
3400 } catch (RemoteException e) {
3401 }
3402 }
3403 }
3404
3405 public class PendingAssistExtras extends Binder implements Runnable {
3406 public final ActivityRecord activity;
3407 public boolean isHome;
3408 public final Bundle extras;
3409 public final Intent intent;
3410 public final String hint;
3411 public final IAssistDataReceiver receiver;
3412 public final int userHandle;
3413 public boolean haveResult = false;
3414 public Bundle result = null;
3415 public AssistStructure structure = null;
3416 public AssistContent content = null;
3417 public Bundle receiverExtras;
3418
3419 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3420 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3421 int _userHandle) {
3422 activity = _activity;
3423 extras = _extras;
3424 intent = _intent;
3425 hint = _hint;
3426 receiver = _receiver;
3427 receiverExtras = _receiverExtras;
3428 userHandle = _userHandle;
3429 }
3430
3431 @Override
3432 public void run() {
3433 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3434 synchronized (this) {
3435 haveResult = true;
3436 notifyAll();
3437 }
3438 pendingAssistExtrasTimedOut(this);
3439 }
3440 }
3441
3442 @Override
3443 public boolean isAssistDataAllowedOnCurrentActivity() {
3444 int userId;
3445 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003446 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3448 return false;
3449 }
3450
3451 final ActivityRecord activity = focusedStack.getTopActivity();
3452 if (activity == null) {
3453 return false;
3454 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003455 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 }
3457 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3458 }
3459
3460 @Override
3461 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3462 long ident = Binder.clearCallingIdentity();
3463 try {
3464 synchronized (mGlobalLock) {
3465 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003466 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 if (top != caller) {
3468 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3469 + " is not current top " + top);
3470 return false;
3471 }
3472 if (!top.nowVisible) {
3473 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3474 + " is not visible");
3475 return false;
3476 }
3477 }
3478 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3479 token);
3480 } finally {
3481 Binder.restoreCallingIdentity(ident);
3482 }
3483 }
3484
3485 @Override
3486 public boolean isRootVoiceInteraction(IBinder token) {
3487 synchronized (mGlobalLock) {
3488 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3489 if (r == null) {
3490 return false;
3491 }
3492 return r.rootVoiceInteraction;
3493 }
3494 }
3495
Wale Ogunwalef6733932018-06-27 05:14:34 -07003496 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3497 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3498 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3499 if (activityToCallback == null) return;
3500 activityToCallback.setVoiceSessionLocked(voiceSession);
3501
3502 // Inform the activity
3503 try {
3504 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3505 voiceInteractor);
3506 long token = Binder.clearCallingIdentity();
3507 try {
3508 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3509 } finally {
3510 Binder.restoreCallingIdentity(token);
3511 }
3512 // TODO: VI Should we cache the activity so that it's easier to find later
3513 // rather than scan through all the stacks and activities?
3514 } catch (RemoteException re) {
3515 activityToCallback.clearVoiceSessionLocked();
3516 // TODO: VI Should this terminate the voice session?
3517 }
3518 }
3519
3520 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3521 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3522 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3523 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3524 boolean wasRunningVoice = mRunningVoice != null;
3525 mRunningVoice = session;
3526 if (!wasRunningVoice) {
3527 mVoiceWakeLock.acquire();
3528 updateSleepIfNeededLocked();
3529 }
3530 }
3531 }
3532
3533 void finishRunningVoiceLocked() {
3534 if (mRunningVoice != null) {
3535 mRunningVoice = null;
3536 mVoiceWakeLock.release();
3537 updateSleepIfNeededLocked();
3538 }
3539 }
3540
3541 @Override
3542 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3543 synchronized (mGlobalLock) {
3544 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3545 if (keepAwake) {
3546 mVoiceWakeLock.acquire();
3547 } else {
3548 mVoiceWakeLock.release();
3549 }
3550 }
3551 }
3552 }
3553
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 @Override
3555 public ComponentName getActivityClassForToken(IBinder token) {
3556 synchronized (mGlobalLock) {
3557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3558 if (r == null) {
3559 return null;
3560 }
3561 return r.intent.getComponent();
3562 }
3563 }
3564
3565 @Override
3566 public String getPackageForToken(IBinder token) {
3567 synchronized (mGlobalLock) {
3568 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3569 if (r == null) {
3570 return null;
3571 }
3572 return r.packageName;
3573 }
3574 }
3575
3576 @Override
3577 public void showLockTaskEscapeMessage(IBinder token) {
3578 synchronized (mGlobalLock) {
3579 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3580 if (r == null) {
3581 return;
3582 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003583 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003584 }
3585 }
3586
3587 @Override
3588 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 final long token = Binder.clearCallingIdentity();
3591 try {
3592 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003593 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 }
3595 } finally {
3596 Binder.restoreCallingIdentity(token);
3597 }
3598 }
3599
3600 /**
3601 * Try to place task to provided position. The final position might be different depending on
3602 * current user and stacks state. The task will be moved to target stack if it's currently in
3603 * different stack.
3604 */
3605 @Override
3606 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003607 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 synchronized (mGlobalLock) {
3609 long ident = Binder.clearCallingIdentity();
3610 try {
3611 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3612 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003613 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 if (task == null) {
3615 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3616 + taskId);
3617 }
3618
Wale Ogunwaled32da472018-11-16 07:19:28 -08003619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620
3621 if (stack == null) {
3622 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3623 + stackId);
3624 }
3625 if (!stack.isActivityTypeStandardOrUndefined()) {
3626 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3627 + " the position of task " + taskId + " in/to non-standard stack");
3628 }
3629
3630 // TODO: Have the callers of this API call a separate reparent method if that is
3631 // what they intended to do vs. having this method also do reparenting.
3632 if (task.getStack() == stack) {
3633 // Change position in current stack.
3634 stack.positionChildAt(task, position);
3635 } else {
3636 // Reparent to new stack.
3637 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3638 !DEFER_RESUME, "positionTaskInStack");
3639 }
3640 } finally {
3641 Binder.restoreCallingIdentity(ident);
3642 }
3643 }
3644 }
3645
3646 @Override
3647 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3648 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3649 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3650 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3651 synchronized (mGlobalLock) {
3652 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3653 if (record == null) {
3654 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3655 + "found for: " + token);
3656 }
3657 record.setSizeConfigurations(horizontalSizeConfiguration,
3658 verticalSizeConfigurations, smallestSizeConfigurations);
3659 }
3660 }
3661
3662 /**
3663 * Dismisses split-screen multi-window mode.
3664 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3665 */
3666 @Override
3667 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003668 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3670 final long ident = Binder.clearCallingIdentity();
3671 try {
3672 synchronized (mGlobalLock) {
3673 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003674 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675 if (stack == null) {
3676 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3677 return;
3678 }
3679
3680 if (toTop) {
3681 // Caller wants the current split-screen primary stack to be the top stack after
3682 // it goes fullscreen, so move it to the front.
3683 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003684 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 // In this case the current split-screen primary stack shouldn't be the top
3686 // stack after it goes fullscreen, but it current has focus, so we move the
3687 // focus to the top-most split-screen secondary stack next to it.
3688 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3689 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3690 if (otherStack != null) {
3691 otherStack.moveToFront("dismissSplitScreenMode_other");
3692 }
3693 }
3694
Evan Rosky10475742018-09-05 19:02:48 -07003695 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 }
3697 } finally {
3698 Binder.restoreCallingIdentity(ident);
3699 }
3700 }
3701
3702 /**
3703 * Dismisses Pip
3704 * @param animate True if the dismissal should be animated.
3705 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3706 * default animation duration should be used.
3707 */
3708 @Override
3709 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 final long ident = Binder.clearCallingIdentity();
3712 try {
3713 synchronized (mGlobalLock) {
3714 final PinnedActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003715 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 if (stack == null) {
3717 Slog.w(TAG, "dismissPip: pinned stack not found.");
3718 return;
3719 }
3720 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3721 throw new IllegalArgumentException("Stack: " + stack
3722 + " doesn't support animated resize.");
3723 }
3724 if (animate) {
3725 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3726 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3727 } else {
3728 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3729 }
3730 }
3731 } finally {
3732 Binder.restoreCallingIdentity(ident);
3733 }
3734 }
3735
3736 @Override
3737 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003738 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 synchronized (mGlobalLock) {
3740 mSuppressResizeConfigChanges = suppress;
3741 }
3742 }
3743
3744 /**
3745 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3746 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3747 * activity and clearing the task at the same time.
3748 */
3749 @Override
3750 // TODO: API should just be about changing windowing modes...
3751 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003752 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 "moveTasksToFullscreenStack()");
3754 synchronized (mGlobalLock) {
3755 final long origId = Binder.clearCallingIdentity();
3756 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003757 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003758 if (stack != null){
3759 if (!stack.isActivityTypeStandardOrUndefined()) {
3760 throw new IllegalArgumentException(
3761 "You can't move tasks from non-standard stacks.");
3762 }
3763 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3764 }
3765 } finally {
3766 Binder.restoreCallingIdentity(origId);
3767 }
3768 }
3769 }
3770
3771 /**
3772 * Moves the top activity in the input stackId to the pinned stack.
3773 *
3774 * @param stackId Id of stack to move the top activity to pinned stack.
3775 * @param bounds Bounds to use for pinned stack.
3776 *
3777 * @return True if the top activity of the input stack was successfully moved to the pinned
3778 * stack.
3779 */
3780 @Override
3781 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003782 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 "moveTopActivityToPinnedStack()");
3784 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003785 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3787 + "Device doesn't support picture-in-picture mode");
3788 }
3789
3790 long ident = Binder.clearCallingIdentity();
3791 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003792 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 } finally {
3794 Binder.restoreCallingIdentity(ident);
3795 }
3796 }
3797 }
3798
3799 @Override
3800 public boolean isInMultiWindowMode(IBinder token) {
3801 final long origId = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mGlobalLock) {
3804 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return false;
3807 }
3808 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3809 return r.inMultiWindowMode();
3810 }
3811 } finally {
3812 Binder.restoreCallingIdentity(origId);
3813 }
3814 }
3815
3816 @Override
3817 public boolean isInPictureInPictureMode(IBinder token) {
3818 final long origId = Binder.clearCallingIdentity();
3819 try {
3820 synchronized (mGlobalLock) {
3821 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3822 }
3823 } finally {
3824 Binder.restoreCallingIdentity(origId);
3825 }
3826 }
3827
3828 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003829 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3830 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 return false;
3832 }
3833
3834 // If we are animating to fullscreen then we have already dispatched the PIP mode
3835 // changed, so we should reflect that check here as well.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003836 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 final PinnedStackWindowController windowController = stack.getWindowContainerController();
Evan Rosky1ac84462018-11-13 11:25:30 -08003838 return !windowController.mContainer.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 }
3840
3841 @Override
3842 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3843 final long origId = Binder.clearCallingIdentity();
3844 try {
3845 synchronized (mGlobalLock) {
3846 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3847 "enterPictureInPictureMode", token, params);
3848
3849 // If the activity is already in picture in picture mode, then just return early
3850 if (isInPictureInPictureMode(r)) {
3851 return true;
3852 }
3853
3854 // Activity supports picture-in-picture, now check that we can enter PiP at this
3855 // point, if it is
3856 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3857 false /* beforeStopping */)) {
3858 return false;
3859 }
3860
3861 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003862 synchronized (mGlobalLock) {
3863 // Only update the saved args from the args that are set
3864 r.pictureInPictureArgs.copyOnlySet(params);
3865 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3866 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3867 // Adjust the source bounds by the insets for the transition down
3868 final Rect sourceBounds = new Rect(
3869 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003870 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003871 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003872 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003873 stack.setPictureInPictureAspectRatio(aspectRatio);
3874 stack.setPictureInPictureActions(actions);
3875 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3876 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3877 logPictureInPictureArgs(params);
3878 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003879 };
3880
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003881 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 // If the keyguard is showing or occluded, then try and dismiss it before
3883 // entering picture-in-picture (this will prompt the user to authenticate if the
3884 // device is currently locked).
3885 dismissKeyguard(token, new KeyguardDismissCallback() {
3886 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003887 public void onDismissSucceeded() {
3888 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 }
3890 }, null /* message */);
3891 } else {
3892 // Enter picture in picture immediately otherwise
3893 enterPipRunnable.run();
3894 }
3895 return true;
3896 }
3897 } finally {
3898 Binder.restoreCallingIdentity(origId);
3899 }
3900 }
3901
3902 @Override
3903 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3904 final long origId = Binder.clearCallingIdentity();
3905 try {
3906 synchronized (mGlobalLock) {
3907 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3908 "setPictureInPictureParams", token, params);
3909
3910 // Only update the saved args from the args that are set
3911 r.pictureInPictureArgs.copyOnlySet(params);
3912 if (r.inPinnedWindowingMode()) {
3913 // If the activity is already in picture-in-picture, update the pinned stack now
3914 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3915 // be used the next time the activity enters PiP
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003916 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 if (!stack.isAnimatingBoundsToFullscreen()) {
3918 stack.setPictureInPictureAspectRatio(
3919 r.pictureInPictureArgs.getAspectRatio());
3920 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3921 }
3922 }
3923 logPictureInPictureArgs(params);
3924 }
3925 } finally {
3926 Binder.restoreCallingIdentity(origId);
3927 }
3928 }
3929
3930 @Override
3931 public int getMaxNumPictureInPictureActions(IBinder token) {
3932 // Currently, this is a static constant, but later, we may change this to be dependent on
3933 // the context of the activity
3934 return 3;
3935 }
3936
3937 private void logPictureInPictureArgs(PictureInPictureParams params) {
3938 if (params.hasSetActions()) {
3939 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3940 params.getActions().size());
3941 }
3942 if (params.hasSetAspectRatio()) {
3943 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3944 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3945 MetricsLogger.action(lm);
3946 }
3947 }
3948
3949 /**
3950 * Checks the state of the system and the activity associated with the given {@param token} to
3951 * verify that picture-in-picture is supported for that activity.
3952 *
3953 * @return the activity record for the given {@param token} if all the checks pass.
3954 */
3955 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3956 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003957 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 throw new IllegalStateException(caller
3959 + ": Device doesn't support picture-in-picture mode.");
3960 }
3961
3962 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3963 if (r == null) {
3964 throw new IllegalStateException(caller
3965 + ": Can't find activity for token=" + token);
3966 }
3967
3968 if (!r.supportsPictureInPicture()) {
3969 throw new IllegalStateException(caller
3970 + ": Current activity does not support picture-in-picture.");
3971 }
3972
3973 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003974 && !mWindowManager.isValidPictureInPictureAspectRatio(
3975 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 final float minAspectRatio = mContext.getResources().getFloat(
3977 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3978 final float maxAspectRatio = mContext.getResources().getFloat(
3979 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3980 throw new IllegalArgumentException(String.format(caller
3981 + ": Aspect ratio is too extreme (must be between %f and %f).",
3982 minAspectRatio, maxAspectRatio));
3983 }
3984
3985 // Truncate the number of actions if necessary
3986 params.truncateActions(getMaxNumPictureInPictureActions(token));
3987
3988 return r;
3989 }
3990
3991 @Override
3992 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003993 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003994 synchronized (mGlobalLock) {
3995 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3996 if (r == null) {
3997 throw new IllegalArgumentException("Activity does not exist; token="
3998 + activityToken);
3999 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004000 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 }
4002 }
4003
4004 @Override
4005 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4006 Rect tempDockedTaskInsetBounds,
4007 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004008 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004009 long ident = Binder.clearCallingIdentity();
4010 try {
4011 synchronized (mGlobalLock) {
4012 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4013 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4014 PRESERVE_WINDOWS);
4015 }
4016 } finally {
4017 Binder.restoreCallingIdentity(ident);
4018 }
4019 }
4020
4021 @Override
4022 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004023 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 final long ident = Binder.clearCallingIdentity();
4025 try {
4026 synchronized (mGlobalLock) {
4027 mStackSupervisor.setSplitScreenResizing(resizing);
4028 }
4029 } finally {
4030 Binder.restoreCallingIdentity(ident);
4031 }
4032 }
4033
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 /**
4035 * Check that we have the features required for VR-related API calls, and throw an exception if
4036 * not.
4037 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004038 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004039 if (!mContext.getPackageManager().hasSystemFeature(
4040 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4041 throw new UnsupportedOperationException("VR mode not supported on this device!");
4042 }
4043 }
4044
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 @Override
4046 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004047 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004048
4049 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4050
4051 ActivityRecord r;
4052 synchronized (mGlobalLock) {
4053 r = ActivityRecord.isInStackLocked(token);
4054 }
4055
4056 if (r == null) {
4057 throw new IllegalArgumentException();
4058 }
4059
4060 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004061 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 VrManagerInternal.NO_ERROR) {
4063 return err;
4064 }
4065
4066 // Clear the binder calling uid since this path may call moveToTask().
4067 final long callingId = Binder.clearCallingIdentity();
4068 try {
4069 synchronized (mGlobalLock) {
4070 r.requestedVrComponent = (enabled) ? packageName : null;
4071
4072 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004073 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004074 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 }
4076 return 0;
4077 }
4078 } finally {
4079 Binder.restoreCallingIdentity(callingId);
4080 }
4081 }
4082
4083 @Override
4084 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4085 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4086 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004087 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4089 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4090 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004091 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 || activity.voiceSession != null) {
4093 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4094 return;
4095 }
4096 if (activity.pendingVoiceInteractionStart) {
4097 Slog.w(TAG, "Pending start of voice interaction already.");
4098 return;
4099 }
4100 activity.pendingVoiceInteractionStart = true;
4101 }
4102 LocalServices.getService(VoiceInteractionManagerInternal.class)
4103 .startLocalVoiceInteraction(callingActivity, options);
4104 }
4105
4106 @Override
4107 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4108 LocalServices.getService(VoiceInteractionManagerInternal.class)
4109 .stopLocalVoiceInteraction(callingActivity);
4110 }
4111
4112 @Override
4113 public boolean supportsLocalVoiceInteraction() {
4114 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4115 .supportsLocalVoiceInteraction();
4116 }
4117
4118 /** Notifies all listeners when the pinned stack animation starts. */
4119 @Override
4120 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004121 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 }
4123
4124 /** Notifies all listeners when the pinned stack animation ends. */
4125 @Override
4126 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004127 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004128 }
4129
4130 @Override
4131 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004132 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 final long ident = Binder.clearCallingIdentity();
4134 try {
4135 synchronized (mGlobalLock) {
4136 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4137 }
4138 } finally {
4139 Binder.restoreCallingIdentity(ident);
4140 }
4141 }
4142
4143 @Override
4144 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004145 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146
4147 synchronized (mGlobalLock) {
4148 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004149 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 // Call might come when display is not yet added or has already been removed.
4151 if (DEBUG_CONFIGURATION) {
4152 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4153 + displayId);
4154 }
4155 return false;
4156 }
4157
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004160 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161 }
4162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004163 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004164 final Message msg = PooledLambda.obtainMessage(
4165 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4166 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 }
4168
4169 final long origId = Binder.clearCallingIdentity();
4170 try {
4171 if (values != null) {
4172 Settings.System.clearConfiguration(values);
4173 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004174 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004175 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4176 return mTmpUpdateConfigurationResult.changes != 0;
4177 } finally {
4178 Binder.restoreCallingIdentity(origId);
4179 }
4180 }
4181 }
4182
4183 @Override
4184 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004185 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186
4187 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004190 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004191 }
4192
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004193 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004194 final Message msg = PooledLambda.obtainMessage(
4195 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4196 DEFAULT_DISPLAY);
4197 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198 }
4199
4200 final long origId = Binder.clearCallingIdentity();
4201 try {
4202 if (values != null) {
4203 Settings.System.clearConfiguration(values);
4204 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 UserHandle.USER_NULL, false /* deferResume */,
4207 mTmpUpdateConfigurationResult);
4208 return mTmpUpdateConfigurationResult.changes != 0;
4209 } finally {
4210 Binder.restoreCallingIdentity(origId);
4211 }
4212 }
4213 }
4214
4215 @Override
4216 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4217 CharSequence message) {
4218 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004219 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4221 }
4222 final long callingId = Binder.clearCallingIdentity();
4223 try {
4224 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004225 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004226 }
4227 } finally {
4228 Binder.restoreCallingIdentity(callingId);
4229 }
4230 }
4231
4232 @Override
4233 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004234 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004235 "cancelTaskWindowTransition()");
4236 final long ident = Binder.clearCallingIdentity();
4237 try {
4238 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004239 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 MATCH_TASK_IN_STACKS_ONLY);
4241 if (task == null) {
4242 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4243 return;
4244 }
4245 task.cancelWindowTransition();
4246 }
4247 } finally {
4248 Binder.restoreCallingIdentity(ident);
4249 }
4250 }
4251
4252 @Override
4253 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004254 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004255 final long ident = Binder.clearCallingIdentity();
4256 try {
4257 final TaskRecord task;
4258 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004259 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004260 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4261 if (task == null) {
4262 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4263 return null;
4264 }
4265 }
4266 // Don't call this while holding the lock as this operation might hit the disk.
4267 return task.getSnapshot(reducedResolution);
4268 } finally {
4269 Binder.restoreCallingIdentity(ident);
4270 }
4271 }
4272
4273 @Override
4274 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4275 synchronized (mGlobalLock) {
4276 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4277 if (r == null) {
4278 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4279 + token);
4280 return;
4281 }
4282 final long origId = Binder.clearCallingIdentity();
4283 try {
4284 r.setDisablePreviewScreenshots(disable);
4285 } finally {
4286 Binder.restoreCallingIdentity(origId);
4287 }
4288 }
4289 }
4290
4291 /** Return the user id of the last resumed activity. */
4292 @Override
4293 public @UserIdInt
4294 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4297 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004298 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004301 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 }
4303 }
4304
4305 @Override
4306 public void updateLockTaskFeatures(int userId, int flags) {
4307 final int callingUid = Binder.getCallingUid();
4308 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004309 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 "updateLockTaskFeatures()");
4311 }
4312 synchronized (mGlobalLock) {
4313 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4314 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004315 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 }
4317 }
4318
4319 @Override
4320 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4321 synchronized (mGlobalLock) {
4322 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4323 if (r == null) {
4324 return;
4325 }
4326 final long origId = Binder.clearCallingIdentity();
4327 try {
4328 r.setShowWhenLocked(showWhenLocked);
4329 } finally {
4330 Binder.restoreCallingIdentity(origId);
4331 }
4332 }
4333 }
4334
4335 @Override
4336 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4337 synchronized (mGlobalLock) {
4338 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4339 if (r == null) {
4340 return;
4341 }
4342 final long origId = Binder.clearCallingIdentity();
4343 try {
4344 r.setTurnScreenOn(turnScreenOn);
4345 } finally {
4346 Binder.restoreCallingIdentity(origId);
4347 }
4348 }
4349 }
4350
4351 @Override
4352 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004353 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 "registerRemoteAnimations");
4355 definition.setCallingPid(Binder.getCallingPid());
4356 synchronized (mGlobalLock) {
4357 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4358 if (r == null) {
4359 return;
4360 }
4361 final long origId = Binder.clearCallingIdentity();
4362 try {
4363 r.registerRemoteAnimations(definition);
4364 } finally {
4365 Binder.restoreCallingIdentity(origId);
4366 }
4367 }
4368 }
4369
4370 @Override
4371 public void registerRemoteAnimationForNextActivityStart(String packageName,
4372 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004373 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004374 "registerRemoteAnimationForNextActivityStart");
4375 adapter.setCallingPid(Binder.getCallingPid());
4376 synchronized (mGlobalLock) {
4377 final long origId = Binder.clearCallingIdentity();
4378 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004379 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 packageName, adapter);
4381 } finally {
4382 Binder.restoreCallingIdentity(origId);
4383 }
4384 }
4385 }
4386
4387 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4388 @Override
4389 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4390 synchronized (mGlobalLock) {
4391 final long origId = Binder.clearCallingIdentity();
4392 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004393 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 } finally {
4395 Binder.restoreCallingIdentity(origId);
4396 }
4397 }
4398 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004399
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004400 @Override
4401 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004402 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004403 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004404 final int pid = Binder.getCallingPid();
4405 final WindowProcessController wpc = mPidMap.get(pid);
4406 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004407 }
4408 }
4409
4410 @Override
4411 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004413 != PERMISSION_GRANTED) {
4414 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4415 + Binder.getCallingPid()
4416 + ", uid=" + Binder.getCallingUid()
4417 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4418 Slog.w(TAG, msg);
4419 throw new SecurityException(msg);
4420 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004422 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004423 final int pid = Binder.getCallingPid();
4424 final WindowProcessController proc = mPidMap.get(pid);
4425 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004426 }
4427 }
4428
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004429 @Override
4430 public void stopAppSwitches() {
4431 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4432 synchronized (mGlobalLock) {
4433 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4434 mDidAppSwitch = false;
4435 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4436 }
4437 }
4438
4439 @Override
4440 public void resumeAppSwitches() {
4441 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4442 synchronized (mGlobalLock) {
4443 // Note that we don't execute any pending app switches... we will
4444 // let those wait until either the timeout, or the next start
4445 // activity request.
4446 mAppSwitchesAllowedTime = 0;
4447 }
4448 }
4449
4450 void onStartActivitySetDidAppSwitch() {
4451 if (mDidAppSwitch) {
4452 // This is the second allowed switch since we stopped switches, so now just generally
4453 // allow switches. Use case:
4454 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4455 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4456 // anyone to switch again).
4457 mAppSwitchesAllowedTime = 0;
4458 } else {
4459 mDidAppSwitch = true;
4460 }
4461 }
4462
4463 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004464 boolean shouldDisableNonVrUiLocked() {
4465 return mVrController.shouldDisableNonVrUiLocked();
4466 }
4467
Wale Ogunwale53783742018-09-16 10:21:51 -07004468 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004469 // VR apps are expected to run in a main display. If an app is turning on VR for
4470 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4471 // fullscreen stack before enabling VR Mode.
4472 // TODO: The goal of this code is to keep the VR app on the main display. When the
4473 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4474 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4475 // option would be a better choice here.
4476 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4477 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4478 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004479 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004480 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004481 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004482 }
4483 mH.post(() -> {
4484 if (!mVrController.onVrModeChanged(r)) {
4485 return;
4486 }
4487 synchronized (mGlobalLock) {
4488 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4489 mWindowManager.disableNonVrUi(disableNonVrUi);
4490 if (disableNonVrUi) {
4491 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4492 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004493 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004494 }
4495 }
4496 });
4497 }
4498
Wale Ogunwale53783742018-09-16 10:21:51 -07004499 @Override
4500 public int getPackageScreenCompatMode(String packageName) {
4501 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4502 synchronized (mGlobalLock) {
4503 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4504 }
4505 }
4506
4507 @Override
4508 public void setPackageScreenCompatMode(String packageName, int mode) {
4509 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4510 "setPackageScreenCompatMode");
4511 synchronized (mGlobalLock) {
4512 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4513 }
4514 }
4515
4516 @Override
4517 public boolean getPackageAskScreenCompat(String packageName) {
4518 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4519 synchronized (mGlobalLock) {
4520 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4521 }
4522 }
4523
4524 @Override
4525 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4526 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4527 "setPackageAskScreenCompat");
4528 synchronized (mGlobalLock) {
4529 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4530 }
4531 }
4532
Wale Ogunwale64258362018-10-16 15:13:37 -07004533 public static String relaunchReasonToString(int relaunchReason) {
4534 switch (relaunchReason) {
4535 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4536 return "window_resize";
4537 case RELAUNCH_REASON_FREE_RESIZE:
4538 return "free_resize";
4539 default:
4540 return null;
4541 }
4542 }
4543
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004544 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004545 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004546 }
4547
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004548 /** Pokes the task persister. */
4549 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4550 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4551 }
4552
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004553 boolean isKeyguardLocked() {
4554 return mKeyguardController.isKeyguardLocked();
4555 }
4556
Garfield Tan01548632018-11-27 10:15:48 -08004557 /**
4558 * Clears launch params for the given package.
4559 * @param packageNames the names of the packages of which the launch params are to be cleared
4560 */
4561 @Override
4562 public void clearLaunchParamsForPackages(List<String> packageNames) {
4563 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4564 "clearLaunchParamsForPackages");
4565 synchronized (mGlobalLock) {
4566 for (int i = 0; i < packageNames.size(); ++i) {
4567 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4568 }
4569 }
4570 }
4571
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004572 /**
4573 * Makes the display with the given id a single task instance display. I.e the display can only
4574 * contain one task.
4575 */
4576 @Override
4577 public void setDisplayToSingleTaskInstance(int displayId) {
4578 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4579 "setDisplayToSingleTaskInstance");
4580 final long origId = Binder.clearCallingIdentity();
4581 try {
4582 final ActivityDisplay display =
4583 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4584 if (display != null) {
4585 display.setDisplayToSingleTaskInstance();
4586 }
4587 } finally {
4588 Binder.restoreCallingIdentity(origId);
4589 }
4590 }
4591
Wale Ogunwale31913b52018-10-13 08:29:31 -07004592 void dumpLastANRLocked(PrintWriter pw) {
4593 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4594 if (mLastANRState == null) {
4595 pw.println(" <no ANR has occurred since boot>");
4596 } else {
4597 pw.println(mLastANRState);
4598 }
4599 }
4600
4601 void dumpLastANRTracesLocked(PrintWriter pw) {
4602 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4603
4604 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4605 if (ArrayUtils.isEmpty(files)) {
4606 pw.println(" <no ANR has occurred since boot>");
4607 return;
4608 }
4609 // Find the latest file.
4610 File latest = null;
4611 for (File f : files) {
4612 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4613 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004614 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004615 }
4616 pw.print("File: ");
4617 pw.print(latest.getName());
4618 pw.println();
4619 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4620 String line;
4621 while ((line = in.readLine()) != null) {
4622 pw.println(line);
4623 }
4624 } catch (IOException e) {
4625 pw.print("Unable to read: ");
4626 pw.print(e);
4627 pw.println();
4628 }
4629 }
4630
4631 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4632 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4633 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4634 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4635 }
4636
4637 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4638 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4639 pw.println(header);
4640
Wale Ogunwaled32da472018-11-16 07:19:28 -08004641 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004642 dumpPackage);
4643 boolean needSep = printedAnything;
4644
4645 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004646 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004647 " ResumedActivity: ");
4648 if (printed) {
4649 printedAnything = true;
4650 needSep = false;
4651 }
4652
4653 if (dumpPackage == null) {
4654 if (needSep) {
4655 pw.println();
4656 }
4657 printedAnything = true;
4658 mStackSupervisor.dump(pw, " ");
4659 }
4660
4661 if (!printedAnything) {
4662 pw.println(" (nothing)");
4663 }
4664 }
4665
4666 void dumpActivityContainersLocked(PrintWriter pw) {
4667 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004668 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004669 pw.println(" ");
4670 }
4671
4672 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4673 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4674 getActivityStartController().dump(pw, "", dumpPackage);
4675 }
4676
4677 /**
4678 * There are three things that cmd can be:
4679 * - a flattened component name that matches an existing activity
4680 * - the cmd arg isn't the flattened component name of an existing activity:
4681 * dump all activity whose component contains the cmd as a substring
4682 * - A hex number of the ActivityRecord object instance.
4683 *
4684 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4685 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4686 */
4687 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4688 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4689 ArrayList<ActivityRecord> activities;
4690
4691 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004692 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004693 dumpFocusedStackOnly);
4694 }
4695
4696 if (activities.size() <= 0) {
4697 return false;
4698 }
4699
4700 String[] newArgs = new String[args.length - opti];
4701 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4702
4703 TaskRecord lastTask = null;
4704 boolean needSep = false;
4705 for (int i = activities.size() - 1; i >= 0; i--) {
4706 ActivityRecord r = activities.get(i);
4707 if (needSep) {
4708 pw.println();
4709 }
4710 needSep = true;
4711 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004712 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004713 if (lastTask != task) {
4714 lastTask = task;
4715 pw.print("TASK "); pw.print(lastTask.affinity);
4716 pw.print(" id="); pw.print(lastTask.taskId);
4717 pw.print(" userId="); pw.println(lastTask.userId);
4718 if (dumpAll) {
4719 lastTask.dump(pw, " ");
4720 }
4721 }
4722 }
4723 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4724 }
4725 return true;
4726 }
4727
4728 /**
4729 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4730 * there is a thread associated with the activity.
4731 */
4732 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4733 final ActivityRecord r, String[] args, boolean dumpAll) {
4734 String innerPrefix = prefix + " ";
4735 synchronized (mGlobalLock) {
4736 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4737 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4738 pw.print(" pid=");
4739 if (r.hasProcess()) pw.println(r.app.getPid());
4740 else pw.println("(not running)");
4741 if (dumpAll) {
4742 r.dump(pw, innerPrefix);
4743 }
4744 }
4745 if (r.attachedToProcess()) {
4746 // flush anything that is already in the PrintWriter since the thread is going
4747 // to write to the file descriptor directly
4748 pw.flush();
4749 try {
4750 TransferPipe tp = new TransferPipe();
4751 try {
4752 r.app.getThread().dumpActivity(tp.getWriteFd(),
4753 r.appToken, innerPrefix, args);
4754 tp.go(fd);
4755 } finally {
4756 tp.kill();
4757 }
4758 } catch (IOException e) {
4759 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4760 } catch (RemoteException e) {
4761 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4762 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004763 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004764 }
4765
sanryhuang498e77e2018-12-06 14:57:01 +08004766 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4767 boolean testPssMode) {
4768 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4769 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4770 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004771 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004772 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4773 st.toString());
4774 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004775 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4776 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4777 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004778 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4779 testPssMode);
4780 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 }
4782
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004783 int getCurrentUserId() {
4784 return mAmInternal.getCurrentUserId();
4785 }
4786
4787 private void enforceNotIsolatedCaller(String caller) {
4788 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4789 throw new SecurityException("Isolated process not allowed to call " + caller);
4790 }
4791 }
4792
Wale Ogunwalef6733932018-06-27 05:14:34 -07004793 public Configuration getConfiguration() {
4794 Configuration ci;
4795 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004796 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004797 ci.userSetLocale = false;
4798 }
4799 return ci;
4800 }
4801
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004802 /**
4803 * Current global configuration information. Contains general settings for the entire system,
4804 * also corresponds to the merged configuration of the default display.
4805 */
4806 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004807 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004808 }
4809
4810 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4811 boolean initLocale) {
4812 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4813 }
4814
4815 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4816 boolean initLocale, boolean deferResume) {
4817 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4818 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4819 UserHandle.USER_NULL, deferResume);
4820 }
4821
Wale Ogunwale59507092018-10-29 09:00:30 -07004822 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004823 final long origId = Binder.clearCallingIdentity();
4824 try {
4825 synchronized (mGlobalLock) {
4826 updateConfigurationLocked(values, null, false, true, userId,
4827 false /* deferResume */);
4828 }
4829 } finally {
4830 Binder.restoreCallingIdentity(origId);
4831 }
4832 }
4833
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004834 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4835 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4836 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4837 deferResume, null /* result */);
4838 }
4839
4840 /**
4841 * Do either or both things: (1) change the current configuration, and (2)
4842 * make sure the given activity is running with the (now) current
4843 * configuration. Returns true if the activity has been left running, or
4844 * false if <var>starting</var> is being destroyed to match the new
4845 * configuration.
4846 *
4847 * @param userId is only used when persistent parameter is set to true to persist configuration
4848 * for that particular user
4849 */
4850 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4851 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4852 ActivityTaskManagerService.UpdateConfigurationResult result) {
4853 int changes = 0;
4854 boolean kept = true;
4855
4856 if (mWindowManager != null) {
4857 mWindowManager.deferSurfaceLayout();
4858 }
4859 try {
4860 if (values != null) {
4861 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4862 deferResume);
4863 }
4864
4865 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4866 } finally {
4867 if (mWindowManager != null) {
4868 mWindowManager.continueSurfaceLayout();
4869 }
4870 }
4871
4872 if (result != null) {
4873 result.changes = changes;
4874 result.activityRelaunched = !kept;
4875 }
4876 return kept;
4877 }
4878
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004879 /** Update default (global) configuration and notify listeners about changes. */
4880 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4881 boolean persistent, int userId, boolean deferResume) {
4882 mTempConfig.setTo(getGlobalConfiguration());
4883 final int changes = mTempConfig.updateFrom(values);
4884 if (changes == 0) {
4885 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4886 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4887 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4888 // (even if there are no actual changes) to unfreeze the window.
4889 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4890 return 0;
4891 }
4892
4893 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4894 "Updating global configuration to: " + values);
4895
4896 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4897 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4898 values.colorMode,
4899 values.densityDpi,
4900 values.fontScale,
4901 values.hardKeyboardHidden,
4902 values.keyboard,
4903 values.keyboardHidden,
4904 values.mcc,
4905 values.mnc,
4906 values.navigation,
4907 values.navigationHidden,
4908 values.orientation,
4909 values.screenHeightDp,
4910 values.screenLayout,
4911 values.screenWidthDp,
4912 values.smallestScreenWidthDp,
4913 values.touchscreen,
4914 values.uiMode);
4915
4916
4917 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4918 final LocaleList locales = values.getLocales();
4919 int bestLocaleIndex = 0;
4920 if (locales.size() > 1) {
4921 if (mSupportedSystemLocales == null) {
4922 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4923 }
4924 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4925 }
4926 SystemProperties.set("persist.sys.locale",
4927 locales.get(bestLocaleIndex).toLanguageTag());
4928 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004929
4930 final Message m = PooledLambda.obtainMessage(
4931 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4932 locales.get(bestLocaleIndex));
4933 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004934 }
4935
Yunfan Chen75157d72018-07-27 14:47:21 +09004936 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004937
4938 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004939 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004940
4941 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4942 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004943 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004944
4945 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004946 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004947
4948 AttributeCache ac = AttributeCache.instance();
4949 if (ac != null) {
4950 ac.updateConfiguration(mTempConfig);
4951 }
4952
4953 // Make sure all resources in our process are updated right now, so that anyone who is going
4954 // to retrieve resource values after we return will be sure to get the new ones. This is
4955 // especially important during boot, where the first config change needs to guarantee all
4956 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004957 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004958
4959 // We need another copy of global config because we're scheduling some calls instead of
4960 // running them in place. We need to be sure that object we send will be handled unchanged.
4961 final Configuration configCopy = new Configuration(mTempConfig);
4962 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004963 final Message msg = PooledLambda.obtainMessage(
4964 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4965 this, userId, configCopy);
4966 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004967 }
4968
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004969 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004970 final int pid = mPidMap.keyAt(i);
4971 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004972 if (DEBUG_CONFIGURATION) {
4973 Slog.v(TAG_CONFIGURATION, "Update process config of "
4974 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004975 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004976 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004977 }
4978
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004979 final Message msg = PooledLambda.obtainMessage(
4980 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4981 mAmInternal, changes, initLocale);
4982 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004983
4984 // Override configuration of the default display duplicates global config, so we need to
4985 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004986 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004987 DEFAULT_DISPLAY);
4988
4989 return changes;
4990 }
4991
4992 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4993 boolean deferResume, int displayId) {
4994 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4995 displayId, null /* result */);
4996 }
4997
4998 /**
4999 * Updates override configuration specific for the selected display. If no config is provided,
5000 * new one will be computed in WM based on current display info.
5001 */
5002 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5003 ActivityRecord starting, boolean deferResume, int displayId,
5004 ActivityTaskManagerService.UpdateConfigurationResult result) {
5005 int changes = 0;
5006 boolean kept = true;
5007
5008 if (mWindowManager != null) {
5009 mWindowManager.deferSurfaceLayout();
5010 }
5011 try {
5012 if (values != null) {
5013 if (displayId == DEFAULT_DISPLAY) {
5014 // Override configuration of the default display duplicates global config, so
5015 // we're calling global config update instead for default display. It will also
5016 // apply the correct override config.
5017 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5018 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5019 } else {
5020 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5021 }
5022 }
5023
5024 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5025 } finally {
5026 if (mWindowManager != null) {
5027 mWindowManager.continueSurfaceLayout();
5028 }
5029 }
5030
5031 if (result != null) {
5032 result.changes = changes;
5033 result.activityRelaunched = !kept;
5034 }
5035 return kept;
5036 }
5037
5038 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5039 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005040 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005041 final int changes = mTempConfig.updateFrom(values);
5042 if (changes != 0) {
5043 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5044 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005045 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005046
5047 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5048 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005049 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005050
Wale Ogunwale5c918702018-10-18 11:06:33 -07005051 // Post message to start process to avoid possible deadlock of calling into AMS with
5052 // the ATMS lock held.
5053 final Message msg = PooledLambda.obtainMessage(
5054 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5055 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5056 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005057 }
5058 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059 return changes;
5060 }
5061
Wale Ogunwalef6733932018-06-27 05:14:34 -07005062 private void updateEventDispatchingLocked(boolean booted) {
5063 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5064 }
5065
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005066 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5067 final ContentResolver resolver = mContext.getContentResolver();
5068 Settings.System.putConfigurationForUser(resolver, config, userId);
5069 }
5070
5071 private void sendLocaleToMountDaemonMsg(Locale l) {
5072 try {
5073 IBinder service = ServiceManager.getService("mount");
5074 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5075 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5076 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5077 } catch (RemoteException e) {
5078 Log.e(TAG, "Error storing locale for decryption UI", e);
5079 }
5080 }
5081
Alison Cichowlas3e340502018-08-07 17:15:01 -04005082 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5083 mStartActivitySources.remove(permissionToken);
5084 mExpiredStartAsCallerTokens.add(permissionToken);
5085 }
5086
5087 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5088 mExpiredStartAsCallerTokens.remove(permissionToken);
5089 }
5090
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005091 boolean isActivityStartsLoggingEnabled() {
5092 return mAmInternal.isActivityStartsLoggingEnabled();
5093 }
5094
Michal Karpinski8596ded2018-11-14 14:43:48 +00005095 boolean isBackgroundActivityStartsEnabled() {
5096 return mAmInternal.isBackgroundActivityStartsEnabled();
5097 }
5098
Wale Ogunwalef6733932018-06-27 05:14:34 -07005099 void enableScreenAfterBoot(boolean booted) {
5100 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5101 SystemClock.uptimeMillis());
5102 mWindowManager.enableScreenAfterBoot();
5103
5104 synchronized (mGlobalLock) {
5105 updateEventDispatchingLocked(booted);
5106 }
5107 }
5108
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005109 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5110 if (r == null || !r.hasProcess()) {
5111 return KEY_DISPATCHING_TIMEOUT_MS;
5112 }
5113 return getInputDispatchingTimeoutLocked(r.app);
5114 }
5115
5116 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005117 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005118 }
5119
Wale Ogunwalef6733932018-06-27 05:14:34 -07005120 /**
5121 * Decide based on the configuration whether we should show the ANR,
5122 * crash, etc dialogs. The idea is that if there is no affordance to
5123 * press the on-screen buttons, or the user experience would be more
5124 * greatly impacted than the crash itself, we shouldn't show the dialog.
5125 *
5126 * A thought: SystemUI might also want to get told about this, the Power
5127 * dialog / global actions also might want different behaviors.
5128 */
5129 private void updateShouldShowDialogsLocked(Configuration config) {
5130 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5131 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5132 && config.navigation == Configuration.NAVIGATION_NONAV);
5133 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5134 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5135 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5136 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5137 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5138 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5139 HIDE_ERROR_DIALOGS, 0) != 0;
5140 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5141 }
5142
5143 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5144 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5145 FONT_SCALE, 1.0f, userId);
5146
5147 synchronized (this) {
5148 if (getGlobalConfiguration().fontScale == scaleFactor) {
5149 return;
5150 }
5151
5152 final Configuration configuration
5153 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5154 configuration.fontScale = scaleFactor;
5155 updatePersistentConfiguration(configuration, userId);
5156 }
5157 }
5158
5159 // Actually is sleeping or shutting down or whatever else in the future
5160 // is an inactive state.
5161 boolean isSleepingOrShuttingDownLocked() {
5162 return isSleepingLocked() || mShuttingDown;
5163 }
5164
5165 boolean isSleepingLocked() {
5166 return mSleeping;
5167 }
5168
Riddle Hsu16567132018-08-16 21:37:47 +08005169 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005170 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005171 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005172 if (task.isActivityTypeStandard()) {
5173 if (mCurAppTimeTracker != r.appTimeTracker) {
5174 // We are switching app tracking. Complete the current one.
5175 if (mCurAppTimeTracker != null) {
5176 mCurAppTimeTracker.stop();
5177 mH.obtainMessage(
5178 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005179 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005180 mCurAppTimeTracker = null;
5181 }
5182 if (r.appTimeTracker != null) {
5183 mCurAppTimeTracker = r.appTimeTracker;
5184 startTimeTrackingFocusedActivityLocked();
5185 }
5186 } else {
5187 startTimeTrackingFocusedActivityLocked();
5188 }
5189 } else {
5190 r.appTimeTracker = null;
5191 }
5192 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5193 // TODO: Probably not, because we don't want to resume voice on switching
5194 // back to this activity
5195 if (task.voiceInteractor != null) {
5196 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5197 } else {
5198 finishRunningVoiceLocked();
5199
5200 if (mLastResumedActivity != null) {
5201 final IVoiceInteractionSession session;
5202
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005203 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005204 if (lastResumedActivityTask != null
5205 && lastResumedActivityTask.voiceSession != null) {
5206 session = lastResumedActivityTask.voiceSession;
5207 } else {
5208 session = mLastResumedActivity.voiceSession;
5209 }
5210
5211 if (session != null) {
5212 // We had been in a voice interaction session, but now focused has
5213 // move to something different. Just finish the session, we can't
5214 // return to it and retain the proper state and synchronization with
5215 // the voice interaction service.
5216 finishVoiceTask(session);
5217 }
5218 }
5219 }
5220
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005221 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5222 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005223 }
5224 updateResumedAppTrace(r);
5225 mLastResumedActivity = r;
5226
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005227 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005228
5229 applyUpdateLockStateLocked(r);
5230 applyUpdateVrModeLocked(r);
5231
5232 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005233 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005234 r == null ? "NULL" : r.shortComponentName,
5235 reason);
5236 }
5237
5238 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5239 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005240 final ActivityTaskManagerInternal.SleepToken token =
5241 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005242 updateSleepIfNeededLocked();
5243 return token;
5244 }
5245 }
5246
5247 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005248 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005249 final boolean wasSleeping = mSleeping;
5250 boolean updateOomAdj = false;
5251
5252 if (!shouldSleep) {
5253 // If wasSleeping is true, we need to wake up activity manager state from when
5254 // we started sleeping. In either case, we need to apply the sleep tokens, which
5255 // will wake up stacks or put them to sleep as appropriate.
5256 if (wasSleeping) {
5257 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005258 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5259 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005260 startTimeTrackingFocusedActivityLocked();
5261 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5262 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5263 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005264 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005265 if (wasSleeping) {
5266 updateOomAdj = true;
5267 }
5268 } else if (!mSleeping && shouldSleep) {
5269 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005270 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5271 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005272 if (mCurAppTimeTracker != null) {
5273 mCurAppTimeTracker.stop();
5274 }
5275 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5276 mStackSupervisor.goingToSleepLocked();
5277 updateResumedAppTrace(null /* resumed */);
5278 updateOomAdj = true;
5279 }
5280 if (updateOomAdj) {
5281 mH.post(mAmInternal::updateOomAdj);
5282 }
5283 }
5284
5285 void updateOomAdj() {
5286 mH.post(mAmInternal::updateOomAdj);
5287 }
5288
Wale Ogunwale53783742018-09-16 10:21:51 -07005289 void updateCpuStats() {
5290 mH.post(mAmInternal::updateCpuStats);
5291 }
5292
Hui Yu03d12402018-12-06 18:00:37 -08005293 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5294 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005295 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5296 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005297 mH.sendMessage(m);
5298 }
5299
Hui Yu03d12402018-12-06 18:00:37 -08005300 void updateActivityUsageStats(ActivityRecord activity, int event) {
5301 final Message m = PooledLambda.obtainMessage(
5302 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5303 activity.mActivityComponent, activity.mUserId, event, activity.appToken);
5304 mH.sendMessage(m);
5305 }
5306
Wale Ogunwale53783742018-09-16 10:21:51 -07005307 void setBooting(boolean booting) {
5308 mAmInternal.setBooting(booting);
5309 }
5310
5311 boolean isBooting() {
5312 return mAmInternal.isBooting();
5313 }
5314
5315 void setBooted(boolean booted) {
5316 mAmInternal.setBooted(booted);
5317 }
5318
5319 boolean isBooted() {
5320 return mAmInternal.isBooted();
5321 }
5322
5323 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5324 mH.post(() -> {
5325 if (finishBooting) {
5326 mAmInternal.finishBooting();
5327 }
5328 if (enableScreen) {
5329 mInternal.enableScreenAfterBoot(isBooted());
5330 }
5331 });
5332 }
5333
5334 void setHeavyWeightProcess(ActivityRecord root) {
5335 mHeavyWeightProcess = root.app;
5336 final Message m = PooledLambda.obtainMessage(
5337 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005338 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005339 mH.sendMessage(m);
5340 }
5341
5342 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5343 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5344 return;
5345 }
5346
5347 mHeavyWeightProcess = null;
5348 final Message m = PooledLambda.obtainMessage(
5349 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5350 proc.mUserId);
5351 mH.sendMessage(m);
5352 }
5353
5354 private void cancelHeavyWeightProcessNotification(int userId) {
5355 final INotificationManager inm = NotificationManager.getService();
5356 if (inm == null) {
5357 return;
5358 }
5359 try {
5360 inm.cancelNotificationWithTag("android", null,
5361 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5362 } catch (RuntimeException e) {
5363 Slog.w(TAG, "Error canceling notification for service", e);
5364 } catch (RemoteException e) {
5365 }
5366
5367 }
5368
5369 private void postHeavyWeightProcessNotification(
5370 WindowProcessController proc, Intent intent, int userId) {
5371 if (proc == null) {
5372 return;
5373 }
5374
5375 final INotificationManager inm = NotificationManager.getService();
5376 if (inm == null) {
5377 return;
5378 }
5379
5380 try {
5381 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5382 String text = mContext.getString(R.string.heavy_weight_notification,
5383 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5384 Notification notification =
5385 new Notification.Builder(context,
5386 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5387 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5388 .setWhen(0)
5389 .setOngoing(true)
5390 .setTicker(text)
5391 .setColor(mContext.getColor(
5392 com.android.internal.R.color.system_notification_accent_color))
5393 .setContentTitle(text)
5394 .setContentText(
5395 mContext.getText(R.string.heavy_weight_notification_detail))
5396 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5397 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5398 new UserHandle(userId)))
5399 .build();
5400 try {
5401 inm.enqueueNotificationWithTag("android", "android", null,
5402 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5403 } catch (RuntimeException e) {
5404 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5405 } catch (RemoteException e) {
5406 }
5407 } catch (PackageManager.NameNotFoundException e) {
5408 Slog.w(TAG, "Unable to create context for heavy notification", e);
5409 }
5410
5411 }
5412
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005413 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5414 IBinder token, String resultWho, int requestCode, Intent[] intents,
5415 String[] resolvedTypes, int flags, Bundle bOptions) {
5416
5417 ActivityRecord activity = null;
5418 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5419 activity = ActivityRecord.isInStackLocked(token);
5420 if (activity == null) {
5421 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5422 return null;
5423 }
5424 if (activity.finishing) {
5425 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5426 return null;
5427 }
5428 }
5429
5430 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5431 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5432 bOptions);
5433 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5434 if (noCreate) {
5435 return rec;
5436 }
5437 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5438 if (activity.pendingResults == null) {
5439 activity.pendingResults = new HashSet<>();
5440 }
5441 activity.pendingResults.add(rec.ref);
5442 }
5443 return rec;
5444 }
5445
Andrii Kulian52d255c2018-07-13 11:32:19 -07005446 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005447 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005448 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5450 mCurAppTimeTracker.start(resumedActivity.packageName);
5451 }
5452 }
5453
5454 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5455 if (mTracedResumedActivity != null) {
5456 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5457 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5458 }
5459 if (resumed != null) {
5460 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5461 constructResumedTraceName(resumed.packageName), 0);
5462 }
5463 mTracedResumedActivity = resumed;
5464 }
5465
5466 private String constructResumedTraceName(String packageName) {
5467 return "focused app: " + packageName;
5468 }
5469
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005470 /** Applies latest configuration and/or visibility updates if needed. */
5471 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5472 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005473 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005474 // mainStack is null during startup.
5475 if (mainStack != null) {
5476 if (changes != 0 && starting == null) {
5477 // If the configuration changed, and the caller is not already
5478 // in the process of starting an activity, then find the top
5479 // activity to check if its configuration needs to change.
5480 starting = mainStack.topRunningActivityLocked();
5481 }
5482
5483 if (starting != null) {
5484 kept = starting.ensureActivityConfiguration(changes,
5485 false /* preserveWindow */);
5486 // And we need to make sure at this point that all other activities
5487 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005488 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005489 !PRESERVE_WINDOWS);
5490 }
5491 }
5492
5493 return kept;
5494 }
5495
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005496 void scheduleAppGcsLocked() {
5497 mH.post(() -> mAmInternal.scheduleAppGcs());
5498 }
5499
Wale Ogunwale53783742018-09-16 10:21:51 -07005500 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5501 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5502 }
5503
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005504 /**
5505 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5506 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5507 * on demand.
5508 */
5509 IPackageManager getPackageManager() {
5510 return AppGlobals.getPackageManager();
5511 }
5512
5513 PackageManagerInternal getPackageManagerInternalLocked() {
5514 if (mPmInternal == null) {
5515 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5516 }
5517 return mPmInternal;
5518 }
5519
Wale Ogunwale008163e2018-07-23 23:11:08 -07005520 AppWarnings getAppWarningsLocked() {
5521 return mAppWarnings;
5522 }
5523
Wale Ogunwale214f3482018-10-04 11:00:47 -07005524 Intent getHomeIntent() {
5525 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5526 intent.setComponent(mTopComponent);
5527 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5528 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5529 intent.addCategory(Intent.CATEGORY_HOME);
5530 }
5531 return intent;
5532 }
5533
Chilun2ef71f72018-11-16 17:57:15 +08005534 /**
5535 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5536 * activities.
5537 *
5538 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5539 * component defined in config_secondaryHomeComponent.
5540 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5541 */
5542 Intent getSecondaryHomeIntent(String preferredPackage) {
5543 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5544 if (preferredPackage == null) {
5545 // Using the component stored in config if no package name.
5546 final String secondaryHomeComponent = mContext.getResources().getString(
5547 com.android.internal.R.string.config_secondaryHomeComponent);
5548 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5549 } else {
5550 intent.setPackage(preferredPackage);
5551 }
5552 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5553 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5554 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5555 }
5556 return intent;
5557 }
5558
Wale Ogunwale214f3482018-10-04 11:00:47 -07005559 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5560 if (info == null) return null;
5561 ApplicationInfo newInfo = new ApplicationInfo(info);
5562 newInfo.initForUser(userId);
5563 return newInfo;
5564 }
5565
Wale Ogunwale9c103022018-10-18 07:44:54 -07005566 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005567 if (uid == SYSTEM_UID) {
5568 // The system gets to run in any process. If there are multiple processes with the same
5569 // uid, just pick the first (this should never happen).
5570 final SparseArray<WindowProcessController> procs =
5571 mProcessNames.getMap().get(processName);
5572 if (procs == null) return null;
5573 final int procCount = procs.size();
5574 for (int i = 0; i < procCount; i++) {
5575 final int procUid = procs.keyAt(i);
5576 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5577 // Don't use an app process or different user process for system component.
5578 continue;
5579 }
5580 return procs.valueAt(i);
5581 }
5582 }
5583
5584 return mProcessNames.get(processName, uid);
5585 }
5586
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005587 WindowProcessController getProcessController(IApplicationThread thread) {
5588 if (thread == null) {
5589 return null;
5590 }
5591
5592 final IBinder threadBinder = thread.asBinder();
5593 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5594 for (int i = pmap.size()-1; i >= 0; i--) {
5595 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5596 for (int j = procs.size() - 1; j >= 0; j--) {
5597 final WindowProcessController proc = procs.valueAt(j);
5598 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5599 return proc;
5600 }
5601 }
5602 }
5603
5604 return null;
5605 }
5606
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005607 int getUidStateLocked(int uid) {
5608 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5609 }
5610
Wale Ogunwale9de19442018-10-18 19:05:03 -07005611 /**
5612 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5613 * the whitelist
5614 */
5615 String getPendingTempWhitelistTagForUidLocked(int uid) {
5616 return mPendingTempWhitelist.get(uid);
5617 }
5618
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005619 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5620 if (true || Build.IS_USER) {
5621 return;
5622 }
5623
5624 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5625 StrictMode.allowThreadDiskWrites();
5626 try {
5627 File tracesDir = new File("/data/anr");
5628 File tracesFile = null;
5629 try {
5630 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5631
5632 StringBuilder sb = new StringBuilder();
5633 Time tobj = new Time();
5634 tobj.set(System.currentTimeMillis());
5635 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5636 sb.append(": ");
5637 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5638 sb.append(" since ");
5639 sb.append(msg);
5640 FileOutputStream fos = new FileOutputStream(tracesFile);
5641 fos.write(sb.toString().getBytes());
5642 if (app == null) {
5643 fos.write("\n*** No application process!".getBytes());
5644 }
5645 fos.close();
5646 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5647 } catch (IOException e) {
5648 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5649 return;
5650 }
5651
5652 if (app != null && app.getPid() > 0) {
5653 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5654 firstPids.add(app.getPid());
5655 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5656 }
5657
5658 File lastTracesFile = null;
5659 File curTracesFile = null;
5660 for (int i=9; i>=0; i--) {
5661 String name = String.format(Locale.US, "slow%02d.txt", i);
5662 curTracesFile = new File(tracesDir, name);
5663 if (curTracesFile.exists()) {
5664 if (lastTracesFile != null) {
5665 curTracesFile.renameTo(lastTracesFile);
5666 } else {
5667 curTracesFile.delete();
5668 }
5669 }
5670 lastTracesFile = curTracesFile;
5671 }
5672 tracesFile.renameTo(curTracesFile);
5673 } finally {
5674 StrictMode.setThreadPolicy(oldPolicy);
5675 }
5676 }
5677
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005678 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005679 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005680
5681
Wale Ogunwale98875612018-10-12 07:53:02 -07005682 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5683 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005684
Riddle Hsud93a6c42018-11-29 21:50:06 +08005685 H(Looper looper) {
5686 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005687 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005688
5689 @Override
5690 public void handleMessage(Message msg) {
5691 switch (msg.what) {
5692 case REPORT_TIME_TRACKER_MSG: {
5693 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5694 tracker.deliverResult(mContext);
5695 } break;
5696 }
5697 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005698 }
5699
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005700 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005701 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005702
5703 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005704 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005705 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005706
5707 @Override
5708 public void handleMessage(Message msg) {
5709 switch (msg.what) {
5710 case DISMISS_DIALOG_UI_MSG: {
5711 final Dialog d = (Dialog) msg.obj;
5712 d.dismiss();
5713 break;
5714 }
5715 }
5716 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005717 }
5718
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005719 final class LocalService extends ActivityTaskManagerInternal {
5720 @Override
5721 public SleepToken acquireSleepToken(String tag, int displayId) {
5722 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005723 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005724 }
5725
5726 @Override
5727 public ComponentName getHomeActivityForUser(int userId) {
5728 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005729 final ActivityRecord homeActivity =
5730 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005731 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005732 }
5733 }
5734
5735 @Override
5736 public void onLocalVoiceInteractionStarted(IBinder activity,
5737 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5738 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005739 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005740 }
5741 }
5742
5743 @Override
5744 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5745 synchronized (mGlobalLock) {
5746 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5747 reasons, timestamp);
5748 }
5749 }
5750
5751 @Override
5752 public void notifyAppTransitionFinished() {
5753 synchronized (mGlobalLock) {
5754 mStackSupervisor.notifyAppTransitionDone();
5755 }
5756 }
5757
5758 @Override
5759 public void notifyAppTransitionCancelled() {
5760 synchronized (mGlobalLock) {
5761 mStackSupervisor.notifyAppTransitionDone();
5762 }
5763 }
5764
5765 @Override
5766 public List<IBinder> getTopVisibleActivities() {
5767 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005768 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005769 }
5770 }
5771
5772 @Override
5773 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5774 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005775 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005776 }
5777 }
5778
5779 @Override
5780 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5781 Bundle bOptions) {
5782 Preconditions.checkNotNull(intents, "intents");
5783 final String[] resolvedTypes = new String[intents.length];
5784
5785 // UID of the package on user userId.
5786 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5787 // packageUid may not be initialized.
5788 int packageUid = 0;
5789 final long ident = Binder.clearCallingIdentity();
5790
5791 try {
5792 for (int i = 0; i < intents.length; i++) {
5793 resolvedTypes[i] =
5794 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5795 }
5796
5797 packageUid = AppGlobals.getPackageManager().getPackageUid(
5798 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5799 } catch (RemoteException e) {
5800 // Shouldn't happen.
5801 } finally {
5802 Binder.restoreCallingIdentity(ident);
5803 }
5804
5805 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005806 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005807 packageUid, packageName,
5808 intents, resolvedTypes, null /* resultTo */,
5809 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005810 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005811 }
5812 }
5813
5814 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005815 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5816 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5817 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5818 synchronized (mGlobalLock) {
5819 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5820 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5821 originatingPendingIntent);
5822 }
5823 }
5824
5825 @Override
5826 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5827 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5828 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5829 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5830 PendingIntentRecord originatingPendingIntent) {
5831 synchronized (mGlobalLock) {
5832 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5833 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5834 requestCode, startFlags, options, userId, inTask, reason,
5835 validateIncomingUser, originatingPendingIntent);
5836 }
5837 }
5838
5839 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005840 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5841 Intent intent, Bundle options, int userId) {
5842 return ActivityTaskManagerService.this.startActivityAsUser(
5843 caller, callerPacakge, intent,
5844 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5845 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5846 false /*validateIncomingUser*/);
5847 }
5848
5849 @Override
lumark588a3e82018-07-20 18:53:54 +08005850 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005851 synchronized (mGlobalLock) {
5852
5853 // We might change the visibilities here, so prepare an empty app transition which
5854 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005855 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005856 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005857 if (activityDisplay == null) {
5858 return;
5859 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005860 final DisplayContent dc = activityDisplay.mDisplayContent;
5861 final boolean wasTransitionSet =
5862 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005863 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005864 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005865 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005866 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005867
5868 // If there was a transition set already we don't want to interfere with it as we
5869 // might be starting it too early.
5870 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005871 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005872 }
5873 }
5874 if (callback != null) {
5875 callback.run();
5876 }
5877 }
5878
5879 @Override
5880 public void notifyKeyguardTrustedChanged() {
5881 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005882 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005883 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005884 }
5885 }
5886 }
5887
5888 /**
5889 * Called after virtual display Id is updated by
5890 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5891 * {@param vrVr2dDisplayId}.
5892 */
5893 @Override
5894 public void setVr2dDisplayId(int vr2dDisplayId) {
5895 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5896 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005897 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005898 }
5899 }
5900
5901 @Override
5902 public void setFocusedActivity(IBinder token) {
5903 synchronized (mGlobalLock) {
5904 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5905 if (r == null) {
5906 throw new IllegalArgumentException(
5907 "setFocusedActivity: No activity record matching token=" + token);
5908 }
Louis Chang19443452018-10-09 12:10:21 +08005909 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005910 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005911 }
5912 }
5913 }
5914
5915 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005916 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005917 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005918 }
5919
5920 @Override
5921 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005922 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005923 }
5924
5925 @Override
5926 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005927 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005928 }
5929
5930 @Override
5931 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5932 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5933 }
5934
5935 @Override
5936 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005937 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005938 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005939
5940 @Override
5941 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5942 synchronized (mGlobalLock) {
5943 mActiveVoiceInteractionServiceComponent = component;
5944 }
5945 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005946
5947 @Override
5948 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5949 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5950 return;
5951 }
5952 synchronized (mGlobalLock) {
5953 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5954 if (types == null) {
5955 if (uid < 0) {
5956 return;
5957 }
5958 types = new ArrayMap<>();
5959 mAllowAppSwitchUids.put(userId, types);
5960 }
5961 if (uid < 0) {
5962 types.remove(type);
5963 } else {
5964 types.put(type, uid);
5965 }
5966 }
5967 }
5968
5969 @Override
5970 public void onUserStopped(int userId) {
5971 synchronized (mGlobalLock) {
5972 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5973 mAllowAppSwitchUids.remove(userId);
5974 }
5975 }
5976
5977 @Override
5978 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5979 synchronized (mGlobalLock) {
5980 return ActivityTaskManagerService.this.isGetTasksAllowed(
5981 caller, callingPid, callingUid);
5982 }
5983 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005984
5985 @Override
5986 public void onProcessAdded(WindowProcessController proc) {
5987 synchronized (mGlobalLock) {
5988 mProcessNames.put(proc.mName, proc.mUid, proc);
5989 }
5990 }
5991
5992 @Override
5993 public void onProcessRemoved(String name, int uid) {
5994 synchronized (mGlobalLock) {
5995 mProcessNames.remove(name, uid);
5996 }
5997 }
5998
5999 @Override
6000 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6001 synchronized (mGlobalLock) {
6002 if (proc == mHomeProcess) {
6003 mHomeProcess = null;
6004 }
6005 if (proc == mPreviousProcess) {
6006 mPreviousProcess = null;
6007 }
6008 }
6009 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006010
6011 @Override
6012 public int getTopProcessState() {
6013 synchronized (mGlobalLock) {
6014 return mTopProcessState;
6015 }
6016 }
6017
6018 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006019 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6020 synchronized (mGlobalLock) {
6021 return proc == mHeavyWeightProcess;
6022 }
6023 }
6024
6025 @Override
6026 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6027 synchronized (mGlobalLock) {
6028 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6029 }
6030 }
6031
6032 @Override
6033 public void finishHeavyWeightApp() {
6034 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006035 if (mHeavyWeightProcess != null) {
6036 mHeavyWeightProcess.finishActivities();
6037 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006038 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6039 mHeavyWeightProcess);
6040 }
6041 }
6042
6043 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006044 public boolean isSleeping() {
6045 synchronized (mGlobalLock) {
6046 return isSleepingLocked();
6047 }
6048 }
6049
6050 @Override
6051 public boolean isShuttingDown() {
6052 synchronized (mGlobalLock) {
6053 return mShuttingDown;
6054 }
6055 }
6056
6057 @Override
6058 public boolean shuttingDown(boolean booted, int timeout) {
6059 synchronized (mGlobalLock) {
6060 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006061 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006062 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006063 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006064 return mStackSupervisor.shutdownLocked(timeout);
6065 }
6066 }
6067
6068 @Override
6069 public void enableScreenAfterBoot(boolean booted) {
6070 synchronized (mGlobalLock) {
6071 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6072 SystemClock.uptimeMillis());
6073 mWindowManager.enableScreenAfterBoot();
6074 updateEventDispatchingLocked(booted);
6075 }
6076 }
6077
6078 @Override
6079 public boolean showStrictModeViolationDialog() {
6080 synchronized (mGlobalLock) {
6081 return mShowDialogs && !mSleeping && !mShuttingDown;
6082 }
6083 }
6084
6085 @Override
6086 public void showSystemReadyErrorDialogsIfNeeded() {
6087 synchronized (mGlobalLock) {
6088 try {
6089 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6090 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6091 + " data partition or your device will be unstable.");
6092 mUiHandler.post(() -> {
6093 if (mShowDialogs) {
6094 AlertDialog d = new BaseErrorDialog(mUiContext);
6095 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6096 d.setCancelable(false);
6097 d.setTitle(mUiContext.getText(R.string.android_system_label));
6098 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6099 d.setButton(DialogInterface.BUTTON_POSITIVE,
6100 mUiContext.getText(R.string.ok),
6101 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6102 d.show();
6103 }
6104 });
6105 }
6106 } catch (RemoteException e) {
6107 }
6108
6109 if (!Build.isBuildConsistent()) {
6110 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6111 mUiHandler.post(() -> {
6112 if (mShowDialogs) {
6113 AlertDialog d = new BaseErrorDialog(mUiContext);
6114 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6115 d.setCancelable(false);
6116 d.setTitle(mUiContext.getText(R.string.android_system_label));
6117 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6118 d.setButton(DialogInterface.BUTTON_POSITIVE,
6119 mUiContext.getText(R.string.ok),
6120 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6121 d.show();
6122 }
6123 });
6124 }
6125 }
6126 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006127
6128 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006129 public void onProcessMapped(int pid, WindowProcessController proc) {
6130 synchronized (mGlobalLock) {
6131 mPidMap.put(pid, proc);
6132 }
6133 }
6134
6135 @Override
6136 public void onProcessUnMapped(int pid) {
6137 synchronized (mGlobalLock) {
6138 mPidMap.remove(pid);
6139 }
6140 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006141
6142 @Override
6143 public void onPackageDataCleared(String name) {
6144 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006145 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006146 mAppWarnings.onPackageDataCleared(name);
6147 }
6148 }
6149
6150 @Override
6151 public void onPackageUninstalled(String name) {
6152 synchronized (mGlobalLock) {
6153 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006154 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006155 }
6156 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006157
6158 @Override
6159 public void onPackageAdded(String name, boolean replacing) {
6160 synchronized (mGlobalLock) {
6161 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6162 }
6163 }
6164
6165 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006166 public void onPackageReplaced(ApplicationInfo aInfo) {
6167 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006168 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006169 }
6170 }
6171
6172 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006173 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6174 synchronized (mGlobalLock) {
6175 return compatibilityInfoForPackageLocked(ai);
6176 }
6177 }
6178
Yunfan Chen75157d72018-07-27 14:47:21 +09006179 /**
6180 * Set the corresponding display information for the process global configuration. To be
6181 * called when we need to show IME on a different display.
6182 *
6183 * @param pid The process id associated with the IME window.
6184 * @param displayId The ID of the display showing the IME.
6185 */
6186 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006187 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006188 if (pid == MY_PID || pid < 0) {
6189 if (DEBUG_CONFIGURATION) {
6190 Slog.w(TAG,
6191 "Trying to update display configuration for system/invalid process.");
6192 }
6193 return;
6194 }
6195 mH.post(() -> {
6196 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006197 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006198 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006199 if (activityDisplay == null) {
6200 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006201 if (DEBUG_CONFIGURATION) {
6202 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006203 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006204 }
6205 return;
6206 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006207 final WindowProcessController process = mPidMap.get(pid);
6208 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006209 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006210 Slog.w(TAG, "Trying to update display configuration for invalid "
6211 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006212 }
6213 return;
6214 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006215 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006216 }
6217 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006218
Yunfan Chen75157d72018-07-27 14:47:21 +09006219 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006220
6221 @Override
6222 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6223 int requestCode, int resultCode, Intent data) {
6224 synchronized (mGlobalLock) {
6225 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006226 if (r != null && r.getActivityStack() != null) {
6227 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6228 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006229 }
6230 }
6231 }
6232
6233 @Override
6234 public void clearPendingResultForActivity(IBinder activityToken,
6235 WeakReference<PendingIntentRecord> pir) {
6236 synchronized (mGlobalLock) {
6237 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6238 if (r != null && r.pendingResults != null) {
6239 r.pendingResults.remove(pir);
6240 }
6241 }
6242 }
6243
6244 @Override
6245 public IIntentSender getIntentSender(int type, String packageName,
6246 int callingUid, int userId, IBinder token, String resultWho,
6247 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6248 Bundle bOptions) {
6249 synchronized (mGlobalLock) {
6250 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6251 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6252 }
6253 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006254
6255 @Override
6256 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6257 synchronized (mGlobalLock) {
6258 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6259 if (r == null) {
6260 return null;
6261 }
6262 if (r.mServiceConnectionsHolder == null) {
6263 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6264 ActivityTaskManagerService.this, r);
6265 }
6266
6267 return r.mServiceConnectionsHolder;
6268 }
6269 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006270
6271 @Override
6272 public Intent getHomeIntent() {
6273 synchronized (mGlobalLock) {
6274 return ActivityTaskManagerService.this.getHomeIntent();
6275 }
6276 }
6277
6278 @Override
6279 public boolean startHomeActivity(int userId, String reason) {
6280 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006281 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006282 }
6283 }
6284
6285 @Override
6286 public boolean startHomeOnAllDisplays(int userId, String reason) {
6287 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006288 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006289 }
6290 }
6291
6292 @Override
6293 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6294 synchronized (mGlobalLock) {
6295 if (mFactoryTest == FACTORY_TEST_OFF) {
6296 return false;
6297 }
6298 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6299 && wpc.mName.equals(mTopComponent.getPackageName())) {
6300 return true;
6301 }
6302 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6303 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6304 }
6305 }
6306
6307 @Override
6308 public void updateTopComponentForFactoryTest() {
6309 synchronized (mGlobalLock) {
6310 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6311 return;
6312 }
6313 final ResolveInfo ri = mContext.getPackageManager()
6314 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6315 final CharSequence errorMsg;
6316 if (ri != null) {
6317 final ActivityInfo ai = ri.activityInfo;
6318 final ApplicationInfo app = ai.applicationInfo;
6319 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6320 mTopAction = Intent.ACTION_FACTORY_TEST;
6321 mTopData = null;
6322 mTopComponent = new ComponentName(app.packageName, ai.name);
6323 errorMsg = null;
6324 } else {
6325 errorMsg = mContext.getResources().getText(
6326 com.android.internal.R.string.factorytest_not_system);
6327 }
6328 } else {
6329 errorMsg = mContext.getResources().getText(
6330 com.android.internal.R.string.factorytest_no_action);
6331 }
6332 if (errorMsg == null) {
6333 return;
6334 }
6335
6336 mTopAction = null;
6337 mTopData = null;
6338 mTopComponent = null;
6339 mUiHandler.post(() -> {
6340 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6341 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006342 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006343 });
6344 }
6345 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006346
6347 @Override
6348 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6349 Runnable finishInstrumentationCallback) {
6350 synchronized (mGlobalLock) {
6351 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006352 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006353
6354 wpc.clearRecentTasks();
6355 wpc.clearActivities();
6356
6357 if (wpc.isInstrumenting()) {
6358 finishInstrumentationCallback.run();
6359 }
6360
Jorim Jaggid0752812018-10-16 16:07:20 +02006361 if (!restarting && hasVisibleActivities) {
6362 mWindowManager.deferSurfaceLayout();
6363 try {
6364 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6365 // If there was nothing to resume, and we are not already restarting
6366 // this process, but there is a visible activity that is hosted by the
6367 // process...then make sure all visible activities are running, taking
6368 // care of restarting this process.
6369 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6370 !PRESERVE_WINDOWS);
6371 }
6372 } finally {
6373 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006374 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006375 }
6376 }
6377 }
6378
6379 @Override
6380 public void closeSystemDialogs(String reason) {
6381 enforceNotIsolatedCaller("closeSystemDialogs");
6382
6383 final int pid = Binder.getCallingPid();
6384 final int uid = Binder.getCallingUid();
6385 final long origId = Binder.clearCallingIdentity();
6386 try {
6387 synchronized (mGlobalLock) {
6388 // Only allow this from foreground processes, so that background
6389 // applications can't abuse it to prevent system UI from being shown.
6390 if (uid >= FIRST_APPLICATION_UID) {
6391 final WindowProcessController proc = mPidMap.get(pid);
6392 if (!proc.isPerceptible()) {
6393 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6394 + " from background process " + proc);
6395 return;
6396 }
6397 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006398 mWindowManager.closeSystemDialogs(reason);
6399
Wale Ogunwaled32da472018-11-16 07:19:28 -08006400 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006401 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006402 // Call into AM outside the synchronized block.
6403 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006404 } finally {
6405 Binder.restoreCallingIdentity(origId);
6406 }
6407 }
6408
6409 @Override
6410 public void cleanupDisabledPackageComponents(
6411 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6412 synchronized (mGlobalLock) {
6413 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006414 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006415 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006416 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006417 mStackSupervisor.scheduleIdleLocked();
6418 }
6419
6420 // Clean-up disabled tasks
6421 getRecentTasks().cleanupDisabledPackageTasksLocked(
6422 packageName, disabledClasses, userId);
6423 }
6424 }
6425
6426 @Override
6427 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6428 int userId) {
6429 synchronized (mGlobalLock) {
6430
6431 boolean didSomething =
6432 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006433 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006434 null, doit, evenPersistent, userId);
6435 return didSomething;
6436 }
6437 }
6438
6439 @Override
6440 public void resumeTopActivities(boolean scheduleIdle) {
6441 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006442 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006443 if (scheduleIdle) {
6444 mStackSupervisor.scheduleIdleLocked();
6445 }
6446 }
6447 }
6448
6449 @Override
6450 public void preBindApplication(WindowProcessController wpc) {
6451 synchronized (mGlobalLock) {
6452 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6453 }
6454 }
6455
6456 @Override
6457 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6458 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006459 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006460 }
6461 }
6462
6463 @Override
6464 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6465 try {
6466 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6467 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6468 }
6469 } catch (RemoteException ex) {
6470 throw new SecurityException("Fail to check is caller a privileged app", ex);
6471 }
6472
6473 synchronized (mGlobalLock) {
6474 final long ident = Binder.clearCallingIdentity();
6475 try {
6476 if (mAmInternal.shouldConfirmCredentials(userId)) {
6477 if (mKeyguardController.isKeyguardLocked()) {
6478 // Showing launcher to avoid user entering credential twice.
6479 startHomeActivity(currentUserId, "notifyLockedProfile");
6480 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006481 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006482 }
6483 } finally {
6484 Binder.restoreCallingIdentity(ident);
6485 }
6486 }
6487 }
6488
6489 @Override
6490 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6491 mAmInternal.enforceCallingPermission(
6492 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6493
6494 synchronized (mGlobalLock) {
6495 final long ident = Binder.clearCallingIdentity();
6496 try {
6497 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6498 FLAG_ACTIVITY_TASK_ON_HOME);
6499 ActivityOptions activityOptions = options != null
6500 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006501 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006502 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006503 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006504 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006505 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006506 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6507 UserHandle.CURRENT);
6508 } finally {
6509 Binder.restoreCallingIdentity(ident);
6510 }
6511 }
6512 }
6513
6514 @Override
6515 public void writeActivitiesToProto(ProtoOutputStream proto) {
6516 synchronized (mGlobalLock) {
6517 // The output proto of "activity --proto activities"
6518 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006519 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006520 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6521 }
6522 }
6523
6524 @Override
6525 public void saveANRState(String reason) {
6526 synchronized (mGlobalLock) {
6527 final StringWriter sw = new StringWriter();
6528 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6529 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6530 if (reason != null) {
6531 pw.println(" Reason: " + reason);
6532 }
6533 pw.println();
6534 getActivityStartController().dump(pw, " ", null);
6535 pw.println();
6536 pw.println("-------------------------------------------------------------------------------");
6537 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6538 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6539 "" /* header */);
6540 pw.println();
6541 pw.close();
6542
6543 mLastANRState = sw.toString();
6544 }
6545 }
6546
6547 @Override
6548 public void clearSavedANRState() {
6549 synchronized (mGlobalLock) {
6550 mLastANRState = null;
6551 }
6552 }
6553
6554 @Override
6555 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6556 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6557 synchronized (mGlobalLock) {
6558 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6559 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6560 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6561 dumpLastANRLocked(pw);
6562 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6563 dumpLastANRTracesLocked(pw);
6564 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6565 dumpActivityStarterLocked(pw, dumpPackage);
6566 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6567 dumpActivityContainersLocked(pw);
6568 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6569 if (getRecentTasks() != null) {
6570 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6571 }
6572 }
6573 }
6574 }
6575
6576 @Override
6577 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6578 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6579 int wakefulness) {
6580 synchronized (mGlobalLock) {
6581 if (mHomeProcess != null && (dumpPackage == null
6582 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6583 if (needSep) {
6584 pw.println();
6585 needSep = false;
6586 }
6587 pw.println(" mHomeProcess: " + mHomeProcess);
6588 }
6589 if (mPreviousProcess != null && (dumpPackage == null
6590 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6591 if (needSep) {
6592 pw.println();
6593 needSep = false;
6594 }
6595 pw.println(" mPreviousProcess: " + mPreviousProcess);
6596 }
6597 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6598 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6599 StringBuilder sb = new StringBuilder(128);
6600 sb.append(" mPreviousProcessVisibleTime: ");
6601 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6602 pw.println(sb);
6603 }
6604 if (mHeavyWeightProcess != null && (dumpPackage == null
6605 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6606 if (needSep) {
6607 pw.println();
6608 needSep = false;
6609 }
6610 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6611 }
6612 if (dumpPackage == null) {
6613 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006614 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006615 }
6616 if (dumpAll) {
6617 if (dumpPackage == null) {
6618 pw.println(" mConfigWillChange: "
6619 + getTopDisplayFocusedStack().mConfigWillChange);
6620 }
6621 if (mCompatModePackages.getPackages().size() > 0) {
6622 boolean printed = false;
6623 for (Map.Entry<String, Integer> entry
6624 : mCompatModePackages.getPackages().entrySet()) {
6625 String pkg = entry.getKey();
6626 int mode = entry.getValue();
6627 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6628 continue;
6629 }
6630 if (!printed) {
6631 pw.println(" mScreenCompatPackages:");
6632 printed = true;
6633 }
6634 pw.println(" " + pkg + ": " + mode);
6635 }
6636 }
6637 }
6638
6639 if (dumpPackage == null) {
6640 pw.println(" mWakefulness="
6641 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006642 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006643 if (mRunningVoice != null) {
6644 pw.println(" mRunningVoice=" + mRunningVoice);
6645 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6646 }
6647 pw.println(" mSleeping=" + mSleeping);
6648 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6649 pw.println(" mVrController=" + mVrController);
6650 }
6651 if (mCurAppTimeTracker != null) {
6652 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6653 }
6654 if (mAllowAppSwitchUids.size() > 0) {
6655 boolean printed = false;
6656 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6657 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6658 for (int j = 0; j < types.size(); j++) {
6659 if (dumpPackage == null ||
6660 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6661 if (needSep) {
6662 pw.println();
6663 needSep = false;
6664 }
6665 if (!printed) {
6666 pw.println(" mAllowAppSwitchUids:");
6667 printed = true;
6668 }
6669 pw.print(" User ");
6670 pw.print(mAllowAppSwitchUids.keyAt(i));
6671 pw.print(": Type ");
6672 pw.print(types.keyAt(j));
6673 pw.print(" = ");
6674 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6675 pw.println();
6676 }
6677 }
6678 }
6679 }
6680 if (dumpPackage == null) {
6681 if (mController != null) {
6682 pw.println(" mController=" + mController
6683 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6684 }
6685 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6686 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6687 }
6688
6689 return needSep;
6690 }
6691 }
6692
6693 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006694 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6695 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006696 synchronized (mGlobalLock) {
6697 if (dumpPackage == null) {
6698 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6699 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006700 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6701 if (mRunningVoice != null) {
6702 final long vrToken = proto.start(
6703 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6704 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6705 mRunningVoice.toString());
6706 mVoiceWakeLock.writeToProto(
6707 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6708 proto.end(vrToken);
6709 }
6710 mVrController.writeToProto(proto,
6711 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006712 if (mController != null) {
6713 final long token = proto.start(CONTROLLER);
6714 proto.write(CONTROLLER, mController.toString());
6715 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6716 proto.end(token);
6717 }
6718 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6719 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6720 }
6721
6722 if (mHomeProcess != null && (dumpPackage == null
6723 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006724 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006725 }
6726
6727 if (mPreviousProcess != null && (dumpPackage == null
6728 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006729 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6731 }
6732
6733 if (mHeavyWeightProcess != null && (dumpPackage == null
6734 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006735 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006736 }
6737
6738 for (Map.Entry<String, Integer> entry
6739 : mCompatModePackages.getPackages().entrySet()) {
6740 String pkg = entry.getKey();
6741 int mode = entry.getValue();
6742 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6743 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6744 proto.write(PACKAGE, pkg);
6745 proto.write(MODE, mode);
6746 proto.end(compatToken);
6747 }
6748 }
6749
6750 if (mCurAppTimeTracker != null) {
6751 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6752 }
6753
6754 }
6755 }
6756
6757 @Override
6758 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6759 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6760 boolean dumpFocusedStackOnly) {
6761 synchronized (mGlobalLock) {
6762 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6763 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6764 }
6765 }
6766
6767 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006768 public void dumpForOom(PrintWriter pw) {
6769 synchronized (mGlobalLock) {
6770 pw.println(" mHomeProcess: " + mHomeProcess);
6771 pw.println(" mPreviousProcess: " + mPreviousProcess);
6772 if (mHeavyWeightProcess != null) {
6773 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6774 }
6775 }
6776 }
6777
6778 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 public boolean canGcNow() {
6780 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006781 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 }
6783 }
6784
6785 @Override
6786 public WindowProcessController getTopApp() {
6787 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006788 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 return top != null ? top.app : null;
6790 }
6791 }
6792
6793 @Override
6794 public void rankTaskLayersIfNeeded() {
6795 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006796 if (mRootActivityContainer != null) {
6797 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 }
6799 }
6800 }
6801
6802 @Override
6803 public void scheduleDestroyAllActivities(String reason) {
6804 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006805 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 }
6807 }
6808
6809 @Override
6810 public void removeUser(int userId) {
6811 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 }
6814 }
6815
6816 @Override
6817 public boolean switchUser(int userId, UserState userState) {
6818 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006819 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 }
6821 }
6822
6823 @Override
6824 public void onHandleAppCrash(WindowProcessController wpc) {
6825 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006826 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 }
6828 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006829
6830 @Override
6831 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6832 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006833 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006834 }
6835 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006836
6837 @Override
6838 public void onUidActive(int uid, int procState) {
6839 synchronized (mGlobalLock) {
6840 mActiveUids.put(uid, procState);
6841 }
6842 }
6843
6844 @Override
6845 public void onUidInactive(int uid) {
6846 synchronized (mGlobalLock) {
6847 mActiveUids.remove(uid);
6848 }
6849 }
6850
6851 @Override
6852 public void onActiveUidsCleared() {
6853 synchronized (mGlobalLock) {
6854 mActiveUids.clear();
6855 }
6856 }
6857
6858 @Override
6859 public void onUidProcStateChanged(int uid, int procState) {
6860 synchronized (mGlobalLock) {
6861 if (mActiveUids.get(uid) != null) {
6862 mActiveUids.put(uid, procState);
6863 }
6864 }
6865 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006866
6867 @Override
6868 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6869 synchronized (mGlobalLock) {
6870 mPendingTempWhitelist.put(uid, tag);
6871 }
6872 }
6873
6874 @Override
6875 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6876 synchronized (mGlobalLock) {
6877 mPendingTempWhitelist.remove(uid);
6878 }
6879 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006880
6881 @Override
6882 public boolean handleAppCrashInActivityController(String processName, int pid,
6883 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6884 Runnable killCrashingAppCallback) {
6885 synchronized (mGlobalLock) {
6886 if (mController == null) {
6887 return false;
6888 }
6889
6890 try {
6891 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6892 stackTrace)) {
6893 killCrashingAppCallback.run();
6894 return true;
6895 }
6896 } catch (RemoteException e) {
6897 mController = null;
6898 Watchdog.getInstance().setActivityController(null);
6899 }
6900 return false;
6901 }
6902 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006903
6904 @Override
6905 public void removeRecentTasksByPackageName(String packageName, int userId) {
6906 synchronized (mGlobalLock) {
6907 mRecentTasks.removeTasksByPackageName(packageName, userId);
6908 }
6909 }
6910
6911 @Override
6912 public void cleanupRecentTasksForUser(int userId) {
6913 synchronized (mGlobalLock) {
6914 mRecentTasks.cleanupLocked(userId);
6915 }
6916 }
6917
6918 @Override
6919 public void loadRecentTasksForUser(int userId) {
6920 synchronized (mGlobalLock) {
6921 mRecentTasks.loadUserRecentsLocked(userId);
6922 }
6923 }
6924
6925 @Override
6926 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6927 synchronized (mGlobalLock) {
6928 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6929 }
6930 }
6931
6932 @Override
6933 public void flushRecentTasks() {
6934 mRecentTasks.flush();
6935 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006936
6937 @Override
6938 public WindowProcessController getHomeProcess() {
6939 synchronized (mGlobalLock) {
6940 return mHomeProcess;
6941 }
6942 }
6943
6944 @Override
6945 public WindowProcessController getPreviousProcess() {
6946 synchronized (mGlobalLock) {
6947 return mPreviousProcess;
6948 }
6949 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006950
6951 @Override
6952 public void clearLockedTasks(String reason) {
6953 synchronized (mGlobalLock) {
6954 getLockTaskController().clearLockedTasks(reason);
6955 }
6956 }
6957
6958 @Override
6959 public void updateUserConfiguration() {
6960 synchronized (mGlobalLock) {
6961 final Configuration configuration = new Configuration(getGlobalConfiguration());
6962 final int currentUserId = mAmInternal.getCurrentUserId();
6963 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6964 configuration, currentUserId, Settings.System.canWrite(mContext));
6965 updateConfigurationLocked(configuration, null /* starting */,
6966 false /* initLocale */, false /* persistent */, currentUserId,
6967 false /* deferResume */);
6968 }
6969 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006970
6971 @Override
6972 public boolean canShowErrorDialogs() {
6973 synchronized (mGlobalLock) {
6974 return mShowDialogs && !mSleeping && !mShuttingDown
6975 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6976 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6977 mAmInternal.getCurrentUserId())
6978 && !(UserManager.isDeviceInDemoMode(mContext)
6979 && mAmInternal.getCurrentUser().isDemo());
6980 }
6981 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006982
6983 @Override
6984 public void setProfileApp(String profileApp) {
6985 synchronized (mGlobalLock) {
6986 mProfileApp = profileApp;
6987 }
6988 }
6989
6990 @Override
6991 public void setProfileProc(WindowProcessController wpc) {
6992 synchronized (mGlobalLock) {
6993 mProfileProc = wpc;
6994 }
6995 }
6996
6997 @Override
6998 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6999 synchronized (mGlobalLock) {
7000 mProfilerInfo = profilerInfo;
7001 }
7002 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007003
7004 @Override
7005 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7006 synchronized (mGlobalLock) {
7007 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7008 }
7009 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007010 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007011}