blob: 4084501a4b509b01289e5b7f158b1c79f80909b3 [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();
866 if (pid == MY_PID || pid < 0) {
867 return getGlobalConfiguration();
868 }
869 synchronized (mGlobalLock) {
870 final WindowProcessController app = mPidMap.get(pid);
871 return app != null ? app.getConfiguration() : getGlobalConfiguration();
872 }
873 }
874
875 /**
876 * Return the device configuration info used by the process corresponding to the input pid.
877 * The value is consistent with the global configuration for the process.
878 */
879 @Override
880 public ConfigurationInfo getDeviceConfigurationInfo() {
881 ConfigurationInfo config = new ConfigurationInfo();
882 synchronized (mGlobalLock) {
883 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
884 config.reqTouchScreen = globalConfig.touchscreen;
885 config.reqKeyboardType = globalConfig.keyboard;
886 config.reqNavigation = globalConfig.navigation;
887 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
888 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
889 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
890 }
891 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
892 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
893 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
894 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700895 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900896 }
897 return config;
898 }
899
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700900 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700901 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700902 }
903
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700904 public static final class Lifecycle extends SystemService {
905 private final ActivityTaskManagerService mService;
906
907 public Lifecycle(Context context) {
908 super(context);
909 mService = new ActivityTaskManagerService(context);
910 }
911
912 @Override
913 public void onStart() {
914 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700915 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700916 }
917
Garfield Tan891146c2018-10-09 12:14:00 -0700918 @Override
919 public void onUnlockUser(int userId) {
920 synchronized (mService.getGlobalLock()) {
921 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
922 }
923 }
924
925 @Override
926 public void onCleanupUser(int userId) {
927 synchronized (mService.getGlobalLock()) {
928 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
929 }
930 }
931
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700932 public ActivityTaskManagerService getService() {
933 return mService;
934 }
935 }
936
937 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700938 public final int startActivity(IApplicationThread caller, String callingPackage,
939 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
940 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
941 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
942 resultWho, requestCode, startFlags, profilerInfo, bOptions,
943 UserHandle.getCallingUserId());
944 }
945
946 @Override
947 public final int startActivities(IApplicationThread caller, String callingPackage,
948 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
949 int userId) {
950 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700951 enforceNotIsolatedCaller(reason);
952 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700953 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700954 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100955 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
956 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700957 }
958
959 @Override
960 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
961 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
962 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
963 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
964 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
965 true /*validateIncomingUser*/);
966 }
967
968 int startActivityAsUser(IApplicationThread caller, String callingPackage,
969 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
970 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
971 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700972 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700973
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700974 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700975 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
976
977 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700978 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700979 .setCaller(caller)
980 .setCallingPackage(callingPackage)
981 .setResolvedType(resolvedType)
982 .setResultTo(resultTo)
983 .setResultWho(resultWho)
984 .setRequestCode(requestCode)
985 .setStartFlags(startFlags)
986 .setProfilerInfo(profilerInfo)
987 .setActivityOptions(bOptions)
988 .setMayWait(userId)
989 .execute();
990
991 }
992
993 @Override
994 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
995 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700996 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
997 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 // Refuse possible leaked file descriptors
999 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1000 throw new IllegalArgumentException("File descriptors passed in Intent");
1001 }
1002
1003 if (!(target instanceof PendingIntentRecord)) {
1004 throw new IllegalArgumentException("Bad PendingIntent object");
1005 }
1006
1007 PendingIntentRecord pir = (PendingIntentRecord)target;
1008
1009 synchronized (mGlobalLock) {
1010 // If this is coming from the currently resumed activity, it is
1011 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001012 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 if (stack.mResumedActivity != null &&
1014 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001018 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 }
1021
1022 @Override
1023 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1024 Bundle bOptions) {
1025 // Refuse possible leaked file descriptors
1026 if (intent != null && intent.hasFileDescriptors()) {
1027 throw new IllegalArgumentException("File descriptors passed in Intent");
1028 }
1029 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1030
1031 synchronized (mGlobalLock) {
1032 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1033 if (r == null) {
1034 SafeActivityOptions.abort(options);
1035 return false;
1036 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001037 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 // The caller is not running... d'oh!
1039 SafeActivityOptions.abort(options);
1040 return false;
1041 }
1042 intent = new Intent(intent);
1043 // The caller is not allowed to change the data.
1044 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1045 // And we are resetting to find the next component...
1046 intent.setComponent(null);
1047
1048 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1049
1050 ActivityInfo aInfo = null;
1051 try {
1052 List<ResolveInfo> resolves =
1053 AppGlobals.getPackageManager().queryIntentActivities(
1054 intent, r.resolvedType,
1055 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1056 UserHandle.getCallingUserId()).getList();
1057
1058 // Look for the original activity in the list...
1059 final int N = resolves != null ? resolves.size() : 0;
1060 for (int i=0; i<N; i++) {
1061 ResolveInfo rInfo = resolves.get(i);
1062 if (rInfo.activityInfo.packageName.equals(r.packageName)
1063 && rInfo.activityInfo.name.equals(r.info.name)) {
1064 // We found the current one... the next matching is
1065 // after it.
1066 i++;
1067 if (i<N) {
1068 aInfo = resolves.get(i).activityInfo;
1069 }
1070 if (debug) {
1071 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1072 + "/" + r.info.name);
1073 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1074 ? "null" : aInfo.packageName + "/" + aInfo.name));
1075 }
1076 break;
1077 }
1078 }
1079 } catch (RemoteException e) {
1080 }
1081
1082 if (aInfo == null) {
1083 // Nobody who is next!
1084 SafeActivityOptions.abort(options);
1085 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1086 return false;
1087 }
1088
1089 intent.setComponent(new ComponentName(
1090 aInfo.applicationInfo.packageName, aInfo.name));
1091 intent.setFlags(intent.getFlags()&~(
1092 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1093 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1094 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1095 FLAG_ACTIVITY_NEW_TASK));
1096
1097 // Okay now we need to start the new activity, replacing the currently running activity.
1098 // This is a little tricky because we want to start the new one as if the current one is
1099 // finished, but not finish the current one first so that there is no flicker.
1100 // And thus...
1101 final boolean wasFinishing = r.finishing;
1102 r.finishing = true;
1103
1104 // Propagate reply information over to the new activity.
1105 final ActivityRecord resultTo = r.resultTo;
1106 final String resultWho = r.resultWho;
1107 final int requestCode = r.requestCode;
1108 r.resultTo = null;
1109 if (resultTo != null) {
1110 resultTo.removeResultsLocked(r, resultWho, requestCode);
1111 }
1112
1113 final long origId = Binder.clearCallingIdentity();
1114 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001115 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001117 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001118 .setResolvedType(r.resolvedType)
1119 .setActivityInfo(aInfo)
1120 .setResultTo(resultTo != null ? resultTo.appToken : null)
1121 .setResultWho(resultWho)
1122 .setRequestCode(requestCode)
1123 .setCallingPid(-1)
1124 .setCallingUid(r.launchedFromUid)
1125 .setCallingPackage(r.launchedFromPackage)
1126 .setRealCallingPid(-1)
1127 .setRealCallingUid(r.launchedFromUid)
1128 .setActivityOptions(options)
1129 .execute();
1130 Binder.restoreCallingIdentity(origId);
1131
1132 r.finishing = wasFinishing;
1133 if (res != ActivityManager.START_SUCCESS) {
1134 return false;
1135 }
1136 return true;
1137 }
1138 }
1139
1140 @Override
1141 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1142 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1143 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1144 final WaitResult res = new WaitResult();
1145 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001146 enforceNotIsolatedCaller("startActivityAndWait");
1147 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1148 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001149 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001150 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001151 .setCaller(caller)
1152 .setCallingPackage(callingPackage)
1153 .setResolvedType(resolvedType)
1154 .setResultTo(resultTo)
1155 .setResultWho(resultWho)
1156 .setRequestCode(requestCode)
1157 .setStartFlags(startFlags)
1158 .setActivityOptions(bOptions)
1159 .setMayWait(userId)
1160 .setProfilerInfo(profilerInfo)
1161 .setWaitResult(res)
1162 .execute();
1163 }
1164 return res;
1165 }
1166
1167 @Override
1168 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1169 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1170 int startFlags, Configuration config, Bundle bOptions, int userId) {
1171 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001172 enforceNotIsolatedCaller("startActivityWithConfig");
1173 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1174 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001176 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .setCaller(caller)
1178 .setCallingPackage(callingPackage)
1179 .setResolvedType(resolvedType)
1180 .setResultTo(resultTo)
1181 .setResultWho(resultWho)
1182 .setRequestCode(requestCode)
1183 .setStartFlags(startFlags)
1184 .setGlobalConfiguration(config)
1185 .setActivityOptions(bOptions)
1186 .setMayWait(userId)
1187 .execute();
1188 }
1189 }
1190
Alison Cichowlas3e340502018-08-07 17:15:01 -04001191
1192 @Override
1193 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1194 int callingUid = Binder.getCallingUid();
1195 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1196 throw new SecurityException("Only the system process can request a permission token, "
1197 + "received request from uid: " + callingUid);
1198 }
1199 IBinder permissionToken = new Binder();
1200 synchronized (mGlobalLock) {
1201 mStartActivitySources.put(permissionToken, delegatorToken);
1202 }
1203
1204 Message expireMsg = PooledLambda.obtainMessage(
1205 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1206 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1207
1208 Message forgetMsg = PooledLambda.obtainMessage(
1209 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1210 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1211
1212 return permissionToken;
1213 }
1214
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 @Override
1216 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1217 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001218 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1219 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001221 // permission grants) as any app that may launch one of your own activities. So we only
1222 // allow this in two cases:
1223 // 1) The caller is an activity that is part of the core framework, and then only when it
1224 // is running as the system.
1225 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1226 // can only be requested by a system activity, which may then delegate this call to
1227 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 final ActivityRecord sourceRecord;
1229 final int targetUid;
1230 final String targetPackage;
1231 final boolean isResolver;
1232 synchronized (mGlobalLock) {
1233 if (resultTo == null) {
1234 throw new SecurityException("Must be called from an activity");
1235 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001236 final IBinder sourceToken;
1237 if (permissionToken != null) {
1238 // To even attempt to use a permissionToken, an app must also have this signature
1239 // permission.
1240 mAmInternal.enforceCallingPermission(
1241 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1242 "startActivityAsCaller");
1243 // If called with a permissionToken, we want the sourceRecord from the delegator
1244 // activity that requested this token.
1245 sourceToken = mStartActivitySources.remove(permissionToken);
1246 if (sourceToken == null) {
1247 // Invalid permissionToken, check if it recently expired.
1248 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1249 throw new SecurityException("Called with expired permission token: "
1250 + permissionToken);
1251 } else {
1252 throw new SecurityException("Called with invalid permission token: "
1253 + permissionToken);
1254 }
1255 }
1256 } else {
1257 // This method was called directly by the source.
1258 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001259 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260
Wale Ogunwaled32da472018-11-16 07:19:28 -08001261 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001262 if (sourceRecord == null) {
1263 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 }
1265 if (sourceRecord.app == null) {
1266 throw new SecurityException("Called without a process attached to activity");
1267 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268
1269 // Whether called directly or from a delegate, the source activity must be from the
1270 // android package.
1271 if (!sourceRecord.info.packageName.equals("android")) {
1272 throw new SecurityException("Must be called from an activity that is "
1273 + "declared in the android package");
1274 }
1275
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001276 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001277 // This is still okay, as long as this activity is running under the
1278 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001279 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001281 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 + " must be system uid or original calling uid "
1283 + sourceRecord.launchedFromUid);
1284 }
1285 }
1286 if (ignoreTargetSecurity) {
1287 if (intent.getComponent() == null) {
1288 throw new SecurityException(
1289 "Component must be specified with ignoreTargetSecurity");
1290 }
1291 if (intent.getSelector() != null) {
1292 throw new SecurityException(
1293 "Selector not allowed with ignoreTargetSecurity");
1294 }
1295 }
1296 targetUid = sourceRecord.launchedFromUid;
1297 targetPackage = sourceRecord.launchedFromPackage;
1298 isResolver = sourceRecord.isResolverOrChildActivity();
1299 }
1300
1301 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001302 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001303 }
1304
1305 // TODO: Switch to user app stacks here.
1306 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001307 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308 .setCallingUid(targetUid)
1309 .setCallingPackage(targetPackage)
1310 .setResolvedType(resolvedType)
1311 .setResultTo(resultTo)
1312 .setResultWho(resultWho)
1313 .setRequestCode(requestCode)
1314 .setStartFlags(startFlags)
1315 .setActivityOptions(bOptions)
1316 .setMayWait(userId)
1317 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1318 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1319 .execute();
1320 } catch (SecurityException e) {
1321 // XXX need to figure out how to propagate to original app.
1322 // A SecurityException here is generally actually a fault of the original
1323 // calling activity (such as a fairly granting permissions), so propagate it
1324 // back to them.
1325 /*
1326 StringBuilder msg = new StringBuilder();
1327 msg.append("While launching");
1328 msg.append(intent.toString());
1329 msg.append(": ");
1330 msg.append(e.getMessage());
1331 */
1332 throw e;
1333 }
1334 }
1335
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001336 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1337 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1338 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1339 }
1340
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 @Override
1342 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1343 Intent intent, String resolvedType, IVoiceInteractionSession session,
1344 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1345 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001346 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 if (session == null || interactor == null) {
1348 throw new NullPointerException("null session or interactor");
1349 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001350 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001352 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 .setCallingUid(callingUid)
1354 .setCallingPackage(callingPackage)
1355 .setResolvedType(resolvedType)
1356 .setVoiceSession(session)
1357 .setVoiceInteractor(interactor)
1358 .setStartFlags(startFlags)
1359 .setProfilerInfo(profilerInfo)
1360 .setActivityOptions(bOptions)
1361 .setMayWait(userId)
1362 .execute();
1363 }
1364
1365 @Override
1366 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1367 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001368 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1369 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001371 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 .setCallingUid(callingUid)
1373 .setCallingPackage(callingPackage)
1374 .setResolvedType(resolvedType)
1375 .setActivityOptions(bOptions)
1376 .setMayWait(userId)
1377 .execute();
1378 }
1379
1380 @Override
1381 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1382 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001383 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 final int callingPid = Binder.getCallingPid();
1385 final long origId = Binder.clearCallingIdentity();
1386 try {
1387 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001388 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1389 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390
1391 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1393 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1395 recentsUid, assistDataReceiver);
1396 }
1397 } finally {
1398 Binder.restoreCallingIdentity(origId);
1399 }
1400 }
1401
1402 @Override
1403 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001404 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 "startActivityFromRecents()");
1406
1407 final int callingPid = Binder.getCallingPid();
1408 final int callingUid = Binder.getCallingUid();
1409 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1410 final long origId = Binder.clearCallingIdentity();
1411 try {
1412 synchronized (mGlobalLock) {
1413 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1414 safeOptions);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(origId);
1418 }
1419 }
1420
1421 /**
1422 * This is the internal entry point for handling Activity.finish().
1423 *
1424 * @param token The Binder token referencing the Activity we want to finish.
1425 * @param resultCode Result code, if any, from this Activity.
1426 * @param resultData Result data (Intent), if any, from this Activity.
1427 * @param finishTask Whether to finish the task associated with this Activity.
1428 *
1429 * @return Returns true if the activity successfully finished, or false if it is still running.
1430 */
1431 @Override
1432 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1433 int finishTask) {
1434 // Refuse possible leaked file descriptors
1435 if (resultData != null && resultData.hasFileDescriptors()) {
1436 throw new IllegalArgumentException("File descriptors passed in Intent");
1437 }
1438
1439 synchronized (mGlobalLock) {
1440 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1441 if (r == null) {
1442 return true;
1443 }
1444 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001445 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 ActivityRecord rootR = tr.getRootActivity();
1447 if (rootR == null) {
1448 Slog.w(TAG, "Finishing task with all activities already finished");
1449 }
1450 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1451 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001452 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 return false;
1454 }
1455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001456 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1457 // We should consolidate.
1458 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001460 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001461 if (next != null) {
1462 // ask watcher if this is allowed
1463 boolean resumeOK = true;
1464 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001467 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 Watchdog.getInstance().setActivityController(null);
1469 }
1470
1471 if (!resumeOK) {
1472 Slog.i(TAG, "Not finishing activity because controller resumed");
1473 return false;
1474 }
1475 }
1476 }
1477 final long origId = Binder.clearCallingIdentity();
1478 try {
1479 boolean res;
1480 final boolean finishWithRootActivity =
1481 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1482 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1483 || (finishWithRootActivity && r == rootR)) {
1484 // If requested, remove the task that is associated to this activity only if it
1485 // was the root activity in the task. The result code and data is ignored
1486 // because we don't support returning them across task boundaries. Also, to
1487 // keep backwards compatibility we remove the task from recents when finishing
1488 // task with root activity.
1489 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1490 finishWithRootActivity, "finish-activity");
1491 if (!res) {
1492 Slog.i(TAG, "Removing task failed to finish activity");
1493 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001494 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001495 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 } else {
1497 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1498 resultData, "app-request", true);
1499 if (!res) {
1500 Slog.i(TAG, "Failed to finish by app-request");
1501 }
1502 }
1503 return res;
1504 } finally {
1505 Binder.restoreCallingIdentity(origId);
1506 }
1507 }
1508 }
1509
1510 @Override
1511 public boolean finishActivityAffinity(IBinder token) {
1512 synchronized (mGlobalLock) {
1513 final long origId = Binder.clearCallingIdentity();
1514 try {
1515 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1516 if (r == null) {
1517 return false;
1518 }
1519
1520 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1521 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001522 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001523 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001524 return false;
1525 }
1526 return task.getStack().finishActivityAffinityLocked(r);
1527 } finally {
1528 Binder.restoreCallingIdentity(origId);
1529 }
1530 }
1531 }
1532
1533 @Override
1534 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1535 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001536 try {
1537 WindowProcessController proc = null;
1538 synchronized (mGlobalLock) {
1539 ActivityStack stack = ActivityRecord.getStackLocked(token);
1540 if (stack == null) {
1541 return;
1542 }
1543 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1544 false /* fromTimeout */, false /* processPausingActivities */, config);
1545 if (r != null) {
1546 proc = r.app;
1547 }
1548 if (stopProfiling && proc != null) {
1549 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 }
1551 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001552 } finally {
1553 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 }
1556
1557 @Override
1558 public final void activityResumed(IBinder token) {
1559 final long origId = Binder.clearCallingIdentity();
1560 synchronized (mGlobalLock) {
1561 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001562 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 }
1564 Binder.restoreCallingIdentity(origId);
1565 }
1566
1567 @Override
1568 public final void activityPaused(IBinder token) {
1569 final long origId = Binder.clearCallingIdentity();
1570 synchronized (mGlobalLock) {
1571 ActivityStack stack = ActivityRecord.getStackLocked(token);
1572 if (stack != null) {
1573 stack.activityPausedLocked(token, false);
1574 }
1575 }
1576 Binder.restoreCallingIdentity(origId);
1577 }
1578
1579 @Override
1580 public final void activityStopped(IBinder token, Bundle icicle,
1581 PersistableBundle persistentState, CharSequence description) {
1582 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1583
1584 // Refuse possible leaked file descriptors
1585 if (icicle != null && icicle.hasFileDescriptors()) {
1586 throw new IllegalArgumentException("File descriptors passed in Bundle");
1587 }
1588
1589 final long origId = Binder.clearCallingIdentity();
1590
1591 synchronized (mGlobalLock) {
1592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1593 if (r != null) {
1594 r.activityStoppedLocked(icicle, persistentState, description);
1595 }
1596 }
1597
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001598 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599
1600 Binder.restoreCallingIdentity(origId);
1601 }
1602
1603 @Override
1604 public final void activityDestroyed(IBinder token) {
1605 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1606 synchronized (mGlobalLock) {
1607 ActivityStack stack = ActivityRecord.getStackLocked(token);
1608 if (stack != null) {
1609 stack.activityDestroyedLocked(token, "activityDestroyed");
1610 }
1611 }
1612 }
1613
1614 @Override
1615 public final void activityRelaunched(IBinder token) {
1616 final long origId = Binder.clearCallingIdentity();
1617 synchronized (mGlobalLock) {
1618 mStackSupervisor.activityRelaunchedLocked(token);
1619 }
1620 Binder.restoreCallingIdentity(origId);
1621 }
1622
1623 public final void activitySlept(IBinder token) {
1624 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1625
1626 final long origId = Binder.clearCallingIdentity();
1627
1628 synchronized (mGlobalLock) {
1629 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1630 if (r != null) {
1631 mStackSupervisor.activitySleptLocked(r);
1632 }
1633 }
1634
1635 Binder.restoreCallingIdentity(origId);
1636 }
1637
1638 @Override
1639 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1640 synchronized (mGlobalLock) {
1641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1642 if (r == null) {
1643 return;
1644 }
1645 final long origId = Binder.clearCallingIdentity();
1646 try {
1647 r.setRequestedOrientation(requestedOrientation);
1648 } finally {
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public int getRequestedOrientation(IBinder token) {
1656 synchronized (mGlobalLock) {
1657 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1658 if (r == null) {
1659 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1660 }
1661 return r.getRequestedOrientation();
1662 }
1663 }
1664
1665 @Override
1666 public void setImmersive(IBinder token, boolean immersive) {
1667 synchronized (mGlobalLock) {
1668 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1669 if (r == null) {
1670 throw new IllegalArgumentException();
1671 }
1672 r.immersive = immersive;
1673
1674 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001675 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001677 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 }
1679 }
1680 }
1681
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001682 void applyUpdateLockStateLocked(ActivityRecord r) {
1683 // Modifications to the UpdateLock state are done on our handler, outside
1684 // the activity manager's locks. The new state is determined based on the
1685 // state *now* of the relevant activity record. The object is passed to
1686 // the handler solely for logging detail, not to be consulted/modified.
1687 final boolean nextState = r != null && r.immersive;
1688 mH.post(() -> {
1689 if (mUpdateLock.isHeld() != nextState) {
1690 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1691 "Applying new update lock state '" + nextState + "' for " + r);
1692 if (nextState) {
1693 mUpdateLock.acquire();
1694 } else {
1695 mUpdateLock.release();
1696 }
1697 }
1698 });
1699 }
1700
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 @Override
1702 public boolean isImmersive(IBinder token) {
1703 synchronized (mGlobalLock) {
1704 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1705 if (r == null) {
1706 throw new IllegalArgumentException();
1707 }
1708 return r.immersive;
1709 }
1710 }
1711
1712 @Override
1713 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001714 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001716 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 return (r != null) ? r.immersive : false;
1718 }
1719 }
1720
1721 @Override
1722 public void overridePendingTransition(IBinder token, String packageName,
1723 int enterAnim, int exitAnim) {
1724 synchronized (mGlobalLock) {
1725 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1726 if (self == null) {
1727 return;
1728 }
1729
1730 final long origId = Binder.clearCallingIdentity();
1731
1732 if (self.isState(
1733 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001734 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1735 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 }
1737
1738 Binder.restoreCallingIdentity(origId);
1739 }
1740 }
1741
1742 @Override
1743 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001744 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001746 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001747 if (r == null) {
1748 return ActivityManager.COMPAT_MODE_UNKNOWN;
1749 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001750 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001751 }
1752 }
1753
1754 @Override
1755 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001756 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001758 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001760 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001761 if (r == null) {
1762 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1763 return;
1764 }
1765 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001766 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 }
1768 }
1769
1770 @Override
1771 public int getLaunchedFromUid(IBinder activityToken) {
1772 ActivityRecord srec;
1773 synchronized (mGlobalLock) {
1774 srec = ActivityRecord.forTokenLocked(activityToken);
1775 }
1776 if (srec == null) {
1777 return -1;
1778 }
1779 return srec.launchedFromUid;
1780 }
1781
1782 @Override
1783 public String getLaunchedFromPackage(IBinder activityToken) {
1784 ActivityRecord srec;
1785 synchronized (mGlobalLock) {
1786 srec = ActivityRecord.forTokenLocked(activityToken);
1787 }
1788 if (srec == null) {
1789 return null;
1790 }
1791 return srec.launchedFromPackage;
1792 }
1793
1794 @Override
1795 public boolean convertFromTranslucent(IBinder token) {
1796 final long origId = Binder.clearCallingIdentity();
1797 try {
1798 synchronized (mGlobalLock) {
1799 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1800 if (r == null) {
1801 return false;
1802 }
1803 final boolean translucentChanged = r.changeWindowTranslucency(true);
1804 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001805 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001807 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 return translucentChanged;
1809 }
1810 } finally {
1811 Binder.restoreCallingIdentity(origId);
1812 }
1813 }
1814
1815 @Override
1816 public boolean convertToTranslucent(IBinder token, Bundle options) {
1817 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1818 final long origId = Binder.clearCallingIdentity();
1819 try {
1820 synchronized (mGlobalLock) {
1821 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return false;
1824 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001825 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 int index = task.mActivities.lastIndexOf(r);
1827 if (index > 0) {
1828 ActivityRecord under = task.mActivities.get(index - 1);
1829 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1830 }
1831 final boolean translucentChanged = r.changeWindowTranslucency(false);
1832 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001833 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001835 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 return translucentChanged;
1838 }
1839 } finally {
1840 Binder.restoreCallingIdentity(origId);
1841 }
1842 }
1843
1844 @Override
1845 public void notifyActivityDrawn(IBinder token) {
1846 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1847 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001848 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001850 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 }
1852 }
1853 }
1854
1855 @Override
1856 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1857 synchronized (mGlobalLock) {
1858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 return;
1861 }
1862 r.reportFullyDrawnLocked(restoredFromBundle);
1863 }
1864 }
1865
1866 @Override
1867 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1868 synchronized (mGlobalLock) {
1869 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1870 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1871 return stack.mDisplayId;
1872 }
1873 return DEFAULT_DISPLAY;
1874 }
1875 }
1876
1877 @Override
1878 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001879 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 long ident = Binder.clearCallingIdentity();
1881 try {
1882 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001883 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001884 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001885 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 }
1887 return null;
1888 }
1889 } finally {
1890 Binder.restoreCallingIdentity(ident);
1891 }
1892 }
1893
1894 @Override
1895 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001896 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1898 final long callingId = Binder.clearCallingIdentity();
1899 try {
1900 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001901 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 if (stack == null) {
1903 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1904 return;
1905 }
1906 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001907 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001908 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 }
1910 }
1911 } finally {
1912 Binder.restoreCallingIdentity(callingId);
1913 }
1914 }
1915
1916 @Override
1917 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1920 final long callingId = Binder.clearCallingIdentity();
1921 try {
1922 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001923 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001924 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 if (task == null) {
1926 return;
1927 }
1928 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001929 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001930 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 }
1932 }
1933 } finally {
1934 Binder.restoreCallingIdentity(callingId);
1935 }
1936 }
1937
1938 @Override
1939 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001940 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 synchronized (mGlobalLock) {
1942 final long ident = Binder.clearCallingIdentity();
1943 try {
1944 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1945 "remove-task");
1946 } finally {
1947 Binder.restoreCallingIdentity(ident);
1948 }
1949 }
1950 }
1951
1952 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001953 public void removeAllVisibleRecentTasks() {
1954 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1955 synchronized (mGlobalLock) {
1956 final long ident = Binder.clearCallingIdentity();
1957 try {
1958 getRecentTasks().removeAllVisibleTasks();
1959 } finally {
1960 Binder.restoreCallingIdentity(ident);
1961 }
1962 }
1963 }
1964
1965 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1967 synchronized (mGlobalLock) {
1968 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1969 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001970 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001971 }
1972 }
1973 return false;
1974 }
1975
1976 @Override
1977 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1978 Intent resultData) {
1979
1980 synchronized (mGlobalLock) {
1981 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1982 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001983 return r.getActivityStack().navigateUpToLocked(
1984 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 }
1986 return false;
1987 }
1988 }
1989
1990 /**
1991 * Attempts to move a task backwards in z-order (the order of activities within the task is
1992 * unchanged).
1993 *
1994 * There are several possible results of this call:
1995 * - if the task is locked, then we will show the lock toast
1996 * - if there is a task behind the provided task, then that task is made visible and resumed as
1997 * this task is moved to the back
1998 * - otherwise, if there are no other tasks in the stack:
1999 * - if this task is in the pinned stack, then we remove the stack completely, which will
2000 * have the effect of moving the task to the top or bottom of the fullscreen stack
2001 * (depending on whether it is visible)
2002 * - otherwise, we simply return home and hide this task
2003 *
2004 * @param token A reference to the activity we wish to move
2005 * @param nonRoot If false then this only works if the activity is the root
2006 * of a task; if true it will work for any activity in a task.
2007 * @return Returns true if the move completed, false if not.
2008 */
2009 @Override
2010 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002011 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 synchronized (mGlobalLock) {
2013 final long origId = Binder.clearCallingIdentity();
2014 try {
2015 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002016 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 if (task != null) {
2018 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2019 }
2020 } finally {
2021 Binder.restoreCallingIdentity(origId);
2022 }
2023 }
2024 return false;
2025 }
2026
2027 @Override
2028 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002029 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 long ident = Binder.clearCallingIdentity();
2031 Rect rect = new Rect();
2032 try {
2033 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002034 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2036 if (task == null) {
2037 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2038 return rect;
2039 }
2040 if (task.getStack() != null) {
2041 // Return the bounds from window manager since it will be adjusted for various
2042 // things like the presense of a docked stack for tasks that aren't resizeable.
2043 task.getWindowContainerBounds(rect);
2044 } else {
2045 // Task isn't in window manager yet since it isn't associated with a stack.
2046 // Return the persist value from activity manager
2047 if (!task.matchParentBounds()) {
2048 rect.set(task.getBounds());
2049 } else if (task.mLastNonFullscreenBounds != null) {
2050 rect.set(task.mLastNonFullscreenBounds);
2051 }
2052 }
2053 }
2054 } finally {
2055 Binder.restoreCallingIdentity(ident);
2056 }
2057 return rect;
2058 }
2059
2060 @Override
2061 public ActivityManager.TaskDescription getTaskDescription(int id) {
2062 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002065 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2067 if (tr != null) {
2068 return tr.lastTaskDescription;
2069 }
2070 }
2071 return null;
2072 }
2073
2074 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002075 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2076 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2077 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2078 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2079 return;
2080 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002081 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002082 synchronized (mGlobalLock) {
2083 final long ident = Binder.clearCallingIdentity();
2084 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002085 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002086 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002087 if (task == null) {
2088 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2089 return;
2090 }
2091
2092 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2093 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2094
2095 if (!task.isActivityTypeStandardOrUndefined()) {
2096 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2097 + " non-standard task " + taskId + " to windowing mode="
2098 + windowingMode);
2099 }
2100
2101 final ActivityStack stack = task.getStack();
2102 if (toTop) {
2103 stack.moveToFront("setTaskWindowingMode", task);
2104 }
2105 stack.setWindowingMode(windowingMode);
2106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
2109 }
2110 }
2111
2112 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002113 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002114 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 ActivityRecord r = getCallingRecordLocked(token);
2116 return r != null ? r.info.packageName : null;
2117 }
2118 }
2119
2120 @Override
2121 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002122 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002123 ActivityRecord r = getCallingRecordLocked(token);
2124 return r != null ? r.intent.getComponent() : null;
2125 }
2126 }
2127
2128 private ActivityRecord getCallingRecordLocked(IBinder token) {
2129 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2130 if (r == null) {
2131 return null;
2132 }
2133 return r.resultTo;
2134 }
2135
2136 @Override
2137 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002138 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002139
2140 synchronized (mGlobalLock) {
2141 final long origId = Binder.clearCallingIdentity();
2142 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002143 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 } finally {
2145 Binder.restoreCallingIdentity(origId);
2146 }
2147 }
2148 }
2149
2150 /**
2151 * TODO: Add mController hook
2152 */
2153 @Override
2154 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002155 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156
2157 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2158 synchronized (mGlobalLock) {
2159 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2160 false /* fromRecents */);
2161 }
2162 }
2163
2164 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2165 boolean fromRecents) {
2166
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002167 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 Binder.getCallingUid(), -1, -1, "Task to front")) {
2169 SafeActivityOptions.abort(options);
2170 return;
2171 }
2172 final long origId = Binder.clearCallingIdentity();
2173 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002174 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 if (task == null) {
2176 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002177 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 return;
2179 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002180 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002181 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002182 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002183 return;
2184 }
2185 ActivityOptions realOptions = options != null
2186 ? options.getOptions(mStackSupervisor)
2187 : null;
2188 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2189 false /* forceNonResizable */);
2190
2191 final ActivityRecord topActivity = task.getTopActivity();
2192 if (topActivity != null) {
2193
2194 // We are reshowing a task, use a starting window to hide the initial draw delay
2195 // so the transition can start earlier.
2196 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2197 true /* taskSwitch */, fromRecents);
2198 }
2199 } finally {
2200 Binder.restoreCallingIdentity(origId);
2201 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 }
2203
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002204 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2205 int callingPid, int callingUid, String name) {
2206 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2207 return true;
2208 }
2209
2210 if (getRecentTasks().isCallerRecents(sourceUid)) {
2211 return true;
2212 }
2213
2214 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2215 if (perm == PackageManager.PERMISSION_GRANTED) {
2216 return true;
2217 }
2218 if (checkAllowAppSwitchUid(sourceUid)) {
2219 return true;
2220 }
2221
2222 // If the actual IPC caller is different from the logical source, then
2223 // also see if they are allowed to control app switches.
2224 if (callingUid != -1 && callingUid != sourceUid) {
2225 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2226 if (perm == PackageManager.PERMISSION_GRANTED) {
2227 return true;
2228 }
2229 if (checkAllowAppSwitchUid(callingUid)) {
2230 return true;
2231 }
2232 }
2233
2234 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2235 return false;
2236 }
2237
2238 private boolean checkAllowAppSwitchUid(int uid) {
2239 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2240 if (types != null) {
2241 for (int i = types.size() - 1; i >= 0; i--) {
2242 if (types.valueAt(i).intValue() == uid) {
2243 return true;
2244 }
2245 }
2246 }
2247 return false;
2248 }
2249
2250 @Override
2251 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2252 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2253 "setActivityController()");
2254 synchronized (mGlobalLock) {
2255 mController = controller;
2256 mControllerIsAMonkey = imAMonkey;
2257 Watchdog.getInstance().setActivityController(controller);
2258 }
2259 }
2260
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002261 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002262 synchronized (mGlobalLock) {
2263 return mController != null && mControllerIsAMonkey;
2264 }
2265 }
2266
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002267 @Override
2268 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2269 synchronized (mGlobalLock) {
2270 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2271 }
2272 }
2273
2274 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002275 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2276 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2277 }
2278
2279 @Override
2280 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2281 @WindowConfiguration.ActivityType int ignoreActivityType,
2282 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2283 final int callingUid = Binder.getCallingUid();
2284 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2285
2286 synchronized (mGlobalLock) {
2287 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2288
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002290 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002291 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002292 ignoreWindowingMode, callingUid, allowed);
2293 }
2294
2295 return list;
2296 }
2297
2298 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2300 synchronized (mGlobalLock) {
2301 final long origId = Binder.clearCallingIdentity();
2302 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2303 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002304 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002305 }
2306 Binder.restoreCallingIdentity(origId);
2307 }
2308 }
2309
2310 @Override
2311 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002312 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313 ActivityStack stack = ActivityRecord.getStackLocked(token);
2314 if (stack != null) {
2315 return stack.willActivityBeVisibleLocked(token);
2316 }
2317 return false;
2318 }
2319 }
2320
2321 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002322 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002323 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002324 synchronized (mGlobalLock) {
2325 final long ident = Binder.clearCallingIdentity();
2326 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002327 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002328 if (task == null) {
2329 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2330 return;
2331 }
2332
2333 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2334 + " to stackId=" + stackId + " toTop=" + toTop);
2335
Wale Ogunwaled32da472018-11-16 07:19:28 -08002336 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002337 if (stack == null) {
2338 throw new IllegalStateException(
2339 "moveTaskToStack: No stack for stackId=" + stackId);
2340 }
2341 if (!stack.isActivityTypeStandardOrUndefined()) {
2342 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2343 + taskId + " to stack " + stackId);
2344 }
2345 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002346 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002347 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2348 }
2349 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2350 "moveTaskToStack");
2351 } finally {
2352 Binder.restoreCallingIdentity(ident);
2353 }
2354 }
2355 }
2356
2357 @Override
2358 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2359 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002360 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002361
2362 final long ident = Binder.clearCallingIdentity();
2363 try {
2364 synchronized (mGlobalLock) {
2365 if (animate) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002366 final PinnedActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 if (stack == null) {
2368 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2369 return;
2370 }
2371 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2372 throw new IllegalArgumentException("Stack: " + stackId
2373 + " doesn't support animated resize.");
2374 }
2375 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2376 animationDuration, false /* fromFullscreen */);
2377 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002378 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 if (stack == null) {
2380 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2381 return;
2382 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002383 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002384 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2385 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2386 }
2387 }
2388 } finally {
2389 Binder.restoreCallingIdentity(ident);
2390 }
2391 }
2392
2393 /**
2394 * Moves the specified task to the primary-split-screen stack.
2395 *
2396 * @param taskId Id of task to move.
2397 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2398 * exist already. See
2399 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2400 * and
2401 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2402 * @param toTop If the task and stack should be moved to the top.
2403 * @param animate Whether we should play an animation for the moving the task.
2404 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2405 * stack. Pass {@code null} to use default bounds.
2406 * @param showRecents If the recents activity should be shown on the other side of the task
2407 * going into split-screen mode.
2408 */
2409 @Override
2410 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2411 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002412 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002413 "setTaskWindowingModeSplitScreenPrimary()");
2414 synchronized (mGlobalLock) {
2415 final long ident = Binder.clearCallingIdentity();
2416 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002417 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002418 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002419 if (task == null) {
2420 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2421 return false;
2422 }
2423 if (DEBUG_STACK) Slog.d(TAG_STACK,
2424 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2425 + " to createMode=" + createMode + " toTop=" + toTop);
2426 if (!task.isActivityTypeStandardOrUndefined()) {
2427 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2428 + " non-standard task " + taskId + " to split-screen windowing mode");
2429 }
2430
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002431 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002432 final int windowingMode = task.getWindowingMode();
2433 final ActivityStack stack = task.getStack();
2434 if (toTop) {
2435 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2436 }
2437 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002438 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2439 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002440 return windowingMode != task.getWindowingMode();
2441 } finally {
2442 Binder.restoreCallingIdentity(ident);
2443 }
2444 }
2445 }
2446
2447 /**
2448 * Removes stacks in the input windowing modes from the system if they are of activity type
2449 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2450 */
2451 @Override
2452 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002453 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002454 "removeStacksInWindowingModes()");
2455
2456 synchronized (mGlobalLock) {
2457 final long ident = Binder.clearCallingIdentity();
2458 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002459 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002460 } finally {
2461 Binder.restoreCallingIdentity(ident);
2462 }
2463 }
2464 }
2465
2466 @Override
2467 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002468 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002469 "removeStacksWithActivityTypes()");
2470
2471 synchronized (mGlobalLock) {
2472 final long ident = Binder.clearCallingIdentity();
2473 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002474 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002475 } finally {
2476 Binder.restoreCallingIdentity(ident);
2477 }
2478 }
2479 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480
2481 @Override
2482 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2483 int userId) {
2484 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002485 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2486 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002487 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002488 final boolean detailed = checkGetTasksPermission(
2489 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2490 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002491 == PackageManager.PERMISSION_GRANTED;
2492
2493 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002494 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002495 callingUid);
2496 }
2497 }
2498
2499 @Override
2500 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002501 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002502 long ident = Binder.clearCallingIdentity();
2503 try {
2504 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002505 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002506 }
2507 } finally {
2508 Binder.restoreCallingIdentity(ident);
2509 }
2510 }
2511
2512 @Override
2513 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002515 long ident = Binder.clearCallingIdentity();
2516 try {
2517 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002518 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 }
2520 } finally {
2521 Binder.restoreCallingIdentity(ident);
2522 }
2523 }
2524
2525 @Override
2526 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 final long callingUid = Binder.getCallingUid();
2529 final long origId = Binder.clearCallingIdentity();
2530 try {
2531 synchronized (mGlobalLock) {
2532 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002533 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2535 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2536 }
2537 } finally {
2538 Binder.restoreCallingIdentity(origId);
2539 }
2540 }
2541
2542 @Override
2543 public void startLockTaskModeByToken(IBinder token) {
2544 synchronized (mGlobalLock) {
2545 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2546 if (r == null) {
2547 return;
2548 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002549 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 }
2551 }
2552
2553 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002554 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002555 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 // This makes inner call to look as if it was initiated by system.
2557 long ident = Binder.clearCallingIdentity();
2558 try {
2559 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002560 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002561 MATCH_TASK_IN_STACKS_ONLY);
2562 if (task == null) {
2563 return;
2564 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002565
2566 // When starting lock task mode the stack must be in front and focused
2567 task.getStack().moveToFront("startSystemLockTaskMode");
2568 startLockTaskModeLocked(task, true /* isSystemCaller */);
2569 }
2570 } finally {
2571 Binder.restoreCallingIdentity(ident);
2572 }
2573 }
2574
2575 @Override
2576 public void stopLockTaskModeByToken(IBinder token) {
2577 synchronized (mGlobalLock) {
2578 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2579 if (r == null) {
2580 return;
2581 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002582 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 }
2584 }
2585
2586 /**
2587 * This API should be called by SystemUI only when user perform certain action to dismiss
2588 * lock task mode. We should only dismiss pinned lock task mode in this case.
2589 */
2590 @Override
2591 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002592 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2594 }
2595
2596 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2597 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2598 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2599 return;
2600 }
2601
Wale Ogunwaled32da472018-11-16 07:19:28 -08002602 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002603 if (stack == null || task != stack.topTask()) {
2604 throw new IllegalArgumentException("Invalid task, not in foreground");
2605 }
2606
2607 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2608 // system or a specific app.
2609 // * System-initiated requests will only start the pinned mode (screen pinning)
2610 // * App-initiated requests
2611 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2612 // - will start the pinned mode, otherwise
2613 final int callingUid = Binder.getCallingUid();
2614 long ident = Binder.clearCallingIdentity();
2615 try {
2616 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002617 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002618
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002619 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002620 } finally {
2621 Binder.restoreCallingIdentity(ident);
2622 }
2623 }
2624
2625 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2626 final int callingUid = Binder.getCallingUid();
2627 long ident = Binder.clearCallingIdentity();
2628 try {
2629 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002630 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002631 }
2632 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2633 // task and jumping straight into a call in the case of emergency call back.
2634 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2635 if (tm != null) {
2636 tm.showInCallScreen(false);
2637 }
2638 } finally {
2639 Binder.restoreCallingIdentity(ident);
2640 }
2641 }
2642
2643 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002644 public void updateLockTaskPackages(int userId, String[] packages) {
2645 final int callingUid = Binder.getCallingUid();
2646 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2647 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2648 "updateLockTaskPackages()");
2649 }
2650 synchronized (this) {
2651 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2652 + Arrays.toString(packages));
2653 getLockTaskController().updateLockTaskPackages(userId, packages);
2654 }
2655 }
2656
2657 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002658 public boolean isInLockTaskMode() {
2659 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2660 }
2661
2662 @Override
2663 public int getLockTaskModeState() {
2664 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002665 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002666 }
2667 }
2668
2669 @Override
2670 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2671 synchronized (mGlobalLock) {
2672 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2673 if (r != null) {
2674 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002675 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002676 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002677 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 }
2679 }
2680 }
2681
2682 @Override
2683 public Bundle getActivityOptions(IBinder token) {
2684 final long origId = Binder.clearCallingIdentity();
2685 try {
2686 synchronized (mGlobalLock) {
2687 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2688 if (r != null) {
2689 final ActivityOptions activityOptions = r.takeOptionsLocked();
2690 return activityOptions == null ? null : activityOptions.toBundle();
2691 }
2692 return null;
2693 }
2694 } finally {
2695 Binder.restoreCallingIdentity(origId);
2696 }
2697 }
2698
2699 @Override
2700 public List<IBinder> getAppTasks(String callingPackage) {
2701 int callingUid = Binder.getCallingUid();
2702 long ident = Binder.clearCallingIdentity();
2703 try {
2704 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002705 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002706 }
2707 } finally {
2708 Binder.restoreCallingIdentity(ident);
2709 }
2710 }
2711
2712 @Override
2713 public void finishVoiceTask(IVoiceInteractionSession session) {
2714 synchronized (mGlobalLock) {
2715 final long origId = Binder.clearCallingIdentity();
2716 try {
2717 // TODO: VI Consider treating local voice interactions and voice tasks
2718 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002719 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 } finally {
2721 Binder.restoreCallingIdentity(origId);
2722 }
2723 }
2724
2725 }
2726
2727 @Override
2728 public boolean isTopOfTask(IBinder token) {
2729 synchronized (mGlobalLock) {
2730 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002731 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002732 }
2733 }
2734
2735 @Override
2736 public void notifyLaunchTaskBehindComplete(IBinder token) {
2737 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2738 }
2739
2740 @Override
2741 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002742 mH.post(() -> {
2743 synchronized (mGlobalLock) {
2744 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002745 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002746 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002747 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002748 } catch (RemoteException e) {
2749 }
2750 }
2751 }
2752
2753 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 }
2755
2756 /** Called from an app when assist data is ready. */
2757 @Override
2758 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2759 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 synchronized (pae) {
2762 pae.result = extras;
2763 pae.structure = structure;
2764 pae.content = content;
2765 if (referrer != null) {
2766 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2767 }
2768 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002769 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002770 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2771 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772 structure.setHomeActivity(pae.isHome);
2773 }
2774 pae.haveResult = true;
2775 pae.notifyAll();
2776 if (pae.intent == null && pae.receiver == null) {
2777 // Caller is just waiting for the result.
2778 return;
2779 }
2780 }
2781 // We are now ready to launch the assist activity.
2782 IAssistDataReceiver sendReceiver = null;
2783 Bundle sendBundle = null;
2784 synchronized (mGlobalLock) {
2785 buildAssistBundleLocked(pae, extras);
2786 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002788 if (!exists) {
2789 // Timed out.
2790 return;
2791 }
2792
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002793 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 // Caller wants result sent back to them.
2795 sendBundle = new Bundle();
2796 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2797 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2798 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2799 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2800 }
2801 }
2802 if (sendReceiver != null) {
2803 try {
2804 sendReceiver.onHandleAssistData(sendBundle);
2805 } catch (RemoteException e) {
2806 }
2807 return;
2808 }
2809
2810 final long ident = Binder.clearCallingIdentity();
2811 try {
2812 if (TextUtils.equals(pae.intent.getAction(),
2813 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2814 pae.intent.putExtras(pae.extras);
2815 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2816 } else {
2817 pae.intent.replaceExtras(pae.extras);
2818 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2819 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2820 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002821 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822
2823 try {
2824 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2825 } catch (ActivityNotFoundException e) {
2826 Slog.w(TAG, "No activity to handle assist action.", e);
2827 }
2828 }
2829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 @Override
2835 public int addAppTask(IBinder activityToken, Intent intent,
2836 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2837 final int callingUid = Binder.getCallingUid();
2838 final long callingIdent = Binder.clearCallingIdentity();
2839
2840 try {
2841 synchronized (mGlobalLock) {
2842 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2843 if (r == null) {
2844 throw new IllegalArgumentException("Activity does not exist; token="
2845 + activityToken);
2846 }
2847 ComponentName comp = intent.getComponent();
2848 if (comp == null) {
2849 throw new IllegalArgumentException("Intent " + intent
2850 + " must specify explicit component");
2851 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002852 if (thumbnail.getWidth() != mThumbnailWidth
2853 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 throw new IllegalArgumentException("Bad thumbnail size: got "
2855 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002856 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 }
2858 if (intent.getSelector() != null) {
2859 intent.setSelector(null);
2860 }
2861 if (intent.getSourceBounds() != null) {
2862 intent.setSourceBounds(null);
2863 }
2864 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2865 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2866 // The caller has added this as an auto-remove task... that makes no
2867 // sense, so turn off auto-remove.
2868 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2869 }
2870 }
2871 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2872 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2873 if (ainfo.applicationInfo.uid != callingUid) {
2874 throw new SecurityException(
2875 "Can't add task for another application: target uid="
2876 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2877 }
2878
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002879 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002881 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002883 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 // The app has too many tasks already and we can't add any more
2885 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2886 return INVALID_TASK_ID;
2887 }
2888 task.lastTaskDescription.copyFrom(description);
2889
2890 // TODO: Send the thumbnail to WM to store it.
2891
2892 return task.taskId;
2893 }
2894 } finally {
2895 Binder.restoreCallingIdentity(callingIdent);
2896 }
2897 }
2898
2899 @Override
2900 public Point getAppTaskThumbnailSize() {
2901 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002902 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 }
2904 }
2905
2906 @Override
2907 public void setTaskResizeable(int taskId, int resizeableMode) {
2908 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002909 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2911 if (task == null) {
2912 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2913 return;
2914 }
2915 task.setResizeMode(resizeableMode);
2916 }
2917 }
2918
2919 @Override
2920 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002921 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 long ident = Binder.clearCallingIdentity();
2923 try {
2924 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002925 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002926 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 if (task == null) {
2928 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2929 return;
2930 }
2931 // Place the task in the right stack if it isn't there already based on
2932 // the requested bounds.
2933 // The stack transition logic is:
2934 // - a null bounds on a freeform task moves that task to fullscreen
2935 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2936 // that task to freeform
2937 // - otherwise the task is not moved
2938 ActivityStack stack = task.getStack();
2939 if (!task.getWindowConfiguration().canResizeTask()) {
2940 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2941 }
2942 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2943 stack = stack.getDisplay().getOrCreateStack(
2944 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2945 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2946 stack = stack.getDisplay().getOrCreateStack(
2947 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2948 }
2949
2950 // Reparent the task to the right stack if necessary
2951 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2952 if (stack != task.getStack()) {
2953 // Defer resume until the task is resized below
2954 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2955 DEFER_RESUME, "resizeTask");
2956 preserveWindow = false;
2957 }
2958
2959 // After reparenting (which only resizes the task to the stack bounds), resize the
2960 // task to the actual bounds provided
2961 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2962 }
2963 } finally {
2964 Binder.restoreCallingIdentity(ident);
2965 }
2966 }
2967
2968 @Override
2969 public boolean releaseActivityInstance(IBinder token) {
2970 synchronized (mGlobalLock) {
2971 final long origId = Binder.clearCallingIdentity();
2972 try {
2973 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2974 if (r == null) {
2975 return false;
2976 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002977 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 } finally {
2979 Binder.restoreCallingIdentity(origId);
2980 }
2981 }
2982 }
2983
2984 @Override
2985 public void releaseSomeActivities(IApplicationThread appInt) {
2986 synchronized (mGlobalLock) {
2987 final long origId = Binder.clearCallingIdentity();
2988 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002989 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002990 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002991 } finally {
2992 Binder.restoreCallingIdentity(origId);
2993 }
2994 }
2995 }
2996
2997 @Override
2998 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002999 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003000 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 != PackageManager.PERMISSION_GRANTED) {
3002 throw new SecurityException("Requires permission "
3003 + android.Manifest.permission.DEVICE_POWER);
3004 }
3005
3006 synchronized (mGlobalLock) {
3007 long ident = Binder.clearCallingIdentity();
3008 if (mKeyguardShown != keyguardShowing) {
3009 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003010 final Message msg = PooledLambda.obtainMessage(
3011 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3012 keyguardShowing);
3013 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 }
3015 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003016 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003017 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 } finally {
3019 Binder.restoreCallingIdentity(ident);
3020 }
3021 }
3022
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003023 mH.post(() -> {
3024 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3025 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3026 }
3027 });
3028 }
3029
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003030 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003031 mH.post(() -> {
3032 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3033 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3034 }
3035 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 }
3037
3038 @Override
3039 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003040 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3041 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042
3043 final File passedIconFile = new File(filePath);
3044 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3045 passedIconFile.getName());
3046 if (!legitIconFile.getPath().equals(filePath)
3047 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3048 throw new IllegalArgumentException("Bad file path: " + filePath
3049 + " passed for userId " + userId);
3050 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003051 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 }
3053
3054 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3057 final ActivityOptions activityOptions = safeOptions != null
3058 ? safeOptions.getOptions(mStackSupervisor)
3059 : null;
3060 if (activityOptions == null
3061 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3062 || activityOptions.getCustomInPlaceResId() == 0) {
3063 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3064 "with valid animation");
3065 }
lumark588a3e82018-07-20 18:53:54 +08003066 // Get top display of front most application.
3067 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3068 if (focusedStack != null) {
3069 final DisplayWindowController dwc =
3070 focusedStack.getDisplay().getWindowContainerController();
3071 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3072 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3073 activityOptions.getCustomInPlaceResId());
3074 dwc.executeAppTransition();
3075 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 }
3077
3078 @Override
3079 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003080 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 synchronized (mGlobalLock) {
3082 final long ident = Binder.clearCallingIdentity();
3083 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003084 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 if (stack == null) {
3086 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3087 return;
3088 }
3089 if (!stack.isActivityTypeStandardOrUndefined()) {
3090 throw new IllegalArgumentException(
3091 "Removing non-standard stack is not allowed.");
3092 }
3093 mStackSupervisor.removeStack(stack);
3094 } finally {
3095 Binder.restoreCallingIdentity(ident);
3096 }
3097 }
3098 }
3099
3100 @Override
3101 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003102 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103
3104 synchronized (mGlobalLock) {
3105 final long ident = Binder.clearCallingIdentity();
3106 try {
3107 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3108 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003109 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110 } finally {
3111 Binder.restoreCallingIdentity(ident);
3112 }
3113 }
3114 }
3115
3116 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 public void exitFreeformMode(IBinder token) {
3118 synchronized (mGlobalLock) {
3119 long ident = Binder.clearCallingIdentity();
3120 try {
3121 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3122 if (r == null) {
3123 throw new IllegalArgumentException(
3124 "exitFreeformMode: No activity record matching token=" + token);
3125 }
3126
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003127 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 if (stack == null || !stack.inFreeformWindowingMode()) {
3129 throw new IllegalStateException(
3130 "exitFreeformMode: You can only go fullscreen from freeform.");
3131 }
3132
3133 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3134 } finally {
3135 Binder.restoreCallingIdentity(ident);
3136 }
3137 }
3138 }
3139
3140 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3141 @Override
3142 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003143 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003145 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 }
3147
3148 /** Unregister a task stack listener so that it stops receiving callbacks. */
3149 @Override
3150 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003151 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003153 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 }
3155
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003156 @Override
3157 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3158 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3159 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3160 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3161 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3162 }
3163
3164 @Override
3165 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3166 IBinder activityToken, int flags) {
3167 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3168 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3169 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3170 }
3171
3172 @Override
3173 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3174 Bundle args) {
3175 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3176 true /* focused */, true /* newSessionId */, userHandle, args,
3177 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3178 }
3179
3180 @Override
3181 public Bundle getAssistContextExtras(int requestType) {
3182 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3183 null, null, true /* focused */, true /* newSessionId */,
3184 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3185 if (pae == null) {
3186 return null;
3187 }
3188 synchronized (pae) {
3189 while (!pae.haveResult) {
3190 try {
3191 pae.wait();
3192 } catch (InterruptedException e) {
3193 }
3194 }
3195 }
3196 synchronized (mGlobalLock) {
3197 buildAssistBundleLocked(pae, pae.result);
3198 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003199 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 }
3201 return pae.extras;
3202 }
3203
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003204 /**
3205 * Binder IPC calls go through the public entry point.
3206 * This can be called with or without the global lock held.
3207 */
3208 private static int checkCallingPermission(String permission) {
3209 return checkPermission(
3210 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3211 }
3212
3213 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003214 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003215 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3216 mAmInternal.enforceCallingPermission(permission, func);
3217 }
3218 }
3219
3220 @VisibleForTesting
3221 int checkGetTasksPermission(String permission, int pid, int uid) {
3222 return checkPermission(permission, pid, uid);
3223 }
3224
3225 static int checkPermission(String permission, int pid, int uid) {
3226 if (permission == null) {
3227 return PackageManager.PERMISSION_DENIED;
3228 }
3229 return checkComponentPermission(permission, pid, uid, -1, true);
3230 }
3231
Wale Ogunwale214f3482018-10-04 11:00:47 -07003232 public static int checkComponentPermission(String permission, int pid, int uid,
3233 int owningUid, boolean exported) {
3234 return ActivityManagerService.checkComponentPermission(
3235 permission, pid, uid, owningUid, exported);
3236 }
3237
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003238 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3239 if (getRecentTasks().isCallerRecents(callingUid)) {
3240 // Always allow the recents component to get tasks
3241 return true;
3242 }
3243
3244 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3245 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3246 if (!allowed) {
3247 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3248 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3249 // Temporary compatibility: some existing apps on the system image may
3250 // still be requesting the old permission and not switched to the new
3251 // one; if so, we'll still allow them full access. This means we need
3252 // to see if they are holding the old permission and are a system app.
3253 try {
3254 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3255 allowed = true;
3256 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3257 + " is using old GET_TASKS but privileged; allowing");
3258 }
3259 } catch (RemoteException e) {
3260 }
3261 }
3262 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3263 + " does not hold REAL_GET_TASKS; limiting output");
3264 }
3265 return allowed;
3266 }
3267
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3269 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3270 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3271 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003272 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003273 "enqueueAssistContext()");
3274
3275 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003276 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003277 if (activity == null) {
3278 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3279 return null;
3280 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003281 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003282 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3283 return null;
3284 }
3285 if (focused) {
3286 if (activityToken != null) {
3287 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3288 if (activity != caller) {
3289 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3290 + " is not current top " + activity);
3291 return null;
3292 }
3293 }
3294 } else {
3295 activity = ActivityRecord.forTokenLocked(activityToken);
3296 if (activity == null) {
3297 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3298 + " couldn't be found");
3299 return null;
3300 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003301 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3303 return null;
3304 }
3305 }
3306
3307 PendingAssistExtras pae;
3308 Bundle extras = new Bundle();
3309 if (args != null) {
3310 extras.putAll(args);
3311 }
3312 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003313 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314
3315 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3316 userHandle);
3317 pae.isHome = activity.isActivityTypeHome();
3318
3319 // Increment the sessionId if necessary
3320 if (newSessionId) {
3321 mViSessionId++;
3322 }
3323 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003324 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3325 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003326 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003327 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 } catch (RemoteException e) {
3329 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3330 return null;
3331 }
3332 return pae;
3333 }
3334 }
3335
3336 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3337 if (result != null) {
3338 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3339 }
3340 if (pae.hint != null) {
3341 pae.extras.putBoolean(pae.hint, true);
3342 }
3343 }
3344
3345 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3346 IAssistDataReceiver receiver;
3347 synchronized (mGlobalLock) {
3348 mPendingAssistExtras.remove(pae);
3349 receiver = pae.receiver;
3350 }
3351 if (receiver != null) {
3352 // Caller wants result sent back to them.
3353 Bundle sendBundle = new Bundle();
3354 // At least return the receiver extras
3355 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3356 try {
3357 pae.receiver.onHandleAssistData(sendBundle);
3358 } catch (RemoteException e) {
3359 }
3360 }
3361 }
3362
3363 public class PendingAssistExtras extends Binder implements Runnable {
3364 public final ActivityRecord activity;
3365 public boolean isHome;
3366 public final Bundle extras;
3367 public final Intent intent;
3368 public final String hint;
3369 public final IAssistDataReceiver receiver;
3370 public final int userHandle;
3371 public boolean haveResult = false;
3372 public Bundle result = null;
3373 public AssistStructure structure = null;
3374 public AssistContent content = null;
3375 public Bundle receiverExtras;
3376
3377 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3378 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3379 int _userHandle) {
3380 activity = _activity;
3381 extras = _extras;
3382 intent = _intent;
3383 hint = _hint;
3384 receiver = _receiver;
3385 receiverExtras = _receiverExtras;
3386 userHandle = _userHandle;
3387 }
3388
3389 @Override
3390 public void run() {
3391 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3392 synchronized (this) {
3393 haveResult = true;
3394 notifyAll();
3395 }
3396 pendingAssistExtrasTimedOut(this);
3397 }
3398 }
3399
3400 @Override
3401 public boolean isAssistDataAllowedOnCurrentActivity() {
3402 int userId;
3403 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003404 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3406 return false;
3407 }
3408
3409 final ActivityRecord activity = focusedStack.getTopActivity();
3410 if (activity == null) {
3411 return false;
3412 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003413 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 }
3415 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3416 }
3417
3418 @Override
3419 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3420 long ident = Binder.clearCallingIdentity();
3421 try {
3422 synchronized (mGlobalLock) {
3423 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003424 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 if (top != caller) {
3426 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3427 + " is not current top " + top);
3428 return false;
3429 }
3430 if (!top.nowVisible) {
3431 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3432 + " is not visible");
3433 return false;
3434 }
3435 }
3436 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3437 token);
3438 } finally {
3439 Binder.restoreCallingIdentity(ident);
3440 }
3441 }
3442
3443 @Override
3444 public boolean isRootVoiceInteraction(IBinder token) {
3445 synchronized (mGlobalLock) {
3446 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3447 if (r == null) {
3448 return false;
3449 }
3450 return r.rootVoiceInteraction;
3451 }
3452 }
3453
Wale Ogunwalef6733932018-06-27 05:14:34 -07003454 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3455 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3456 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3457 if (activityToCallback == null) return;
3458 activityToCallback.setVoiceSessionLocked(voiceSession);
3459
3460 // Inform the activity
3461 try {
3462 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3463 voiceInteractor);
3464 long token = Binder.clearCallingIdentity();
3465 try {
3466 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3467 } finally {
3468 Binder.restoreCallingIdentity(token);
3469 }
3470 // TODO: VI Should we cache the activity so that it's easier to find later
3471 // rather than scan through all the stacks and activities?
3472 } catch (RemoteException re) {
3473 activityToCallback.clearVoiceSessionLocked();
3474 // TODO: VI Should this terminate the voice session?
3475 }
3476 }
3477
3478 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3479 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3480 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3481 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3482 boolean wasRunningVoice = mRunningVoice != null;
3483 mRunningVoice = session;
3484 if (!wasRunningVoice) {
3485 mVoiceWakeLock.acquire();
3486 updateSleepIfNeededLocked();
3487 }
3488 }
3489 }
3490
3491 void finishRunningVoiceLocked() {
3492 if (mRunningVoice != null) {
3493 mRunningVoice = null;
3494 mVoiceWakeLock.release();
3495 updateSleepIfNeededLocked();
3496 }
3497 }
3498
3499 @Override
3500 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3501 synchronized (mGlobalLock) {
3502 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3503 if (keepAwake) {
3504 mVoiceWakeLock.acquire();
3505 } else {
3506 mVoiceWakeLock.release();
3507 }
3508 }
3509 }
3510 }
3511
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 @Override
3513 public ComponentName getActivityClassForToken(IBinder token) {
3514 synchronized (mGlobalLock) {
3515 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3516 if (r == null) {
3517 return null;
3518 }
3519 return r.intent.getComponent();
3520 }
3521 }
3522
3523 @Override
3524 public String getPackageForToken(IBinder token) {
3525 synchronized (mGlobalLock) {
3526 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3527 if (r == null) {
3528 return null;
3529 }
3530 return r.packageName;
3531 }
3532 }
3533
3534 @Override
3535 public void showLockTaskEscapeMessage(IBinder token) {
3536 synchronized (mGlobalLock) {
3537 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3538 if (r == null) {
3539 return;
3540 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003541 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003542 }
3543 }
3544
3545 @Override
3546 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003547 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 final long token = Binder.clearCallingIdentity();
3549 try {
3550 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003551 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 }
3553 } finally {
3554 Binder.restoreCallingIdentity(token);
3555 }
3556 }
3557
3558 /**
3559 * Try to place task to provided position. The final position might be different depending on
3560 * current user and stacks state. The task will be moved to target stack if it's currently in
3561 * different stack.
3562 */
3563 @Override
3564 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003565 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 synchronized (mGlobalLock) {
3567 long ident = Binder.clearCallingIdentity();
3568 try {
3569 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3570 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003571 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003572 if (task == null) {
3573 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3574 + taskId);
3575 }
3576
Wale Ogunwaled32da472018-11-16 07:19:28 -08003577 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003578
3579 if (stack == null) {
3580 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3581 + stackId);
3582 }
3583 if (!stack.isActivityTypeStandardOrUndefined()) {
3584 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3585 + " the position of task " + taskId + " in/to non-standard stack");
3586 }
3587
3588 // TODO: Have the callers of this API call a separate reparent method if that is
3589 // what they intended to do vs. having this method also do reparenting.
3590 if (task.getStack() == stack) {
3591 // Change position in current stack.
3592 stack.positionChildAt(task, position);
3593 } else {
3594 // Reparent to new stack.
3595 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3596 !DEFER_RESUME, "positionTaskInStack");
3597 }
3598 } finally {
3599 Binder.restoreCallingIdentity(ident);
3600 }
3601 }
3602 }
3603
3604 @Override
3605 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3606 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3607 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3608 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3609 synchronized (mGlobalLock) {
3610 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3611 if (record == null) {
3612 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3613 + "found for: " + token);
3614 }
3615 record.setSizeConfigurations(horizontalSizeConfiguration,
3616 verticalSizeConfigurations, smallestSizeConfigurations);
3617 }
3618 }
3619
3620 /**
3621 * Dismisses split-screen multi-window mode.
3622 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3623 */
3624 @Override
3625 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003626 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003627 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3628 final long ident = Binder.clearCallingIdentity();
3629 try {
3630 synchronized (mGlobalLock) {
3631 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003632 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 if (stack == null) {
3634 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3635 return;
3636 }
3637
3638 if (toTop) {
3639 // Caller wants the current split-screen primary stack to be the top stack after
3640 // it goes fullscreen, so move it to the front.
3641 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003642 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 // In this case the current split-screen primary stack shouldn't be the top
3644 // stack after it goes fullscreen, but it current has focus, so we move the
3645 // focus to the top-most split-screen secondary stack next to it.
3646 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3647 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3648 if (otherStack != null) {
3649 otherStack.moveToFront("dismissSplitScreenMode_other");
3650 }
3651 }
3652
Evan Rosky10475742018-09-05 19:02:48 -07003653 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 }
3655 } finally {
3656 Binder.restoreCallingIdentity(ident);
3657 }
3658 }
3659
3660 /**
3661 * Dismisses Pip
3662 * @param animate True if the dismissal should be animated.
3663 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3664 * default animation duration should be used.
3665 */
3666 @Override
3667 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003668 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 final long ident = Binder.clearCallingIdentity();
3670 try {
3671 synchronized (mGlobalLock) {
3672 final PinnedActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003673 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003674 if (stack == null) {
3675 Slog.w(TAG, "dismissPip: pinned stack not found.");
3676 return;
3677 }
3678 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3679 throw new IllegalArgumentException("Stack: " + stack
3680 + " doesn't support animated resize.");
3681 }
3682 if (animate) {
3683 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3684 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3685 } else {
3686 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3687 }
3688 }
3689 } finally {
3690 Binder.restoreCallingIdentity(ident);
3691 }
3692 }
3693
3694 @Override
3695 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003696 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 synchronized (mGlobalLock) {
3698 mSuppressResizeConfigChanges = suppress;
3699 }
3700 }
3701
3702 /**
3703 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3704 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3705 * activity and clearing the task at the same time.
3706 */
3707 @Override
3708 // TODO: API should just be about changing windowing modes...
3709 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 "moveTasksToFullscreenStack()");
3712 synchronized (mGlobalLock) {
3713 final long origId = Binder.clearCallingIdentity();
3714 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003715 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 if (stack != null){
3717 if (!stack.isActivityTypeStandardOrUndefined()) {
3718 throw new IllegalArgumentException(
3719 "You can't move tasks from non-standard stacks.");
3720 }
3721 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3722 }
3723 } finally {
3724 Binder.restoreCallingIdentity(origId);
3725 }
3726 }
3727 }
3728
3729 /**
3730 * Moves the top activity in the input stackId to the pinned stack.
3731 *
3732 * @param stackId Id of stack to move the top activity to pinned stack.
3733 * @param bounds Bounds to use for pinned stack.
3734 *
3735 * @return True if the top activity of the input stack was successfully moved to the pinned
3736 * stack.
3737 */
3738 @Override
3739 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003740 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003741 "moveTopActivityToPinnedStack()");
3742 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003743 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3745 + "Device doesn't support picture-in-picture mode");
3746 }
3747
3748 long ident = Binder.clearCallingIdentity();
3749 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003750 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 } finally {
3752 Binder.restoreCallingIdentity(ident);
3753 }
3754 }
3755 }
3756
3757 @Override
3758 public boolean isInMultiWindowMode(IBinder token) {
3759 final long origId = Binder.clearCallingIdentity();
3760 try {
3761 synchronized (mGlobalLock) {
3762 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3763 if (r == null) {
3764 return false;
3765 }
3766 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3767 return r.inMultiWindowMode();
3768 }
3769 } finally {
3770 Binder.restoreCallingIdentity(origId);
3771 }
3772 }
3773
3774 @Override
3775 public boolean isInPictureInPictureMode(IBinder token) {
3776 final long origId = Binder.clearCallingIdentity();
3777 try {
3778 synchronized (mGlobalLock) {
3779 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3780 }
3781 } finally {
3782 Binder.restoreCallingIdentity(origId);
3783 }
3784 }
3785
3786 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003787 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3788 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003789 return false;
3790 }
3791
3792 // If we are animating to fullscreen then we have already dispatched the PIP mode
3793 // changed, so we should reflect that check here as well.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003794 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3796 return !windowController.isAnimatingBoundsToFullscreen();
3797 }
3798
3799 @Override
3800 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3801 final long origId = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mGlobalLock) {
3804 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3805 "enterPictureInPictureMode", token, params);
3806
3807 // If the activity is already in picture in picture mode, then just return early
3808 if (isInPictureInPictureMode(r)) {
3809 return true;
3810 }
3811
3812 // Activity supports picture-in-picture, now check that we can enter PiP at this
3813 // point, if it is
3814 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3815 false /* beforeStopping */)) {
3816 return false;
3817 }
3818
3819 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003820 synchronized (mGlobalLock) {
3821 // Only update the saved args from the args that are set
3822 r.pictureInPictureArgs.copyOnlySet(params);
3823 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3824 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3825 // Adjust the source bounds by the insets for the transition down
3826 final Rect sourceBounds = new Rect(
3827 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003828 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003829 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003830 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003831 stack.setPictureInPictureAspectRatio(aspectRatio);
3832 stack.setPictureInPictureActions(actions);
3833 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3834 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3835 logPictureInPictureArgs(params);
3836 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 };
3838
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003839 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 // If the keyguard is showing or occluded, then try and dismiss it before
3841 // entering picture-in-picture (this will prompt the user to authenticate if the
3842 // device is currently locked).
3843 dismissKeyguard(token, new KeyguardDismissCallback() {
3844 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003845 public void onDismissSucceeded() {
3846 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 }
3848 }, null /* message */);
3849 } else {
3850 // Enter picture in picture immediately otherwise
3851 enterPipRunnable.run();
3852 }
3853 return true;
3854 }
3855 } finally {
3856 Binder.restoreCallingIdentity(origId);
3857 }
3858 }
3859
3860 @Override
3861 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3862 final long origId = Binder.clearCallingIdentity();
3863 try {
3864 synchronized (mGlobalLock) {
3865 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3866 "setPictureInPictureParams", token, params);
3867
3868 // Only update the saved args from the args that are set
3869 r.pictureInPictureArgs.copyOnlySet(params);
3870 if (r.inPinnedWindowingMode()) {
3871 // If the activity is already in picture-in-picture, update the pinned stack now
3872 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3873 // be used the next time the activity enters PiP
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003874 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875 if (!stack.isAnimatingBoundsToFullscreen()) {
3876 stack.setPictureInPictureAspectRatio(
3877 r.pictureInPictureArgs.getAspectRatio());
3878 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3879 }
3880 }
3881 logPictureInPictureArgs(params);
3882 }
3883 } finally {
3884 Binder.restoreCallingIdentity(origId);
3885 }
3886 }
3887
3888 @Override
3889 public int getMaxNumPictureInPictureActions(IBinder token) {
3890 // Currently, this is a static constant, but later, we may change this to be dependent on
3891 // the context of the activity
3892 return 3;
3893 }
3894
3895 private void logPictureInPictureArgs(PictureInPictureParams params) {
3896 if (params.hasSetActions()) {
3897 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3898 params.getActions().size());
3899 }
3900 if (params.hasSetAspectRatio()) {
3901 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3902 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3903 MetricsLogger.action(lm);
3904 }
3905 }
3906
3907 /**
3908 * Checks the state of the system and the activity associated with the given {@param token} to
3909 * verify that picture-in-picture is supported for that activity.
3910 *
3911 * @return the activity record for the given {@param token} if all the checks pass.
3912 */
3913 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3914 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003915 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 throw new IllegalStateException(caller
3917 + ": Device doesn't support picture-in-picture mode.");
3918 }
3919
3920 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3921 if (r == null) {
3922 throw new IllegalStateException(caller
3923 + ": Can't find activity for token=" + token);
3924 }
3925
3926 if (!r.supportsPictureInPicture()) {
3927 throw new IllegalStateException(caller
3928 + ": Current activity does not support picture-in-picture.");
3929 }
3930
3931 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003932 && !mWindowManager.isValidPictureInPictureAspectRatio(
3933 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 final float minAspectRatio = mContext.getResources().getFloat(
3935 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3936 final float maxAspectRatio = mContext.getResources().getFloat(
3937 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3938 throw new IllegalArgumentException(String.format(caller
3939 + ": Aspect ratio is too extreme (must be between %f and %f).",
3940 minAspectRatio, maxAspectRatio));
3941 }
3942
3943 // Truncate the number of actions if necessary
3944 params.truncateActions(getMaxNumPictureInPictureActions(token));
3945
3946 return r;
3947 }
3948
3949 @Override
3950 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003951 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 synchronized (mGlobalLock) {
3953 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3954 if (r == null) {
3955 throw new IllegalArgumentException("Activity does not exist; token="
3956 + activityToken);
3957 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003958 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 }
3960 }
3961
3962 @Override
3963 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3964 Rect tempDockedTaskInsetBounds,
3965 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003966 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003967 long ident = Binder.clearCallingIdentity();
3968 try {
3969 synchronized (mGlobalLock) {
3970 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3971 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3972 PRESERVE_WINDOWS);
3973 }
3974 } finally {
3975 Binder.restoreCallingIdentity(ident);
3976 }
3977 }
3978
3979 @Override
3980 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003981 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982 final long ident = Binder.clearCallingIdentity();
3983 try {
3984 synchronized (mGlobalLock) {
3985 mStackSupervisor.setSplitScreenResizing(resizing);
3986 }
3987 } finally {
3988 Binder.restoreCallingIdentity(ident);
3989 }
3990 }
3991
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 /**
3993 * Check that we have the features required for VR-related API calls, and throw an exception if
3994 * not.
3995 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003996 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003997 if (!mContext.getPackageManager().hasSystemFeature(
3998 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3999 throw new UnsupportedOperationException("VR mode not supported on this device!");
4000 }
4001 }
4002
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 @Override
4004 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004005 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006
4007 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4008
4009 ActivityRecord r;
4010 synchronized (mGlobalLock) {
4011 r = ActivityRecord.isInStackLocked(token);
4012 }
4013
4014 if (r == null) {
4015 throw new IllegalArgumentException();
4016 }
4017
4018 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004019 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 VrManagerInternal.NO_ERROR) {
4021 return err;
4022 }
4023
4024 // Clear the binder calling uid since this path may call moveToTask().
4025 final long callingId = Binder.clearCallingIdentity();
4026 try {
4027 synchronized (mGlobalLock) {
4028 r.requestedVrComponent = (enabled) ? packageName : null;
4029
4030 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004031 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004032 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 }
4034 return 0;
4035 }
4036 } finally {
4037 Binder.restoreCallingIdentity(callingId);
4038 }
4039 }
4040
4041 @Override
4042 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4043 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4044 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004045 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4047 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4048 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004049 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 || activity.voiceSession != null) {
4051 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4052 return;
4053 }
4054 if (activity.pendingVoiceInteractionStart) {
4055 Slog.w(TAG, "Pending start of voice interaction already.");
4056 return;
4057 }
4058 activity.pendingVoiceInteractionStart = true;
4059 }
4060 LocalServices.getService(VoiceInteractionManagerInternal.class)
4061 .startLocalVoiceInteraction(callingActivity, options);
4062 }
4063
4064 @Override
4065 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4066 LocalServices.getService(VoiceInteractionManagerInternal.class)
4067 .stopLocalVoiceInteraction(callingActivity);
4068 }
4069
4070 @Override
4071 public boolean supportsLocalVoiceInteraction() {
4072 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4073 .supportsLocalVoiceInteraction();
4074 }
4075
4076 /** Notifies all listeners when the pinned stack animation starts. */
4077 @Override
4078 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004079 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 }
4081
4082 /** Notifies all listeners when the pinned stack animation ends. */
4083 @Override
4084 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004085 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 }
4087
4088 @Override
4089 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004090 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 final long ident = Binder.clearCallingIdentity();
4092 try {
4093 synchronized (mGlobalLock) {
4094 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4095 }
4096 } finally {
4097 Binder.restoreCallingIdentity(ident);
4098 }
4099 }
4100
4101 @Override
4102 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004103 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004104
4105 synchronized (mGlobalLock) {
4106 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004107 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004108 // Call might come when display is not yet added or has already been removed.
4109 if (DEBUG_CONFIGURATION) {
4110 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4111 + displayId);
4112 }
4113 return false;
4114 }
4115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004116 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004118 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 }
4120
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004121 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004122 final Message msg = PooledLambda.obtainMessage(
4123 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4124 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 }
4126
4127 final long origId = Binder.clearCallingIdentity();
4128 try {
4129 if (values != null) {
4130 Settings.System.clearConfiguration(values);
4131 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004132 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4134 return mTmpUpdateConfigurationResult.changes != 0;
4135 } finally {
4136 Binder.restoreCallingIdentity(origId);
4137 }
4138 }
4139 }
4140
4141 @Override
4142 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004143 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144
4145 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004146 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004148 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 }
4150
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004151 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004152 final Message msg = PooledLambda.obtainMessage(
4153 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4154 DEFAULT_DISPLAY);
4155 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 }
4157
4158 final long origId = Binder.clearCallingIdentity();
4159 try {
4160 if (values != null) {
4161 Settings.System.clearConfiguration(values);
4162 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004163 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 UserHandle.USER_NULL, false /* deferResume */,
4165 mTmpUpdateConfigurationResult);
4166 return mTmpUpdateConfigurationResult.changes != 0;
4167 } finally {
4168 Binder.restoreCallingIdentity(origId);
4169 }
4170 }
4171 }
4172
4173 @Override
4174 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4175 CharSequence message) {
4176 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004177 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4179 }
4180 final long callingId = Binder.clearCallingIdentity();
4181 try {
4182 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004183 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004184 }
4185 } finally {
4186 Binder.restoreCallingIdentity(callingId);
4187 }
4188 }
4189
4190 @Override
4191 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 "cancelTaskWindowTransition()");
4194 final long ident = Binder.clearCallingIdentity();
4195 try {
4196 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004197 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198 MATCH_TASK_IN_STACKS_ONLY);
4199 if (task == null) {
4200 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4201 return;
4202 }
4203 task.cancelWindowTransition();
4204 }
4205 } finally {
4206 Binder.restoreCallingIdentity(ident);
4207 }
4208 }
4209
4210 @Override
4211 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004212 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 final long ident = Binder.clearCallingIdentity();
4214 try {
4215 final TaskRecord task;
4216 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004217 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4219 if (task == null) {
4220 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4221 return null;
4222 }
4223 }
4224 // Don't call this while holding the lock as this operation might hit the disk.
4225 return task.getSnapshot(reducedResolution);
4226 } finally {
4227 Binder.restoreCallingIdentity(ident);
4228 }
4229 }
4230
4231 @Override
4232 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4233 synchronized (mGlobalLock) {
4234 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4235 if (r == null) {
4236 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4237 + token);
4238 return;
4239 }
4240 final long origId = Binder.clearCallingIdentity();
4241 try {
4242 r.setDisablePreviewScreenshots(disable);
4243 } finally {
4244 Binder.restoreCallingIdentity(origId);
4245 }
4246 }
4247 }
4248
4249 /** Return the user id of the last resumed activity. */
4250 @Override
4251 public @UserIdInt
4252 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4255 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004256 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004257 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004259 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004260 }
4261 }
4262
4263 @Override
4264 public void updateLockTaskFeatures(int userId, int flags) {
4265 final int callingUid = Binder.getCallingUid();
4266 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004267 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 "updateLockTaskFeatures()");
4269 }
4270 synchronized (mGlobalLock) {
4271 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4272 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004273 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 }
4275 }
4276
4277 @Override
4278 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4279 synchronized (mGlobalLock) {
4280 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4281 if (r == null) {
4282 return;
4283 }
4284 final long origId = Binder.clearCallingIdentity();
4285 try {
4286 r.setShowWhenLocked(showWhenLocked);
4287 } finally {
4288 Binder.restoreCallingIdentity(origId);
4289 }
4290 }
4291 }
4292
4293 @Override
4294 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4295 synchronized (mGlobalLock) {
4296 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4297 if (r == null) {
4298 return;
4299 }
4300 final long origId = Binder.clearCallingIdentity();
4301 try {
4302 r.setTurnScreenOn(turnScreenOn);
4303 } finally {
4304 Binder.restoreCallingIdentity(origId);
4305 }
4306 }
4307 }
4308
4309 @Override
4310 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 "registerRemoteAnimations");
4313 definition.setCallingPid(Binder.getCallingPid());
4314 synchronized (mGlobalLock) {
4315 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4316 if (r == null) {
4317 return;
4318 }
4319 final long origId = Binder.clearCallingIdentity();
4320 try {
4321 r.registerRemoteAnimations(definition);
4322 } finally {
4323 Binder.restoreCallingIdentity(origId);
4324 }
4325 }
4326 }
4327
4328 @Override
4329 public void registerRemoteAnimationForNextActivityStart(String packageName,
4330 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004331 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 "registerRemoteAnimationForNextActivityStart");
4333 adapter.setCallingPid(Binder.getCallingPid());
4334 synchronized (mGlobalLock) {
4335 final long origId = Binder.clearCallingIdentity();
4336 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004337 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004338 packageName, adapter);
4339 } finally {
4340 Binder.restoreCallingIdentity(origId);
4341 }
4342 }
4343 }
4344
4345 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4346 @Override
4347 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4348 synchronized (mGlobalLock) {
4349 final long origId = Binder.clearCallingIdentity();
4350 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004351 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 } finally {
4353 Binder.restoreCallingIdentity(origId);
4354 }
4355 }
4356 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004357
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004358 @Override
4359 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004360 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004362 final int pid = Binder.getCallingPid();
4363 final WindowProcessController wpc = mPidMap.get(pid);
4364 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004365 }
4366 }
4367
4368 @Override
4369 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004370 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004371 != PERMISSION_GRANTED) {
4372 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4373 + Binder.getCallingPid()
4374 + ", uid=" + Binder.getCallingUid()
4375 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4376 Slog.w(TAG, msg);
4377 throw new SecurityException(msg);
4378 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004380 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004381 final int pid = Binder.getCallingPid();
4382 final WindowProcessController proc = mPidMap.get(pid);
4383 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004384 }
4385 }
4386
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 @Override
4388 public void stopAppSwitches() {
4389 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4390 synchronized (mGlobalLock) {
4391 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4392 mDidAppSwitch = false;
4393 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4394 }
4395 }
4396
4397 @Override
4398 public void resumeAppSwitches() {
4399 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4400 synchronized (mGlobalLock) {
4401 // Note that we don't execute any pending app switches... we will
4402 // let those wait until either the timeout, or the next start
4403 // activity request.
4404 mAppSwitchesAllowedTime = 0;
4405 }
4406 }
4407
4408 void onStartActivitySetDidAppSwitch() {
4409 if (mDidAppSwitch) {
4410 // This is the second allowed switch since we stopped switches, so now just generally
4411 // allow switches. Use case:
4412 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4413 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4414 // anyone to switch again).
4415 mAppSwitchesAllowedTime = 0;
4416 } else {
4417 mDidAppSwitch = true;
4418 }
4419 }
4420
4421 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004422 boolean shouldDisableNonVrUiLocked() {
4423 return mVrController.shouldDisableNonVrUiLocked();
4424 }
4425
Wale Ogunwale53783742018-09-16 10:21:51 -07004426 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004427 // VR apps are expected to run in a main display. If an app is turning on VR for
4428 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4429 // fullscreen stack before enabling VR Mode.
4430 // TODO: The goal of this code is to keep the VR app on the main display. When the
4431 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4432 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4433 // option would be a better choice here.
4434 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4435 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4436 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004437 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004438 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004439 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004440 }
4441 mH.post(() -> {
4442 if (!mVrController.onVrModeChanged(r)) {
4443 return;
4444 }
4445 synchronized (mGlobalLock) {
4446 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4447 mWindowManager.disableNonVrUi(disableNonVrUi);
4448 if (disableNonVrUi) {
4449 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4450 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004451 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004452 }
4453 }
4454 });
4455 }
4456
Wale Ogunwale53783742018-09-16 10:21:51 -07004457 @Override
4458 public int getPackageScreenCompatMode(String packageName) {
4459 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4460 synchronized (mGlobalLock) {
4461 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4462 }
4463 }
4464
4465 @Override
4466 public void setPackageScreenCompatMode(String packageName, int mode) {
4467 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4468 "setPackageScreenCompatMode");
4469 synchronized (mGlobalLock) {
4470 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4471 }
4472 }
4473
4474 @Override
4475 public boolean getPackageAskScreenCompat(String packageName) {
4476 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4477 synchronized (mGlobalLock) {
4478 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4479 }
4480 }
4481
4482 @Override
4483 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4484 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4485 "setPackageAskScreenCompat");
4486 synchronized (mGlobalLock) {
4487 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4488 }
4489 }
4490
Wale Ogunwale64258362018-10-16 15:13:37 -07004491 public static String relaunchReasonToString(int relaunchReason) {
4492 switch (relaunchReason) {
4493 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4494 return "window_resize";
4495 case RELAUNCH_REASON_FREE_RESIZE:
4496 return "free_resize";
4497 default:
4498 return null;
4499 }
4500 }
4501
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004502 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004503 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004504 }
4505
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004506 /** Pokes the task persister. */
4507 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4508 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4509 }
4510
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004511 boolean isKeyguardLocked() {
4512 return mKeyguardController.isKeyguardLocked();
4513 }
4514
Garfield Tan01548632018-11-27 10:15:48 -08004515 /**
4516 * Clears launch params for the given package.
4517 * @param packageNames the names of the packages of which the launch params are to be cleared
4518 */
4519 @Override
4520 public void clearLaunchParamsForPackages(List<String> packageNames) {
4521 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4522 "clearLaunchParamsForPackages");
4523 synchronized (mGlobalLock) {
4524 for (int i = 0; i < packageNames.size(); ++i) {
4525 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4526 }
4527 }
4528 }
4529
Wale Ogunwale31913b52018-10-13 08:29:31 -07004530 void dumpLastANRLocked(PrintWriter pw) {
4531 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4532 if (mLastANRState == null) {
4533 pw.println(" <no ANR has occurred since boot>");
4534 } else {
4535 pw.println(mLastANRState);
4536 }
4537 }
4538
4539 void dumpLastANRTracesLocked(PrintWriter pw) {
4540 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4541
4542 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4543 if (ArrayUtils.isEmpty(files)) {
4544 pw.println(" <no ANR has occurred since boot>");
4545 return;
4546 }
4547 // Find the latest file.
4548 File latest = null;
4549 for (File f : files) {
4550 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4551 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004552 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004553 }
4554 pw.print("File: ");
4555 pw.print(latest.getName());
4556 pw.println();
4557 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4558 String line;
4559 while ((line = in.readLine()) != null) {
4560 pw.println(line);
4561 }
4562 } catch (IOException e) {
4563 pw.print("Unable to read: ");
4564 pw.print(e);
4565 pw.println();
4566 }
4567 }
4568
4569 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4570 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4571 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4572 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4573 }
4574
4575 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4576 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4577 pw.println(header);
4578
Wale Ogunwaled32da472018-11-16 07:19:28 -08004579 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004580 dumpPackage);
4581 boolean needSep = printedAnything;
4582
4583 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004584 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004585 " ResumedActivity: ");
4586 if (printed) {
4587 printedAnything = true;
4588 needSep = false;
4589 }
4590
4591 if (dumpPackage == null) {
4592 if (needSep) {
4593 pw.println();
4594 }
4595 printedAnything = true;
4596 mStackSupervisor.dump(pw, " ");
4597 }
4598
4599 if (!printedAnything) {
4600 pw.println(" (nothing)");
4601 }
4602 }
4603
4604 void dumpActivityContainersLocked(PrintWriter pw) {
4605 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004606 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004607 pw.println(" ");
4608 }
4609
4610 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4611 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4612 getActivityStartController().dump(pw, "", dumpPackage);
4613 }
4614
4615 /**
4616 * There are three things that cmd can be:
4617 * - a flattened component name that matches an existing activity
4618 * - the cmd arg isn't the flattened component name of an existing activity:
4619 * dump all activity whose component contains the cmd as a substring
4620 * - A hex number of the ActivityRecord object instance.
4621 *
4622 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4623 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4624 */
4625 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4626 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4627 ArrayList<ActivityRecord> activities;
4628
4629 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004630 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004631 dumpFocusedStackOnly);
4632 }
4633
4634 if (activities.size() <= 0) {
4635 return false;
4636 }
4637
4638 String[] newArgs = new String[args.length - opti];
4639 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4640
4641 TaskRecord lastTask = null;
4642 boolean needSep = false;
4643 for (int i = activities.size() - 1; i >= 0; i--) {
4644 ActivityRecord r = activities.get(i);
4645 if (needSep) {
4646 pw.println();
4647 }
4648 needSep = true;
4649 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004650 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004651 if (lastTask != task) {
4652 lastTask = task;
4653 pw.print("TASK "); pw.print(lastTask.affinity);
4654 pw.print(" id="); pw.print(lastTask.taskId);
4655 pw.print(" userId="); pw.println(lastTask.userId);
4656 if (dumpAll) {
4657 lastTask.dump(pw, " ");
4658 }
4659 }
4660 }
4661 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4662 }
4663 return true;
4664 }
4665
4666 /**
4667 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4668 * there is a thread associated with the activity.
4669 */
4670 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4671 final ActivityRecord r, String[] args, boolean dumpAll) {
4672 String innerPrefix = prefix + " ";
4673 synchronized (mGlobalLock) {
4674 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4675 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4676 pw.print(" pid=");
4677 if (r.hasProcess()) pw.println(r.app.getPid());
4678 else pw.println("(not running)");
4679 if (dumpAll) {
4680 r.dump(pw, innerPrefix);
4681 }
4682 }
4683 if (r.attachedToProcess()) {
4684 // flush anything that is already in the PrintWriter since the thread is going
4685 // to write to the file descriptor directly
4686 pw.flush();
4687 try {
4688 TransferPipe tp = new TransferPipe();
4689 try {
4690 r.app.getThread().dumpActivity(tp.getWriteFd(),
4691 r.appToken, innerPrefix, args);
4692 tp.go(fd);
4693 } finally {
4694 tp.kill();
4695 }
4696 } catch (IOException e) {
4697 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4698 } catch (RemoteException e) {
4699 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4700 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004701 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 }
4703
Wale Ogunwalef6733932018-06-27 05:14:34 -07004704 void writeSleepStateToProto(ProtoOutputStream proto) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004705 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004706 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4707 st.toString());
4708 }
4709
4710 if (mRunningVoice != null) {
4711 final long vrToken = proto.start(
4712 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4713 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4714 mRunningVoice.toString());
4715 mVoiceWakeLock.writeToProto(
4716 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4717 proto.end(vrToken);
4718 }
4719
4720 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4721 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4722 mShuttingDown);
4723 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 }
4725
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004726 int getCurrentUserId() {
4727 return mAmInternal.getCurrentUserId();
4728 }
4729
4730 private void enforceNotIsolatedCaller(String caller) {
4731 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4732 throw new SecurityException("Isolated process not allowed to call " + caller);
4733 }
4734 }
4735
Wale Ogunwalef6733932018-06-27 05:14:34 -07004736 public Configuration getConfiguration() {
4737 Configuration ci;
4738 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004739 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004740 ci.userSetLocale = false;
4741 }
4742 return ci;
4743 }
4744
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 /**
4746 * Current global configuration information. Contains general settings for the entire system,
4747 * also corresponds to the merged configuration of the default display.
4748 */
4749 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004750 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004751 }
4752
4753 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4754 boolean initLocale) {
4755 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4756 }
4757
4758 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4759 boolean initLocale, boolean deferResume) {
4760 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4761 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4762 UserHandle.USER_NULL, deferResume);
4763 }
4764
Wale Ogunwale59507092018-10-29 09:00:30 -07004765 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004766 final long origId = Binder.clearCallingIdentity();
4767 try {
4768 synchronized (mGlobalLock) {
4769 updateConfigurationLocked(values, null, false, true, userId,
4770 false /* deferResume */);
4771 }
4772 } finally {
4773 Binder.restoreCallingIdentity(origId);
4774 }
4775 }
4776
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004777 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4778 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4779 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4780 deferResume, null /* result */);
4781 }
4782
4783 /**
4784 * Do either or both things: (1) change the current configuration, and (2)
4785 * make sure the given activity is running with the (now) current
4786 * configuration. Returns true if the activity has been left running, or
4787 * false if <var>starting</var> is being destroyed to match the new
4788 * configuration.
4789 *
4790 * @param userId is only used when persistent parameter is set to true to persist configuration
4791 * for that particular user
4792 */
4793 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4794 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4795 ActivityTaskManagerService.UpdateConfigurationResult result) {
4796 int changes = 0;
4797 boolean kept = true;
4798
4799 if (mWindowManager != null) {
4800 mWindowManager.deferSurfaceLayout();
4801 }
4802 try {
4803 if (values != null) {
4804 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4805 deferResume);
4806 }
4807
4808 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4809 } finally {
4810 if (mWindowManager != null) {
4811 mWindowManager.continueSurfaceLayout();
4812 }
4813 }
4814
4815 if (result != null) {
4816 result.changes = changes;
4817 result.activityRelaunched = !kept;
4818 }
4819 return kept;
4820 }
4821
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004822 /** Update default (global) configuration and notify listeners about changes. */
4823 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4824 boolean persistent, int userId, boolean deferResume) {
4825 mTempConfig.setTo(getGlobalConfiguration());
4826 final int changes = mTempConfig.updateFrom(values);
4827 if (changes == 0) {
4828 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4829 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4830 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4831 // (even if there are no actual changes) to unfreeze the window.
4832 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4833 return 0;
4834 }
4835
4836 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4837 "Updating global configuration to: " + values);
4838
4839 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4840 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4841 values.colorMode,
4842 values.densityDpi,
4843 values.fontScale,
4844 values.hardKeyboardHidden,
4845 values.keyboard,
4846 values.keyboardHidden,
4847 values.mcc,
4848 values.mnc,
4849 values.navigation,
4850 values.navigationHidden,
4851 values.orientation,
4852 values.screenHeightDp,
4853 values.screenLayout,
4854 values.screenWidthDp,
4855 values.smallestScreenWidthDp,
4856 values.touchscreen,
4857 values.uiMode);
4858
4859
4860 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4861 final LocaleList locales = values.getLocales();
4862 int bestLocaleIndex = 0;
4863 if (locales.size() > 1) {
4864 if (mSupportedSystemLocales == null) {
4865 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4866 }
4867 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4868 }
4869 SystemProperties.set("persist.sys.locale",
4870 locales.get(bestLocaleIndex).toLanguageTag());
4871 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004872
4873 final Message m = PooledLambda.obtainMessage(
4874 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4875 locales.get(bestLocaleIndex));
4876 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004877 }
4878
Yunfan Chen75157d72018-07-27 14:47:21 +09004879 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004880
4881 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004882 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004883
4884 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4885 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004886 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004887
4888 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004889 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890
4891 AttributeCache ac = AttributeCache.instance();
4892 if (ac != null) {
4893 ac.updateConfiguration(mTempConfig);
4894 }
4895
4896 // Make sure all resources in our process are updated right now, so that anyone who is going
4897 // to retrieve resource values after we return will be sure to get the new ones. This is
4898 // especially important during boot, where the first config change needs to guarantee all
4899 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004900 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004901
4902 // We need another copy of global config because we're scheduling some calls instead of
4903 // running them in place. We need to be sure that object we send will be handled unchanged.
4904 final Configuration configCopy = new Configuration(mTempConfig);
4905 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004906 final Message msg = PooledLambda.obtainMessage(
4907 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4908 this, userId, configCopy);
4909 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004910 }
4911
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004912 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004913 final int pid = mPidMap.keyAt(i);
4914 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004915 if (DEBUG_CONFIGURATION) {
4916 Slog.v(TAG_CONFIGURATION, "Update process config of "
4917 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004918 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004919 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004920 }
4921
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004922 final Message msg = PooledLambda.obtainMessage(
4923 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4924 mAmInternal, changes, initLocale);
4925 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004926
4927 // Override configuration of the default display duplicates global config, so we need to
4928 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004929 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004930 DEFAULT_DISPLAY);
4931
4932 return changes;
4933 }
4934
4935 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4936 boolean deferResume, int displayId) {
4937 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4938 displayId, null /* result */);
4939 }
4940
4941 /**
4942 * Updates override configuration specific for the selected display. If no config is provided,
4943 * new one will be computed in WM based on current display info.
4944 */
4945 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4946 ActivityRecord starting, boolean deferResume, int displayId,
4947 ActivityTaskManagerService.UpdateConfigurationResult result) {
4948 int changes = 0;
4949 boolean kept = true;
4950
4951 if (mWindowManager != null) {
4952 mWindowManager.deferSurfaceLayout();
4953 }
4954 try {
4955 if (values != null) {
4956 if (displayId == DEFAULT_DISPLAY) {
4957 // Override configuration of the default display duplicates global config, so
4958 // we're calling global config update instead for default display. It will also
4959 // apply the correct override config.
4960 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4961 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4962 } else {
4963 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4964 }
4965 }
4966
4967 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4968 } finally {
4969 if (mWindowManager != null) {
4970 mWindowManager.continueSurfaceLayout();
4971 }
4972 }
4973
4974 if (result != null) {
4975 result.changes = changes;
4976 result.activityRelaunched = !kept;
4977 }
4978 return kept;
4979 }
4980
4981 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4982 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004983 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004984 final int changes = mTempConfig.updateFrom(values);
4985 if (changes != 0) {
4986 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4987 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08004988 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004989
4990 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4991 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004992 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004993
Wale Ogunwale5c918702018-10-18 11:06:33 -07004994 // Post message to start process to avoid possible deadlock of calling into AMS with
4995 // the ATMS lock held.
4996 final Message msg = PooledLambda.obtainMessage(
4997 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4998 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4999 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005000 }
5001 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005002 return changes;
5003 }
5004
Wale Ogunwalef6733932018-06-27 05:14:34 -07005005 private void updateEventDispatchingLocked(boolean booted) {
5006 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5007 }
5008
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005009 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5010 final ContentResolver resolver = mContext.getContentResolver();
5011 Settings.System.putConfigurationForUser(resolver, config, userId);
5012 }
5013
5014 private void sendLocaleToMountDaemonMsg(Locale l) {
5015 try {
5016 IBinder service = ServiceManager.getService("mount");
5017 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5018 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5019 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5020 } catch (RemoteException e) {
5021 Log.e(TAG, "Error storing locale for decryption UI", e);
5022 }
5023 }
5024
Alison Cichowlas3e340502018-08-07 17:15:01 -04005025 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5026 mStartActivitySources.remove(permissionToken);
5027 mExpiredStartAsCallerTokens.add(permissionToken);
5028 }
5029
5030 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5031 mExpiredStartAsCallerTokens.remove(permissionToken);
5032 }
5033
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005034 boolean isActivityStartsLoggingEnabled() {
5035 return mAmInternal.isActivityStartsLoggingEnabled();
5036 }
5037
Michal Karpinski8596ded2018-11-14 14:43:48 +00005038 boolean isBackgroundActivityStartsEnabled() {
5039 return mAmInternal.isBackgroundActivityStartsEnabled();
5040 }
5041
Wale Ogunwalef6733932018-06-27 05:14:34 -07005042 void enableScreenAfterBoot(boolean booted) {
5043 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5044 SystemClock.uptimeMillis());
5045 mWindowManager.enableScreenAfterBoot();
5046
5047 synchronized (mGlobalLock) {
5048 updateEventDispatchingLocked(booted);
5049 }
5050 }
5051
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005052 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5053 if (r == null || !r.hasProcess()) {
5054 return KEY_DISPATCHING_TIMEOUT_MS;
5055 }
5056 return getInputDispatchingTimeoutLocked(r.app);
5057 }
5058
5059 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005060 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005061 }
5062
Wale Ogunwalef6733932018-06-27 05:14:34 -07005063 /**
5064 * Decide based on the configuration whether we should show the ANR,
5065 * crash, etc dialogs. The idea is that if there is no affordance to
5066 * press the on-screen buttons, or the user experience would be more
5067 * greatly impacted than the crash itself, we shouldn't show the dialog.
5068 *
5069 * A thought: SystemUI might also want to get told about this, the Power
5070 * dialog / global actions also might want different behaviors.
5071 */
5072 private void updateShouldShowDialogsLocked(Configuration config) {
5073 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5074 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5075 && config.navigation == Configuration.NAVIGATION_NONAV);
5076 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5077 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5078 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5079 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5080 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5081 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5082 HIDE_ERROR_DIALOGS, 0) != 0;
5083 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5084 }
5085
5086 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5087 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5088 FONT_SCALE, 1.0f, userId);
5089
5090 synchronized (this) {
5091 if (getGlobalConfiguration().fontScale == scaleFactor) {
5092 return;
5093 }
5094
5095 final Configuration configuration
5096 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5097 configuration.fontScale = scaleFactor;
5098 updatePersistentConfiguration(configuration, userId);
5099 }
5100 }
5101
5102 // Actually is sleeping or shutting down or whatever else in the future
5103 // is an inactive state.
5104 boolean isSleepingOrShuttingDownLocked() {
5105 return isSleepingLocked() || mShuttingDown;
5106 }
5107
5108 boolean isSleepingLocked() {
5109 return mSleeping;
5110 }
5111
Riddle Hsu16567132018-08-16 21:37:47 +08005112 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005113 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005114 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005115 if (task.isActivityTypeStandard()) {
5116 if (mCurAppTimeTracker != r.appTimeTracker) {
5117 // We are switching app tracking. Complete the current one.
5118 if (mCurAppTimeTracker != null) {
5119 mCurAppTimeTracker.stop();
5120 mH.obtainMessage(
5121 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005122 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005123 mCurAppTimeTracker = null;
5124 }
5125 if (r.appTimeTracker != null) {
5126 mCurAppTimeTracker = r.appTimeTracker;
5127 startTimeTrackingFocusedActivityLocked();
5128 }
5129 } else {
5130 startTimeTrackingFocusedActivityLocked();
5131 }
5132 } else {
5133 r.appTimeTracker = null;
5134 }
5135 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5136 // TODO: Probably not, because we don't want to resume voice on switching
5137 // back to this activity
5138 if (task.voiceInteractor != null) {
5139 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5140 } else {
5141 finishRunningVoiceLocked();
5142
5143 if (mLastResumedActivity != null) {
5144 final IVoiceInteractionSession session;
5145
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005146 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147 if (lastResumedActivityTask != null
5148 && lastResumedActivityTask.voiceSession != null) {
5149 session = lastResumedActivityTask.voiceSession;
5150 } else {
5151 session = mLastResumedActivity.voiceSession;
5152 }
5153
5154 if (session != null) {
5155 // We had been in a voice interaction session, but now focused has
5156 // move to something different. Just finish the session, we can't
5157 // return to it and retain the proper state and synchronization with
5158 // the voice interaction service.
5159 finishVoiceTask(session);
5160 }
5161 }
5162 }
5163
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005164 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5165 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005166 }
5167 updateResumedAppTrace(r);
5168 mLastResumedActivity = r;
5169
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005170 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005171
5172 applyUpdateLockStateLocked(r);
5173 applyUpdateVrModeLocked(r);
5174
5175 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005176 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005177 r == null ? "NULL" : r.shortComponentName,
5178 reason);
5179 }
5180
5181 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5182 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005183 final ActivityTaskManagerInternal.SleepToken token =
5184 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005185 updateSleepIfNeededLocked();
5186 return token;
5187 }
5188 }
5189
5190 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005191 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005192 final boolean wasSleeping = mSleeping;
5193 boolean updateOomAdj = false;
5194
5195 if (!shouldSleep) {
5196 // If wasSleeping is true, we need to wake up activity manager state from when
5197 // we started sleeping. In either case, we need to apply the sleep tokens, which
5198 // will wake up stacks or put them to sleep as appropriate.
5199 if (wasSleeping) {
5200 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005201 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5202 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005203 startTimeTrackingFocusedActivityLocked();
5204 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5205 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5206 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005207 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005208 if (wasSleeping) {
5209 updateOomAdj = true;
5210 }
5211 } else if (!mSleeping && shouldSleep) {
5212 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005213 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5214 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005215 if (mCurAppTimeTracker != null) {
5216 mCurAppTimeTracker.stop();
5217 }
5218 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5219 mStackSupervisor.goingToSleepLocked();
5220 updateResumedAppTrace(null /* resumed */);
5221 updateOomAdj = true;
5222 }
5223 if (updateOomAdj) {
5224 mH.post(mAmInternal::updateOomAdj);
5225 }
5226 }
5227
5228 void updateOomAdj() {
5229 mH.post(mAmInternal::updateOomAdj);
5230 }
5231
Wale Ogunwale53783742018-09-16 10:21:51 -07005232 void updateCpuStats() {
5233 mH.post(mAmInternal::updateCpuStats);
5234 }
5235
5236 void updateUsageStats(ActivityRecord component, boolean resumed) {
5237 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005238 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5239 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005240 mH.sendMessage(m);
5241 }
5242
5243 void setBooting(boolean booting) {
5244 mAmInternal.setBooting(booting);
5245 }
5246
5247 boolean isBooting() {
5248 return mAmInternal.isBooting();
5249 }
5250
5251 void setBooted(boolean booted) {
5252 mAmInternal.setBooted(booted);
5253 }
5254
5255 boolean isBooted() {
5256 return mAmInternal.isBooted();
5257 }
5258
5259 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5260 mH.post(() -> {
5261 if (finishBooting) {
5262 mAmInternal.finishBooting();
5263 }
5264 if (enableScreen) {
5265 mInternal.enableScreenAfterBoot(isBooted());
5266 }
5267 });
5268 }
5269
5270 void setHeavyWeightProcess(ActivityRecord root) {
5271 mHeavyWeightProcess = root.app;
5272 final Message m = PooledLambda.obtainMessage(
5273 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005274 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005275 mH.sendMessage(m);
5276 }
5277
5278 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5279 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5280 return;
5281 }
5282
5283 mHeavyWeightProcess = null;
5284 final Message m = PooledLambda.obtainMessage(
5285 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5286 proc.mUserId);
5287 mH.sendMessage(m);
5288 }
5289
5290 private void cancelHeavyWeightProcessNotification(int userId) {
5291 final INotificationManager inm = NotificationManager.getService();
5292 if (inm == null) {
5293 return;
5294 }
5295 try {
5296 inm.cancelNotificationWithTag("android", null,
5297 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5298 } catch (RuntimeException e) {
5299 Slog.w(TAG, "Error canceling notification for service", e);
5300 } catch (RemoteException e) {
5301 }
5302
5303 }
5304
5305 private void postHeavyWeightProcessNotification(
5306 WindowProcessController proc, Intent intent, int userId) {
5307 if (proc == null) {
5308 return;
5309 }
5310
5311 final INotificationManager inm = NotificationManager.getService();
5312 if (inm == null) {
5313 return;
5314 }
5315
5316 try {
5317 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5318 String text = mContext.getString(R.string.heavy_weight_notification,
5319 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5320 Notification notification =
5321 new Notification.Builder(context,
5322 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5323 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5324 .setWhen(0)
5325 .setOngoing(true)
5326 .setTicker(text)
5327 .setColor(mContext.getColor(
5328 com.android.internal.R.color.system_notification_accent_color))
5329 .setContentTitle(text)
5330 .setContentText(
5331 mContext.getText(R.string.heavy_weight_notification_detail))
5332 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5333 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5334 new UserHandle(userId)))
5335 .build();
5336 try {
5337 inm.enqueueNotificationWithTag("android", "android", null,
5338 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5339 } catch (RuntimeException e) {
5340 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5341 } catch (RemoteException e) {
5342 }
5343 } catch (PackageManager.NameNotFoundException e) {
5344 Slog.w(TAG, "Unable to create context for heavy notification", e);
5345 }
5346
5347 }
5348
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005349 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5350 IBinder token, String resultWho, int requestCode, Intent[] intents,
5351 String[] resolvedTypes, int flags, Bundle bOptions) {
5352
5353 ActivityRecord activity = null;
5354 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5355 activity = ActivityRecord.isInStackLocked(token);
5356 if (activity == null) {
5357 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5358 return null;
5359 }
5360 if (activity.finishing) {
5361 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5362 return null;
5363 }
5364 }
5365
5366 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5367 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5368 bOptions);
5369 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5370 if (noCreate) {
5371 return rec;
5372 }
5373 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5374 if (activity.pendingResults == null) {
5375 activity.pendingResults = new HashSet<>();
5376 }
5377 activity.pendingResults.add(rec.ref);
5378 }
5379 return rec;
5380 }
5381
Andrii Kulian52d255c2018-07-13 11:32:19 -07005382 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005383 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005384 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005385 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5386 mCurAppTimeTracker.start(resumedActivity.packageName);
5387 }
5388 }
5389
5390 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5391 if (mTracedResumedActivity != null) {
5392 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5393 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5394 }
5395 if (resumed != null) {
5396 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5397 constructResumedTraceName(resumed.packageName), 0);
5398 }
5399 mTracedResumedActivity = resumed;
5400 }
5401
5402 private String constructResumedTraceName(String packageName) {
5403 return "focused app: " + packageName;
5404 }
5405
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005406 /** Applies latest configuration and/or visibility updates if needed. */
5407 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5408 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005409 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005410 // mainStack is null during startup.
5411 if (mainStack != null) {
5412 if (changes != 0 && starting == null) {
5413 // If the configuration changed, and the caller is not already
5414 // in the process of starting an activity, then find the top
5415 // activity to check if its configuration needs to change.
5416 starting = mainStack.topRunningActivityLocked();
5417 }
5418
5419 if (starting != null) {
5420 kept = starting.ensureActivityConfiguration(changes,
5421 false /* preserveWindow */);
5422 // And we need to make sure at this point that all other activities
5423 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005424 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005425 !PRESERVE_WINDOWS);
5426 }
5427 }
5428
5429 return kept;
5430 }
5431
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005432 void scheduleAppGcsLocked() {
5433 mH.post(() -> mAmInternal.scheduleAppGcs());
5434 }
5435
Wale Ogunwale53783742018-09-16 10:21:51 -07005436 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5437 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5438 }
5439
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005440 /**
5441 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5442 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5443 * on demand.
5444 */
5445 IPackageManager getPackageManager() {
5446 return AppGlobals.getPackageManager();
5447 }
5448
5449 PackageManagerInternal getPackageManagerInternalLocked() {
5450 if (mPmInternal == null) {
5451 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5452 }
5453 return mPmInternal;
5454 }
5455
Wale Ogunwale008163e2018-07-23 23:11:08 -07005456 AppWarnings getAppWarningsLocked() {
5457 return mAppWarnings;
5458 }
5459
Wale Ogunwale214f3482018-10-04 11:00:47 -07005460 Intent getHomeIntent() {
5461 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5462 intent.setComponent(mTopComponent);
5463 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5464 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5465 intent.addCategory(Intent.CATEGORY_HOME);
5466 }
5467 return intent;
5468 }
5469
Wale Ogunwale214f3482018-10-04 11:00:47 -07005470 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5471 if (info == null) return null;
5472 ApplicationInfo newInfo = new ApplicationInfo(info);
5473 newInfo.initForUser(userId);
5474 return newInfo;
5475 }
5476
Wale Ogunwale9c103022018-10-18 07:44:54 -07005477 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005478 if (uid == SYSTEM_UID) {
5479 // The system gets to run in any process. If there are multiple processes with the same
5480 // uid, just pick the first (this should never happen).
5481 final SparseArray<WindowProcessController> procs =
5482 mProcessNames.getMap().get(processName);
5483 if (procs == null) return null;
5484 final int procCount = procs.size();
5485 for (int i = 0; i < procCount; i++) {
5486 final int procUid = procs.keyAt(i);
5487 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5488 // Don't use an app process or different user process for system component.
5489 continue;
5490 }
5491 return procs.valueAt(i);
5492 }
5493 }
5494
5495 return mProcessNames.get(processName, uid);
5496 }
5497
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005498 WindowProcessController getProcessController(IApplicationThread thread) {
5499 if (thread == null) {
5500 return null;
5501 }
5502
5503 final IBinder threadBinder = thread.asBinder();
5504 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5505 for (int i = pmap.size()-1; i >= 0; i--) {
5506 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5507 for (int j = procs.size() - 1; j >= 0; j--) {
5508 final WindowProcessController proc = procs.valueAt(j);
5509 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5510 return proc;
5511 }
5512 }
5513 }
5514
5515 return null;
5516 }
5517
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005518 int getUidStateLocked(int uid) {
5519 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5520 }
5521
Wale Ogunwale9de19442018-10-18 19:05:03 -07005522 /**
5523 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5524 * the whitelist
5525 */
5526 String getPendingTempWhitelistTagForUidLocked(int uid) {
5527 return mPendingTempWhitelist.get(uid);
5528 }
5529
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005530 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5531 if (true || Build.IS_USER) {
5532 return;
5533 }
5534
5535 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5536 StrictMode.allowThreadDiskWrites();
5537 try {
5538 File tracesDir = new File("/data/anr");
5539 File tracesFile = null;
5540 try {
5541 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5542
5543 StringBuilder sb = new StringBuilder();
5544 Time tobj = new Time();
5545 tobj.set(System.currentTimeMillis());
5546 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5547 sb.append(": ");
5548 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5549 sb.append(" since ");
5550 sb.append(msg);
5551 FileOutputStream fos = new FileOutputStream(tracesFile);
5552 fos.write(sb.toString().getBytes());
5553 if (app == null) {
5554 fos.write("\n*** No application process!".getBytes());
5555 }
5556 fos.close();
5557 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5558 } catch (IOException e) {
5559 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5560 return;
5561 }
5562
5563 if (app != null && app.getPid() > 0) {
5564 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5565 firstPids.add(app.getPid());
5566 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5567 }
5568
5569 File lastTracesFile = null;
5570 File curTracesFile = null;
5571 for (int i=9; i>=0; i--) {
5572 String name = String.format(Locale.US, "slow%02d.txt", i);
5573 curTracesFile = new File(tracesDir, name);
5574 if (curTracesFile.exists()) {
5575 if (lastTracesFile != null) {
5576 curTracesFile.renameTo(lastTracesFile);
5577 } else {
5578 curTracesFile.delete();
5579 }
5580 }
5581 lastTracesFile = curTracesFile;
5582 }
5583 tracesFile.renameTo(curTracesFile);
5584 } finally {
5585 StrictMode.setThreadPolicy(oldPolicy);
5586 }
5587 }
5588
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005589 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005590 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005591
5592
Wale Ogunwale98875612018-10-12 07:53:02 -07005593 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5594 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595
Riddle Hsud93a6c42018-11-29 21:50:06 +08005596 H(Looper looper) {
5597 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005598 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005599
5600 @Override
5601 public void handleMessage(Message msg) {
5602 switch (msg.what) {
5603 case REPORT_TIME_TRACKER_MSG: {
5604 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5605 tracker.deliverResult(mContext);
5606 } break;
5607 }
5608 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005609 }
5610
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005611 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005612 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005613
5614 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005615 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005616 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005617
5618 @Override
5619 public void handleMessage(Message msg) {
5620 switch (msg.what) {
5621 case DISMISS_DIALOG_UI_MSG: {
5622 final Dialog d = (Dialog) msg.obj;
5623 d.dismiss();
5624 break;
5625 }
5626 }
5627 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005628 }
5629
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005630 final class LocalService extends ActivityTaskManagerInternal {
5631 @Override
5632 public SleepToken acquireSleepToken(String tag, int displayId) {
5633 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005634 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005635 }
5636
5637 @Override
5638 public ComponentName getHomeActivityForUser(int userId) {
5639 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005640 final ActivityRecord homeActivity =
5641 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005642 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005643 }
5644 }
5645
5646 @Override
5647 public void onLocalVoiceInteractionStarted(IBinder activity,
5648 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5649 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005650 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005651 }
5652 }
5653
5654 @Override
5655 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5656 synchronized (mGlobalLock) {
5657 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5658 reasons, timestamp);
5659 }
5660 }
5661
5662 @Override
5663 public void notifyAppTransitionFinished() {
5664 synchronized (mGlobalLock) {
5665 mStackSupervisor.notifyAppTransitionDone();
5666 }
5667 }
5668
5669 @Override
5670 public void notifyAppTransitionCancelled() {
5671 synchronized (mGlobalLock) {
5672 mStackSupervisor.notifyAppTransitionDone();
5673 }
5674 }
5675
5676 @Override
5677 public List<IBinder> getTopVisibleActivities() {
5678 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005679 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005680 }
5681 }
5682
5683 @Override
5684 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5685 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005686 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005687 }
5688 }
5689
5690 @Override
5691 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5692 Bundle bOptions) {
5693 Preconditions.checkNotNull(intents, "intents");
5694 final String[] resolvedTypes = new String[intents.length];
5695
5696 // UID of the package on user userId.
5697 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5698 // packageUid may not be initialized.
5699 int packageUid = 0;
5700 final long ident = Binder.clearCallingIdentity();
5701
5702 try {
5703 for (int i = 0; i < intents.length; i++) {
5704 resolvedTypes[i] =
5705 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5706 }
5707
5708 packageUid = AppGlobals.getPackageManager().getPackageUid(
5709 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5710 } catch (RemoteException e) {
5711 // Shouldn't happen.
5712 } finally {
5713 Binder.restoreCallingIdentity(ident);
5714 }
5715
5716 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005717 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005718 packageUid, packageName,
5719 intents, resolvedTypes, null /* resultTo */,
5720 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005721 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005722 }
5723 }
5724
5725 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005726 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5727 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5728 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5729 synchronized (mGlobalLock) {
5730 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5731 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5732 originatingPendingIntent);
5733 }
5734 }
5735
5736 @Override
5737 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5738 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5739 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5740 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5741 PendingIntentRecord originatingPendingIntent) {
5742 synchronized (mGlobalLock) {
5743 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5744 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5745 requestCode, startFlags, options, userId, inTask, reason,
5746 validateIncomingUser, originatingPendingIntent);
5747 }
5748 }
5749
5750 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005751 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5752 Intent intent, Bundle options, int userId) {
5753 return ActivityTaskManagerService.this.startActivityAsUser(
5754 caller, callerPacakge, intent,
5755 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5756 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5757 false /*validateIncomingUser*/);
5758 }
5759
5760 @Override
lumark588a3e82018-07-20 18:53:54 +08005761 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005762 synchronized (mGlobalLock) {
5763
5764 // We might change the visibilities here, so prepare an empty app transition which
5765 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005766 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005767 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005768 if (activityDisplay == null) {
5769 return;
5770 }
5771 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005772 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005773 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005774 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005775 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005776 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005777
5778 // If there was a transition set already we don't want to interfere with it as we
5779 // might be starting it too early.
5780 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005781 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
5783 }
5784 if (callback != null) {
5785 callback.run();
5786 }
5787 }
5788
5789 @Override
5790 public void notifyKeyguardTrustedChanged() {
5791 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005792 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005793 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005794 }
5795 }
5796 }
5797
5798 /**
5799 * Called after virtual display Id is updated by
5800 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5801 * {@param vrVr2dDisplayId}.
5802 */
5803 @Override
5804 public void setVr2dDisplayId(int vr2dDisplayId) {
5805 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5806 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005807 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005808 }
5809 }
5810
5811 @Override
5812 public void setFocusedActivity(IBinder token) {
5813 synchronized (mGlobalLock) {
5814 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5815 if (r == null) {
5816 throw new IllegalArgumentException(
5817 "setFocusedActivity: No activity record matching token=" + token);
5818 }
Louis Chang19443452018-10-09 12:10:21 +08005819 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005820 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005821 }
5822 }
5823 }
5824
5825 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005826 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005827 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005828 }
5829
5830 @Override
5831 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005832 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005833 }
5834
5835 @Override
5836 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005837 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005838 }
5839
5840 @Override
5841 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5842 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5843 }
5844
5845 @Override
5846 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005847 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005848 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005849
5850 @Override
5851 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5852 synchronized (mGlobalLock) {
5853 mActiveVoiceInteractionServiceComponent = component;
5854 }
5855 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005856
5857 @Override
5858 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5859 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5860 return;
5861 }
5862 synchronized (mGlobalLock) {
5863 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5864 if (types == null) {
5865 if (uid < 0) {
5866 return;
5867 }
5868 types = new ArrayMap<>();
5869 mAllowAppSwitchUids.put(userId, types);
5870 }
5871 if (uid < 0) {
5872 types.remove(type);
5873 } else {
5874 types.put(type, uid);
5875 }
5876 }
5877 }
5878
5879 @Override
5880 public void onUserStopped(int userId) {
5881 synchronized (mGlobalLock) {
5882 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5883 mAllowAppSwitchUids.remove(userId);
5884 }
5885 }
5886
5887 @Override
5888 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5889 synchronized (mGlobalLock) {
5890 return ActivityTaskManagerService.this.isGetTasksAllowed(
5891 caller, callingPid, callingUid);
5892 }
5893 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005894
5895 @Override
5896 public void onProcessAdded(WindowProcessController proc) {
5897 synchronized (mGlobalLock) {
5898 mProcessNames.put(proc.mName, proc.mUid, proc);
5899 }
5900 }
5901
5902 @Override
5903 public void onProcessRemoved(String name, int uid) {
5904 synchronized (mGlobalLock) {
5905 mProcessNames.remove(name, uid);
5906 }
5907 }
5908
5909 @Override
5910 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5911 synchronized (mGlobalLock) {
5912 if (proc == mHomeProcess) {
5913 mHomeProcess = null;
5914 }
5915 if (proc == mPreviousProcess) {
5916 mPreviousProcess = null;
5917 }
5918 }
5919 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005920
5921 @Override
5922 public int getTopProcessState() {
5923 synchronized (mGlobalLock) {
5924 return mTopProcessState;
5925 }
5926 }
5927
5928 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005929 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5930 synchronized (mGlobalLock) {
5931 return proc == mHeavyWeightProcess;
5932 }
5933 }
5934
5935 @Override
5936 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5937 synchronized (mGlobalLock) {
5938 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5939 }
5940 }
5941
5942 @Override
5943 public void finishHeavyWeightApp() {
5944 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005945 if (mHeavyWeightProcess != null) {
5946 mHeavyWeightProcess.finishActivities();
5947 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005948 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5949 mHeavyWeightProcess);
5950 }
5951 }
5952
5953 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005954 public boolean isSleeping() {
5955 synchronized (mGlobalLock) {
5956 return isSleepingLocked();
5957 }
5958 }
5959
5960 @Override
5961 public boolean isShuttingDown() {
5962 synchronized (mGlobalLock) {
5963 return mShuttingDown;
5964 }
5965 }
5966
5967 @Override
5968 public boolean shuttingDown(boolean booted, int timeout) {
5969 synchronized (mGlobalLock) {
5970 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005971 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005973 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005974 return mStackSupervisor.shutdownLocked(timeout);
5975 }
5976 }
5977
5978 @Override
5979 public void enableScreenAfterBoot(boolean booted) {
5980 synchronized (mGlobalLock) {
5981 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5982 SystemClock.uptimeMillis());
5983 mWindowManager.enableScreenAfterBoot();
5984 updateEventDispatchingLocked(booted);
5985 }
5986 }
5987
5988 @Override
5989 public boolean showStrictModeViolationDialog() {
5990 synchronized (mGlobalLock) {
5991 return mShowDialogs && !mSleeping && !mShuttingDown;
5992 }
5993 }
5994
5995 @Override
5996 public void showSystemReadyErrorDialogsIfNeeded() {
5997 synchronized (mGlobalLock) {
5998 try {
5999 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6000 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6001 + " data partition or your device will be unstable.");
6002 mUiHandler.post(() -> {
6003 if (mShowDialogs) {
6004 AlertDialog d = new BaseErrorDialog(mUiContext);
6005 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6006 d.setCancelable(false);
6007 d.setTitle(mUiContext.getText(R.string.android_system_label));
6008 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6009 d.setButton(DialogInterface.BUTTON_POSITIVE,
6010 mUiContext.getText(R.string.ok),
6011 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6012 d.show();
6013 }
6014 });
6015 }
6016 } catch (RemoteException e) {
6017 }
6018
6019 if (!Build.isBuildConsistent()) {
6020 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6021 mUiHandler.post(() -> {
6022 if (mShowDialogs) {
6023 AlertDialog d = new BaseErrorDialog(mUiContext);
6024 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6025 d.setCancelable(false);
6026 d.setTitle(mUiContext.getText(R.string.android_system_label));
6027 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6028 d.setButton(DialogInterface.BUTTON_POSITIVE,
6029 mUiContext.getText(R.string.ok),
6030 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6031 d.show();
6032 }
6033 });
6034 }
6035 }
6036 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006037
6038 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006039 public void onProcessMapped(int pid, WindowProcessController proc) {
6040 synchronized (mGlobalLock) {
6041 mPidMap.put(pid, proc);
6042 }
6043 }
6044
6045 @Override
6046 public void onProcessUnMapped(int pid) {
6047 synchronized (mGlobalLock) {
6048 mPidMap.remove(pid);
6049 }
6050 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006051
6052 @Override
6053 public void onPackageDataCleared(String name) {
6054 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006055 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006056 mAppWarnings.onPackageDataCleared(name);
6057 }
6058 }
6059
6060 @Override
6061 public void onPackageUninstalled(String name) {
6062 synchronized (mGlobalLock) {
6063 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006064 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006065 }
6066 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006067
6068 @Override
6069 public void onPackageAdded(String name, boolean replacing) {
6070 synchronized (mGlobalLock) {
6071 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6072 }
6073 }
6074
6075 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006076 public void onPackageReplaced(ApplicationInfo aInfo) {
6077 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006078 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006079 }
6080 }
6081
6082 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006083 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6084 synchronized (mGlobalLock) {
6085 return compatibilityInfoForPackageLocked(ai);
6086 }
6087 }
6088
Yunfan Chen75157d72018-07-27 14:47:21 +09006089 /**
6090 * Set the corresponding display information for the process global configuration. To be
6091 * called when we need to show IME on a different display.
6092 *
6093 * @param pid The process id associated with the IME window.
6094 * @param displayId The ID of the display showing the IME.
6095 */
6096 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006097 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006098 if (pid == MY_PID || pid < 0) {
6099 if (DEBUG_CONFIGURATION) {
6100 Slog.w(TAG,
6101 "Trying to update display configuration for system/invalid process.");
6102 }
6103 return;
6104 }
6105 mH.post(() -> {
6106 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006107 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006108 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006109 if (activityDisplay == null) {
6110 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006111 if (DEBUG_CONFIGURATION) {
6112 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006113 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006114 }
6115 return;
6116 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006117 final WindowProcessController process = mPidMap.get(pid);
6118 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006119 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006120 Slog.w(TAG, "Trying to update display configuration for invalid "
6121 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006122 }
6123 return;
6124 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006125 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006126 }
6127 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006128
Yunfan Chen75157d72018-07-27 14:47:21 +09006129 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006130
6131 @Override
6132 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6133 int requestCode, int resultCode, Intent data) {
6134 synchronized (mGlobalLock) {
6135 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006136 if (r != null && r.getActivityStack() != null) {
6137 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6138 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006139 }
6140 }
6141 }
6142
6143 @Override
6144 public void clearPendingResultForActivity(IBinder activityToken,
6145 WeakReference<PendingIntentRecord> pir) {
6146 synchronized (mGlobalLock) {
6147 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6148 if (r != null && r.pendingResults != null) {
6149 r.pendingResults.remove(pir);
6150 }
6151 }
6152 }
6153
6154 @Override
6155 public IIntentSender getIntentSender(int type, String packageName,
6156 int callingUid, int userId, IBinder token, String resultWho,
6157 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6158 Bundle bOptions) {
6159 synchronized (mGlobalLock) {
6160 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6161 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6162 }
6163 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006164
6165 @Override
6166 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6167 synchronized (mGlobalLock) {
6168 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6169 if (r == null) {
6170 return null;
6171 }
6172 if (r.mServiceConnectionsHolder == null) {
6173 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6174 ActivityTaskManagerService.this, r);
6175 }
6176
6177 return r.mServiceConnectionsHolder;
6178 }
6179 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006180
6181 @Override
6182 public Intent getHomeIntent() {
6183 synchronized (mGlobalLock) {
6184 return ActivityTaskManagerService.this.getHomeIntent();
6185 }
6186 }
6187
6188 @Override
6189 public boolean startHomeActivity(int userId, String reason) {
6190 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006191 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006192 }
6193 }
6194
6195 @Override
6196 public boolean startHomeOnAllDisplays(int userId, String reason) {
6197 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006198 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006199 }
6200 }
6201
6202 @Override
6203 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6204 synchronized (mGlobalLock) {
6205 if (mFactoryTest == FACTORY_TEST_OFF) {
6206 return false;
6207 }
6208 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6209 && wpc.mName.equals(mTopComponent.getPackageName())) {
6210 return true;
6211 }
6212 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6213 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6214 }
6215 }
6216
6217 @Override
6218 public void updateTopComponentForFactoryTest() {
6219 synchronized (mGlobalLock) {
6220 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6221 return;
6222 }
6223 final ResolveInfo ri = mContext.getPackageManager()
6224 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6225 final CharSequence errorMsg;
6226 if (ri != null) {
6227 final ActivityInfo ai = ri.activityInfo;
6228 final ApplicationInfo app = ai.applicationInfo;
6229 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6230 mTopAction = Intent.ACTION_FACTORY_TEST;
6231 mTopData = null;
6232 mTopComponent = new ComponentName(app.packageName, ai.name);
6233 errorMsg = null;
6234 } else {
6235 errorMsg = mContext.getResources().getText(
6236 com.android.internal.R.string.factorytest_not_system);
6237 }
6238 } else {
6239 errorMsg = mContext.getResources().getText(
6240 com.android.internal.R.string.factorytest_no_action);
6241 }
6242 if (errorMsg == null) {
6243 return;
6244 }
6245
6246 mTopAction = null;
6247 mTopData = null;
6248 mTopComponent = null;
6249 mUiHandler.post(() -> {
6250 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6251 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006252 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006253 });
6254 }
6255 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006256
6257 @Override
6258 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6259 Runnable finishInstrumentationCallback) {
6260 synchronized (mGlobalLock) {
6261 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006262 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006263
6264 wpc.clearRecentTasks();
6265 wpc.clearActivities();
6266
6267 if (wpc.isInstrumenting()) {
6268 finishInstrumentationCallback.run();
6269 }
6270
Jorim Jaggid0752812018-10-16 16:07:20 +02006271 if (!restarting && hasVisibleActivities) {
6272 mWindowManager.deferSurfaceLayout();
6273 try {
6274 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6275 // If there was nothing to resume, and we are not already restarting
6276 // this process, but there is a visible activity that is hosted by the
6277 // process...then make sure all visible activities are running, taking
6278 // care of restarting this process.
6279 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6280 !PRESERVE_WINDOWS);
6281 }
6282 } finally {
6283 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006284 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006285 }
6286 }
6287 }
6288
6289 @Override
6290 public void closeSystemDialogs(String reason) {
6291 enforceNotIsolatedCaller("closeSystemDialogs");
6292
6293 final int pid = Binder.getCallingPid();
6294 final int uid = Binder.getCallingUid();
6295 final long origId = Binder.clearCallingIdentity();
6296 try {
6297 synchronized (mGlobalLock) {
6298 // Only allow this from foreground processes, so that background
6299 // applications can't abuse it to prevent system UI from being shown.
6300 if (uid >= FIRST_APPLICATION_UID) {
6301 final WindowProcessController proc = mPidMap.get(pid);
6302 if (!proc.isPerceptible()) {
6303 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6304 + " from background process " + proc);
6305 return;
6306 }
6307 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006308 mWindowManager.closeSystemDialogs(reason);
6309
Wale Ogunwaled32da472018-11-16 07:19:28 -08006310 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006311 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006312 // Call into AM outside the synchronized block.
6313 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006314 } finally {
6315 Binder.restoreCallingIdentity(origId);
6316 }
6317 }
6318
6319 @Override
6320 public void cleanupDisabledPackageComponents(
6321 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6322 synchronized (mGlobalLock) {
6323 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006324 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006325 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006326 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006327 mStackSupervisor.scheduleIdleLocked();
6328 }
6329
6330 // Clean-up disabled tasks
6331 getRecentTasks().cleanupDisabledPackageTasksLocked(
6332 packageName, disabledClasses, userId);
6333 }
6334 }
6335
6336 @Override
6337 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6338 int userId) {
6339 synchronized (mGlobalLock) {
6340
6341 boolean didSomething =
6342 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006343 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006344 null, doit, evenPersistent, userId);
6345 return didSomething;
6346 }
6347 }
6348
6349 @Override
6350 public void resumeTopActivities(boolean scheduleIdle) {
6351 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006352 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006353 if (scheduleIdle) {
6354 mStackSupervisor.scheduleIdleLocked();
6355 }
6356 }
6357 }
6358
6359 @Override
6360 public void preBindApplication(WindowProcessController wpc) {
6361 synchronized (mGlobalLock) {
6362 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6363 }
6364 }
6365
6366 @Override
6367 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6368 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006369 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006370 }
6371 }
6372
6373 @Override
6374 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6375 try {
6376 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6377 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6378 }
6379 } catch (RemoteException ex) {
6380 throw new SecurityException("Fail to check is caller a privileged app", ex);
6381 }
6382
6383 synchronized (mGlobalLock) {
6384 final long ident = Binder.clearCallingIdentity();
6385 try {
6386 if (mAmInternal.shouldConfirmCredentials(userId)) {
6387 if (mKeyguardController.isKeyguardLocked()) {
6388 // Showing launcher to avoid user entering credential twice.
6389 startHomeActivity(currentUserId, "notifyLockedProfile");
6390 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006391 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006392 }
6393 } finally {
6394 Binder.restoreCallingIdentity(ident);
6395 }
6396 }
6397 }
6398
6399 @Override
6400 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6401 mAmInternal.enforceCallingPermission(
6402 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6403
6404 synchronized (mGlobalLock) {
6405 final long ident = Binder.clearCallingIdentity();
6406 try {
6407 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6408 FLAG_ACTIVITY_TASK_ON_HOME);
6409 ActivityOptions activityOptions = options != null
6410 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006411 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006412 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006413 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006414 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006415 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006416 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6417 UserHandle.CURRENT);
6418 } finally {
6419 Binder.restoreCallingIdentity(ident);
6420 }
6421 }
6422 }
6423
6424 @Override
6425 public void writeActivitiesToProto(ProtoOutputStream proto) {
6426 synchronized (mGlobalLock) {
6427 // The output proto of "activity --proto activities"
6428 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006429 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006430 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6431 }
6432 }
6433
6434 @Override
6435 public void saveANRState(String reason) {
6436 synchronized (mGlobalLock) {
6437 final StringWriter sw = new StringWriter();
6438 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6439 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6440 if (reason != null) {
6441 pw.println(" Reason: " + reason);
6442 }
6443 pw.println();
6444 getActivityStartController().dump(pw, " ", null);
6445 pw.println();
6446 pw.println("-------------------------------------------------------------------------------");
6447 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6448 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6449 "" /* header */);
6450 pw.println();
6451 pw.close();
6452
6453 mLastANRState = sw.toString();
6454 }
6455 }
6456
6457 @Override
6458 public void clearSavedANRState() {
6459 synchronized (mGlobalLock) {
6460 mLastANRState = null;
6461 }
6462 }
6463
6464 @Override
6465 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6466 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6467 synchronized (mGlobalLock) {
6468 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6469 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6470 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6471 dumpLastANRLocked(pw);
6472 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6473 dumpLastANRTracesLocked(pw);
6474 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6475 dumpActivityStarterLocked(pw, dumpPackage);
6476 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6477 dumpActivityContainersLocked(pw);
6478 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6479 if (getRecentTasks() != null) {
6480 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6481 }
6482 }
6483 }
6484 }
6485
6486 @Override
6487 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6488 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6489 int wakefulness) {
6490 synchronized (mGlobalLock) {
6491 if (mHomeProcess != null && (dumpPackage == null
6492 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6493 if (needSep) {
6494 pw.println();
6495 needSep = false;
6496 }
6497 pw.println(" mHomeProcess: " + mHomeProcess);
6498 }
6499 if (mPreviousProcess != null && (dumpPackage == null
6500 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6501 if (needSep) {
6502 pw.println();
6503 needSep = false;
6504 }
6505 pw.println(" mPreviousProcess: " + mPreviousProcess);
6506 }
6507 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6508 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6509 StringBuilder sb = new StringBuilder(128);
6510 sb.append(" mPreviousProcessVisibleTime: ");
6511 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6512 pw.println(sb);
6513 }
6514 if (mHeavyWeightProcess != null && (dumpPackage == null
6515 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6516 if (needSep) {
6517 pw.println();
6518 needSep = false;
6519 }
6520 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6521 }
6522 if (dumpPackage == null) {
6523 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006524 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006525 }
6526 if (dumpAll) {
6527 if (dumpPackage == null) {
6528 pw.println(" mConfigWillChange: "
6529 + getTopDisplayFocusedStack().mConfigWillChange);
6530 }
6531 if (mCompatModePackages.getPackages().size() > 0) {
6532 boolean printed = false;
6533 for (Map.Entry<String, Integer> entry
6534 : mCompatModePackages.getPackages().entrySet()) {
6535 String pkg = entry.getKey();
6536 int mode = entry.getValue();
6537 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6538 continue;
6539 }
6540 if (!printed) {
6541 pw.println(" mScreenCompatPackages:");
6542 printed = true;
6543 }
6544 pw.println(" " + pkg + ": " + mode);
6545 }
6546 }
6547 }
6548
6549 if (dumpPackage == null) {
6550 pw.println(" mWakefulness="
6551 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006552 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006553 if (mRunningVoice != null) {
6554 pw.println(" mRunningVoice=" + mRunningVoice);
6555 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6556 }
6557 pw.println(" mSleeping=" + mSleeping);
6558 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6559 pw.println(" mVrController=" + mVrController);
6560 }
6561 if (mCurAppTimeTracker != null) {
6562 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6563 }
6564 if (mAllowAppSwitchUids.size() > 0) {
6565 boolean printed = false;
6566 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6567 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6568 for (int j = 0; j < types.size(); j++) {
6569 if (dumpPackage == null ||
6570 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6571 if (needSep) {
6572 pw.println();
6573 needSep = false;
6574 }
6575 if (!printed) {
6576 pw.println(" mAllowAppSwitchUids:");
6577 printed = true;
6578 }
6579 pw.print(" User ");
6580 pw.print(mAllowAppSwitchUids.keyAt(i));
6581 pw.print(": Type ");
6582 pw.print(types.keyAt(j));
6583 pw.print(" = ");
6584 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6585 pw.println();
6586 }
6587 }
6588 }
6589 }
6590 if (dumpPackage == null) {
6591 if (mController != null) {
6592 pw.println(" mController=" + mController
6593 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6594 }
6595 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6596 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6597 }
6598
6599 return needSep;
6600 }
6601 }
6602
6603 @Override
6604 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6605 synchronized (mGlobalLock) {
6606 if (dumpPackage == null) {
6607 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6608 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6609 writeSleepStateToProto(proto);
6610 if (mController != null) {
6611 final long token = proto.start(CONTROLLER);
6612 proto.write(CONTROLLER, mController.toString());
6613 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6614 proto.end(token);
6615 }
6616 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6617 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6618 }
6619
6620 if (mHomeProcess != null && (dumpPackage == null
6621 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006622 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006623 }
6624
6625 if (mPreviousProcess != null && (dumpPackage == null
6626 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006627 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006628 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6629 }
6630
6631 if (mHeavyWeightProcess != null && (dumpPackage == null
6632 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006633 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006634 }
6635
6636 for (Map.Entry<String, Integer> entry
6637 : mCompatModePackages.getPackages().entrySet()) {
6638 String pkg = entry.getKey();
6639 int mode = entry.getValue();
6640 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6641 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6642 proto.write(PACKAGE, pkg);
6643 proto.write(MODE, mode);
6644 proto.end(compatToken);
6645 }
6646 }
6647
6648 if (mCurAppTimeTracker != null) {
6649 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6650 }
6651
6652 }
6653 }
6654
6655 @Override
6656 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6657 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6658 boolean dumpFocusedStackOnly) {
6659 synchronized (mGlobalLock) {
6660 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6661 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6662 }
6663 }
6664
6665 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006666 public void dumpForOom(PrintWriter pw) {
6667 synchronized (mGlobalLock) {
6668 pw.println(" mHomeProcess: " + mHomeProcess);
6669 pw.println(" mPreviousProcess: " + mPreviousProcess);
6670 if (mHeavyWeightProcess != null) {
6671 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6672 }
6673 }
6674 }
6675
6676 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006677 public boolean canGcNow() {
6678 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006679 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006680 }
6681 }
6682
6683 @Override
6684 public WindowProcessController getTopApp() {
6685 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006686 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006687 return top != null ? top.app : null;
6688 }
6689 }
6690
6691 @Override
6692 public void rankTaskLayersIfNeeded() {
6693 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006694 if (mRootActivityContainer != null) {
6695 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006696 }
6697 }
6698 }
6699
6700 @Override
6701 public void scheduleDestroyAllActivities(String reason) {
6702 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006703 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006704 }
6705 }
6706
6707 @Override
6708 public void removeUser(int userId) {
6709 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006710 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006711 }
6712 }
6713
6714 @Override
6715 public boolean switchUser(int userId, UserState userState) {
6716 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006717 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 }
6719 }
6720
6721 @Override
6722 public void onHandleAppCrash(WindowProcessController wpc) {
6723 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006724 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006725 }
6726 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006727
6728 @Override
6729 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6730 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006731 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006732 }
6733 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006734
6735 @Override
6736 public void onUidActive(int uid, int procState) {
6737 synchronized (mGlobalLock) {
6738 mActiveUids.put(uid, procState);
6739 }
6740 }
6741
6742 @Override
6743 public void onUidInactive(int uid) {
6744 synchronized (mGlobalLock) {
6745 mActiveUids.remove(uid);
6746 }
6747 }
6748
6749 @Override
6750 public void onActiveUidsCleared() {
6751 synchronized (mGlobalLock) {
6752 mActiveUids.clear();
6753 }
6754 }
6755
6756 @Override
6757 public void onUidProcStateChanged(int uid, int procState) {
6758 synchronized (mGlobalLock) {
6759 if (mActiveUids.get(uid) != null) {
6760 mActiveUids.put(uid, procState);
6761 }
6762 }
6763 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006764
6765 @Override
6766 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6767 synchronized (mGlobalLock) {
6768 mPendingTempWhitelist.put(uid, tag);
6769 }
6770 }
6771
6772 @Override
6773 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6774 synchronized (mGlobalLock) {
6775 mPendingTempWhitelist.remove(uid);
6776 }
6777 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006778
6779 @Override
6780 public boolean handleAppCrashInActivityController(String processName, int pid,
6781 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6782 Runnable killCrashingAppCallback) {
6783 synchronized (mGlobalLock) {
6784 if (mController == null) {
6785 return false;
6786 }
6787
6788 try {
6789 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6790 stackTrace)) {
6791 killCrashingAppCallback.run();
6792 return true;
6793 }
6794 } catch (RemoteException e) {
6795 mController = null;
6796 Watchdog.getInstance().setActivityController(null);
6797 }
6798 return false;
6799 }
6800 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006801
6802 @Override
6803 public void removeRecentTasksByPackageName(String packageName, int userId) {
6804 synchronized (mGlobalLock) {
6805 mRecentTasks.removeTasksByPackageName(packageName, userId);
6806 }
6807 }
6808
6809 @Override
6810 public void cleanupRecentTasksForUser(int userId) {
6811 synchronized (mGlobalLock) {
6812 mRecentTasks.cleanupLocked(userId);
6813 }
6814 }
6815
6816 @Override
6817 public void loadRecentTasksForUser(int userId) {
6818 synchronized (mGlobalLock) {
6819 mRecentTasks.loadUserRecentsLocked(userId);
6820 }
6821 }
6822
6823 @Override
6824 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6825 synchronized (mGlobalLock) {
6826 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6827 }
6828 }
6829
6830 @Override
6831 public void flushRecentTasks() {
6832 mRecentTasks.flush();
6833 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006834
6835 @Override
6836 public WindowProcessController getHomeProcess() {
6837 synchronized (mGlobalLock) {
6838 return mHomeProcess;
6839 }
6840 }
6841
6842 @Override
6843 public WindowProcessController getPreviousProcess() {
6844 synchronized (mGlobalLock) {
6845 return mPreviousProcess;
6846 }
6847 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006848
6849 @Override
6850 public void clearLockedTasks(String reason) {
6851 synchronized (mGlobalLock) {
6852 getLockTaskController().clearLockedTasks(reason);
6853 }
6854 }
6855
6856 @Override
6857 public void updateUserConfiguration() {
6858 synchronized (mGlobalLock) {
6859 final Configuration configuration = new Configuration(getGlobalConfiguration());
6860 final int currentUserId = mAmInternal.getCurrentUserId();
6861 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6862 configuration, currentUserId, Settings.System.canWrite(mContext));
6863 updateConfigurationLocked(configuration, null /* starting */,
6864 false /* initLocale */, false /* persistent */, currentUserId,
6865 false /* deferResume */);
6866 }
6867 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006868
6869 @Override
6870 public boolean canShowErrorDialogs() {
6871 synchronized (mGlobalLock) {
6872 return mShowDialogs && !mSleeping && !mShuttingDown
6873 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6874 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6875 mAmInternal.getCurrentUserId())
6876 && !(UserManager.isDeviceInDemoMode(mContext)
6877 && mAmInternal.getCurrentUser().isDemo());
6878 }
6879 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006880
6881 @Override
6882 public void setProfileApp(String profileApp) {
6883 synchronized (mGlobalLock) {
6884 mProfileApp = profileApp;
6885 }
6886 }
6887
6888 @Override
6889 public void setProfileProc(WindowProcessController wpc) {
6890 synchronized (mGlobalLock) {
6891 mProfileProc = wpc;
6892 }
6893 }
6894
6895 @Override
6896 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6897 synchronized (mGlobalLock) {
6898 mProfilerInfo = profilerInfo;
6899 }
6900 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08006901
6902 @Override
6903 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
6904 synchronized (mGlobalLock) {
6905 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
6906 }
6907 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006908 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08006909}