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