blob: 6832f0d39a40ad23fdec9cec0317a0fb6d3fa47c [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
Charles Chen8d98dd22018-12-26 17:36:54 +0800642 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
643 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700644 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700645 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700646 mSystemThread = ActivityThread.currentActivityThread();
647 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700648 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800649 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700650 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700651 }
652
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700653 public void onSystemReady() {
654 synchronized (mGlobalLock) {
655 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
656 PackageManager.FEATURE_CANT_SAVE_STATE);
657 mAssistUtils = new AssistUtils(mContext);
658 mVrController.onSystemReady();
659 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700660 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700662 }
663
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700664 public void onInitPowerManagement() {
665 synchronized (mGlobalLock) {
666 mStackSupervisor.initPowerManagement();
667 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
668 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
669 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
670 mVoiceWakeLock.setReferenceCounted(false);
671 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700672 }
673
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700674 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700675 mFontScaleSettingObserver = new FontScaleSettingObserver();
676 }
677
Wale Ogunwale59507092018-10-29 09:00:30 -0700678 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700679 final boolean freeformWindowManagement =
680 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
681 || Settings.Global.getInt(
682 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
683
684 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
685 final boolean supportsPictureInPicture = supportsMultiWindow &&
686 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
687 final boolean supportsSplitScreenMultiWindow =
688 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
689 final boolean supportsMultiDisplay = mContext.getPackageManager()
690 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700691 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
692 final boolean forceResizable = Settings.Global.getInt(
693 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700694 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700695
696 // Transfer any global setting for forcing RTL layout, into a System Property
697 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
698
699 final Configuration configuration = new Configuration();
700 Settings.System.getConfiguration(resolver, configuration);
701 if (forceRtl) {
702 // This will take care of setting the correct layout direction flags
703 configuration.setLayoutDirection(configuration.locale);
704 }
705
706 synchronized (mGlobalLock) {
707 mForceResizableActivities = forceResizable;
708 final boolean multiWindowFormEnabled = freeformWindowManagement
709 || supportsSplitScreenMultiWindow
710 || supportsPictureInPicture
711 || supportsMultiDisplay;
712 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
713 mSupportsMultiWindow = true;
714 mSupportsFreeformWindowManagement = freeformWindowManagement;
715 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
716 mSupportsPictureInPicture = supportsPictureInPicture;
717 mSupportsMultiDisplay = supportsMultiDisplay;
718 } else {
719 mSupportsMultiWindow = false;
720 mSupportsFreeformWindowManagement = false;
721 mSupportsSplitScreenMultiWindow = false;
722 mSupportsPictureInPicture = false;
723 mSupportsMultiDisplay = false;
724 }
725 mWindowManager.setForceResizableTasks(mForceResizableActivities);
726 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700727 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
728 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729 // This happens before any activities are started, so we can change global configuration
730 // in-place.
731 updateConfigurationLocked(configuration, null, true);
732 final Configuration globalConfig = getGlobalConfiguration();
733 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
734
735 // Load resources only after the current configuration has been set.
736 final Resources res = mContext.getResources();
737 mThumbnailWidth = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_width);
739 mThumbnailHeight = res.getDimensionPixelSize(
740 com.android.internal.R.dimen.thumbnail_height);
741
742 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
743 mFullscreenThumbnailScale = (float) res
744 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
745 (float) globalConfig.screenWidthDp;
746 } else {
747 mFullscreenThumbnailScale = res.getFraction(
748 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
749 }
750 }
751 }
752
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800753 public WindowManagerGlobalLock getGlobalLock() {
754 return mGlobalLock;
755 }
756
Riddle Hsud93a6c42018-11-29 21:50:06 +0800757 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
758 Looper looper) {
759 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700760 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700761 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700762 final File systemDir = SystemServiceManager.ensureSystemDir();
763 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
764 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700765 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700766
767 mTempConfig.setToDefaults();
768 mTempConfig.setLocales(LocaleList.getDefault());
769 mConfigurationSeq = mTempConfig.seq = 1;
770 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800771 mRootActivityContainer = new RootActivityContainer(this);
772 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700773
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700774 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700776 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700777 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700778 mRecentTasks = createRecentTasks();
779 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700781 mKeyguardController = mStackSupervisor.getKeyguardController();
782 }
783
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700784 public void onActivityManagerInternalAdded() {
785 synchronized (mGlobalLock) {
786 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
787 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
788 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700789 }
790
Yunfan Chen75157d72018-07-27 14:47:21 +0900791 int increaseConfigurationSeqLocked() {
792 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
793 return mConfigurationSeq;
794 }
795
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700796 protected ActivityStackSupervisor createStackSupervisor() {
797 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
798 supervisor.initialize();
799 return supervisor;
800 }
801
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700802 public void setWindowManager(WindowManagerService wm) {
803 synchronized (mGlobalLock) {
804 mWindowManager = wm;
805 mLockTaskController.setWindowManager(wm);
806 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800807 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700808 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700809 }
810
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700811 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
812 synchronized (mGlobalLock) {
813 mUsageStatsInternal = usageStatsManager;
814 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700815 }
816
Wale Ogunwalef6733932018-06-27 05:14:34 -0700817 UserManagerService getUserManager() {
818 if (mUserManager == null) {
819 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
820 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
821 }
822 return mUserManager;
823 }
824
825 AppOpsService getAppOpsService() {
826 if (mAppOpsService == null) {
827 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
828 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
829 }
830 return mAppOpsService;
831 }
832
833 boolean hasUserRestriction(String restriction, int userId) {
834 return getUserManager().hasUserRestriction(restriction, userId);
835 }
836
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700837 protected RecentTasks createRecentTasks() {
838 return new RecentTasks(this, mStackSupervisor);
839 }
840
841 RecentTasks getRecentTasks() {
842 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700843 }
844
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700845 ClientLifecycleManager getLifecycleManager() {
846 return mLifecycleManager;
847 }
848
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700849 ActivityStartController getActivityStartController() {
850 return mActivityStartController;
851 }
852
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700853 TaskChangeNotificationController getTaskChangeNotificationController() {
854 return mTaskChangeNotificationController;
855 }
856
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700857 LockTaskController getLockTaskController() {
858 return mLockTaskController;
859 }
860
Yunfan Chen75157d72018-07-27 14:47:21 +0900861 /**
862 * Return the global configuration used by the process corresponding to the input pid. This is
863 * usually the global configuration with some overrides specific to that process.
864 */
865 Configuration getGlobalConfigurationForCallingPid() {
866 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800867 return getGlobalConfigurationForPid(pid);
868 }
869
870 /**
871 * Return the global configuration used by the process corresponding to the given pid.
872 */
873 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900874 if (pid == MY_PID || pid < 0) {
875 return getGlobalConfiguration();
876 }
877 synchronized (mGlobalLock) {
878 final WindowProcessController app = mPidMap.get(pid);
879 return app != null ? app.getConfiguration() : getGlobalConfiguration();
880 }
881 }
882
883 /**
884 * Return the device configuration info used by the process corresponding to the input pid.
885 * The value is consistent with the global configuration for the process.
886 */
887 @Override
888 public ConfigurationInfo getDeviceConfigurationInfo() {
889 ConfigurationInfo config = new ConfigurationInfo();
890 synchronized (mGlobalLock) {
891 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
892 config.reqTouchScreen = globalConfig.touchscreen;
893 config.reqKeyboardType = globalConfig.keyboard;
894 config.reqNavigation = globalConfig.navigation;
895 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
896 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
897 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
898 }
899 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
900 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
901 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
902 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700903 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900904 }
905 return config;
906 }
907
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700908 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700909 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700910 }
911
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700912 public static final class Lifecycle extends SystemService {
913 private final ActivityTaskManagerService mService;
914
915 public Lifecycle(Context context) {
916 super(context);
917 mService = new ActivityTaskManagerService(context);
918 }
919
920 @Override
921 public void onStart() {
922 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700923 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700924 }
925
Garfield Tan891146c2018-10-09 12:14:00 -0700926 @Override
927 public void onUnlockUser(int userId) {
928 synchronized (mService.getGlobalLock()) {
929 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
930 }
931 }
932
933 @Override
934 public void onCleanupUser(int userId) {
935 synchronized (mService.getGlobalLock()) {
936 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
937 }
938 }
939
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700940 public ActivityTaskManagerService getService() {
941 return mService;
942 }
943 }
944
945 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700946 public final int startActivity(IApplicationThread caller, String callingPackage,
947 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
948 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
949 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
950 resultWho, requestCode, startFlags, profilerInfo, bOptions,
951 UserHandle.getCallingUserId());
952 }
953
954 @Override
955 public final int startActivities(IApplicationThread caller, String callingPackage,
956 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
957 int userId) {
958 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700959 enforceNotIsolatedCaller(reason);
960 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700961 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700962 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100963 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
964 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700965 }
966
967 @Override
968 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
969 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
970 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
971 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
972 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
973 true /*validateIncomingUser*/);
974 }
975
976 int startActivityAsUser(IApplicationThread caller, String callingPackage,
977 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
978 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
979 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700980 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700981
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700982 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700983 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
984
985 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700986 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700987 .setCaller(caller)
988 .setCallingPackage(callingPackage)
989 .setResolvedType(resolvedType)
990 .setResultTo(resultTo)
991 .setResultWho(resultWho)
992 .setRequestCode(requestCode)
993 .setStartFlags(startFlags)
994 .setProfilerInfo(profilerInfo)
995 .setActivityOptions(bOptions)
996 .setMayWait(userId)
997 .execute();
998
999 }
1000
1001 @Override
1002 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1003 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001004 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1005 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 // Refuse possible leaked file descriptors
1007 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1008 throw new IllegalArgumentException("File descriptors passed in Intent");
1009 }
1010
1011 if (!(target instanceof PendingIntentRecord)) {
1012 throw new IllegalArgumentException("Bad PendingIntent object");
1013 }
1014
1015 PendingIntentRecord pir = (PendingIntentRecord)target;
1016
1017 synchronized (mGlobalLock) {
1018 // If this is coming from the currently resumed activity, it is
1019 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001020 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 if (stack.mResumedActivity != null &&
1022 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001023 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 }
1025 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001026 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 }
1029
1030 @Override
1031 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1032 Bundle bOptions) {
1033 // Refuse possible leaked file descriptors
1034 if (intent != null && intent.hasFileDescriptors()) {
1035 throw new IllegalArgumentException("File descriptors passed in Intent");
1036 }
1037 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1038
1039 synchronized (mGlobalLock) {
1040 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1041 if (r == null) {
1042 SafeActivityOptions.abort(options);
1043 return false;
1044 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001045 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 // The caller is not running... d'oh!
1047 SafeActivityOptions.abort(options);
1048 return false;
1049 }
1050 intent = new Intent(intent);
1051 // The caller is not allowed to change the data.
1052 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1053 // And we are resetting to find the next component...
1054 intent.setComponent(null);
1055
1056 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1057
1058 ActivityInfo aInfo = null;
1059 try {
1060 List<ResolveInfo> resolves =
1061 AppGlobals.getPackageManager().queryIntentActivities(
1062 intent, r.resolvedType,
1063 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1064 UserHandle.getCallingUserId()).getList();
1065
1066 // Look for the original activity in the list...
1067 final int N = resolves != null ? resolves.size() : 0;
1068 for (int i=0; i<N; i++) {
1069 ResolveInfo rInfo = resolves.get(i);
1070 if (rInfo.activityInfo.packageName.equals(r.packageName)
1071 && rInfo.activityInfo.name.equals(r.info.name)) {
1072 // We found the current one... the next matching is
1073 // after it.
1074 i++;
1075 if (i<N) {
1076 aInfo = resolves.get(i).activityInfo;
1077 }
1078 if (debug) {
1079 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1080 + "/" + r.info.name);
1081 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1082 ? "null" : aInfo.packageName + "/" + aInfo.name));
1083 }
1084 break;
1085 }
1086 }
1087 } catch (RemoteException e) {
1088 }
1089
1090 if (aInfo == null) {
1091 // Nobody who is next!
1092 SafeActivityOptions.abort(options);
1093 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1094 return false;
1095 }
1096
1097 intent.setComponent(new ComponentName(
1098 aInfo.applicationInfo.packageName, aInfo.name));
1099 intent.setFlags(intent.getFlags()&~(
1100 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1101 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1102 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1103 FLAG_ACTIVITY_NEW_TASK));
1104
1105 // Okay now we need to start the new activity, replacing the currently running activity.
1106 // This is a little tricky because we want to start the new one as if the current one is
1107 // finished, but not finish the current one first so that there is no flicker.
1108 // And thus...
1109 final boolean wasFinishing = r.finishing;
1110 r.finishing = true;
1111
1112 // Propagate reply information over to the new activity.
1113 final ActivityRecord resultTo = r.resultTo;
1114 final String resultWho = r.resultWho;
1115 final int requestCode = r.requestCode;
1116 r.resultTo = null;
1117 if (resultTo != null) {
1118 resultTo.removeResultsLocked(r, resultWho, requestCode);
1119 }
1120
1121 final long origId = Binder.clearCallingIdentity();
1122 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001123 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001125 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001126 .setResolvedType(r.resolvedType)
1127 .setActivityInfo(aInfo)
1128 .setResultTo(resultTo != null ? resultTo.appToken : null)
1129 .setResultWho(resultWho)
1130 .setRequestCode(requestCode)
1131 .setCallingPid(-1)
1132 .setCallingUid(r.launchedFromUid)
1133 .setCallingPackage(r.launchedFromPackage)
1134 .setRealCallingPid(-1)
1135 .setRealCallingUid(r.launchedFromUid)
1136 .setActivityOptions(options)
1137 .execute();
1138 Binder.restoreCallingIdentity(origId);
1139
1140 r.finishing = wasFinishing;
1141 if (res != ActivityManager.START_SUCCESS) {
1142 return false;
1143 }
1144 return true;
1145 }
1146 }
1147
1148 @Override
1149 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1150 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1151 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1152 final WaitResult res = new WaitResult();
1153 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001154 enforceNotIsolatedCaller("startActivityAndWait");
1155 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1156 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001157 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001158 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001159 .setCaller(caller)
1160 .setCallingPackage(callingPackage)
1161 .setResolvedType(resolvedType)
1162 .setResultTo(resultTo)
1163 .setResultWho(resultWho)
1164 .setRequestCode(requestCode)
1165 .setStartFlags(startFlags)
1166 .setActivityOptions(bOptions)
1167 .setMayWait(userId)
1168 .setProfilerInfo(profilerInfo)
1169 .setWaitResult(res)
1170 .execute();
1171 }
1172 return res;
1173 }
1174
1175 @Override
1176 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1177 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1178 int startFlags, Configuration config, Bundle bOptions, int userId) {
1179 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001180 enforceNotIsolatedCaller("startActivityWithConfig");
1181 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1182 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001183 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001184 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001185 .setCaller(caller)
1186 .setCallingPackage(callingPackage)
1187 .setResolvedType(resolvedType)
1188 .setResultTo(resultTo)
1189 .setResultWho(resultWho)
1190 .setRequestCode(requestCode)
1191 .setStartFlags(startFlags)
1192 .setGlobalConfiguration(config)
1193 .setActivityOptions(bOptions)
1194 .setMayWait(userId)
1195 .execute();
1196 }
1197 }
1198
Alison Cichowlas3e340502018-08-07 17:15:01 -04001199
1200 @Override
1201 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1202 int callingUid = Binder.getCallingUid();
1203 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1204 throw new SecurityException("Only the system process can request a permission token, "
1205 + "received request from uid: " + callingUid);
1206 }
1207 IBinder permissionToken = new Binder();
1208 synchronized (mGlobalLock) {
1209 mStartActivitySources.put(permissionToken, delegatorToken);
1210 }
1211
1212 Message expireMsg = PooledLambda.obtainMessage(
1213 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1214 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1215
1216 Message forgetMsg = PooledLambda.obtainMessage(
1217 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1218 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1219
1220 return permissionToken;
1221 }
1222
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001223 @Override
1224 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1225 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001226 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1227 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001229 // permission grants) as any app that may launch one of your own activities. So we only
1230 // allow this in two cases:
1231 // 1) The caller is an activity that is part of the core framework, and then only when it
1232 // is running as the system.
1233 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1234 // can only be requested by a system activity, which may then delegate this call to
1235 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 final ActivityRecord sourceRecord;
1237 final int targetUid;
1238 final String targetPackage;
1239 final boolean isResolver;
1240 synchronized (mGlobalLock) {
1241 if (resultTo == null) {
1242 throw new SecurityException("Must be called from an activity");
1243 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001244 final IBinder sourceToken;
1245 if (permissionToken != null) {
1246 // To even attempt to use a permissionToken, an app must also have this signature
1247 // permission.
1248 mAmInternal.enforceCallingPermission(
1249 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1250 "startActivityAsCaller");
1251 // If called with a permissionToken, we want the sourceRecord from the delegator
1252 // activity that requested this token.
1253 sourceToken = mStartActivitySources.remove(permissionToken);
1254 if (sourceToken == null) {
1255 // Invalid permissionToken, check if it recently expired.
1256 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1257 throw new SecurityException("Called with expired permission token: "
1258 + permissionToken);
1259 } else {
1260 throw new SecurityException("Called with invalid permission token: "
1261 + permissionToken);
1262 }
1263 }
1264 } else {
1265 // This method was called directly by the source.
1266 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001267 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268
Wale Ogunwaled32da472018-11-16 07:19:28 -08001269 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001270 if (sourceRecord == null) {
1271 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001272 }
1273 if (sourceRecord.app == null) {
1274 throw new SecurityException("Called without a process attached to activity");
1275 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001276
1277 // Whether called directly or from a delegate, the source activity must be from the
1278 // android package.
1279 if (!sourceRecord.info.packageName.equals("android")) {
1280 throw new SecurityException("Must be called from an activity that is "
1281 + "declared in the android package");
1282 }
1283
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001284 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 // This is still okay, as long as this activity is running under the
1286 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001287 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001289 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 + " must be system uid or original calling uid "
1291 + sourceRecord.launchedFromUid);
1292 }
1293 }
1294 if (ignoreTargetSecurity) {
1295 if (intent.getComponent() == null) {
1296 throw new SecurityException(
1297 "Component must be specified with ignoreTargetSecurity");
1298 }
1299 if (intent.getSelector() != null) {
1300 throw new SecurityException(
1301 "Selector not allowed with ignoreTargetSecurity");
1302 }
1303 }
1304 targetUid = sourceRecord.launchedFromUid;
1305 targetPackage = sourceRecord.launchedFromPackage;
1306 isResolver = sourceRecord.isResolverOrChildActivity();
1307 }
1308
1309 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001310 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 }
1312
1313 // TODO: Switch to user app stacks here.
1314 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001315 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001316 .setCallingUid(targetUid)
1317 .setCallingPackage(targetPackage)
1318 .setResolvedType(resolvedType)
1319 .setResultTo(resultTo)
1320 .setResultWho(resultWho)
1321 .setRequestCode(requestCode)
1322 .setStartFlags(startFlags)
1323 .setActivityOptions(bOptions)
1324 .setMayWait(userId)
1325 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1326 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1327 .execute();
1328 } catch (SecurityException e) {
1329 // XXX need to figure out how to propagate to original app.
1330 // A SecurityException here is generally actually a fault of the original
1331 // calling activity (such as a fairly granting permissions), so propagate it
1332 // back to them.
1333 /*
1334 StringBuilder msg = new StringBuilder();
1335 msg.append("While launching");
1336 msg.append(intent.toString());
1337 msg.append(": ");
1338 msg.append(e.getMessage());
1339 */
1340 throw e;
1341 }
1342 }
1343
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001344 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1345 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1346 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1347 }
1348
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 @Override
1350 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1351 Intent intent, String resolvedType, IVoiceInteractionSession session,
1352 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1353 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001354 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001355 if (session == null || interactor == null) {
1356 throw new NullPointerException("null session or interactor");
1357 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001358 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001360 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 .setCallingUid(callingUid)
1362 .setCallingPackage(callingPackage)
1363 .setResolvedType(resolvedType)
1364 .setVoiceSession(session)
1365 .setVoiceInteractor(interactor)
1366 .setStartFlags(startFlags)
1367 .setProfilerInfo(profilerInfo)
1368 .setActivityOptions(bOptions)
1369 .setMayWait(userId)
1370 .execute();
1371 }
1372
1373 @Override
1374 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1375 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001376 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1377 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001379 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 .setCallingUid(callingUid)
1381 .setCallingPackage(callingPackage)
1382 .setResolvedType(resolvedType)
1383 .setActivityOptions(bOptions)
1384 .setMayWait(userId)
1385 .execute();
1386 }
1387
1388 @Override
1389 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1390 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001391 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001392 final int callingPid = Binder.getCallingPid();
1393 final long origId = Binder.clearCallingIdentity();
1394 try {
1395 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001396 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1397 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398
1399 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1401 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1403 recentsUid, assistDataReceiver);
1404 }
1405 } finally {
1406 Binder.restoreCallingIdentity(origId);
1407 }
1408 }
1409
1410 @Override
1411 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001412 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 "startActivityFromRecents()");
1414
1415 final int callingPid = Binder.getCallingPid();
1416 final int callingUid = Binder.getCallingUid();
1417 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1418 final long origId = Binder.clearCallingIdentity();
1419 try {
1420 synchronized (mGlobalLock) {
1421 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1422 safeOptions);
1423 }
1424 } finally {
1425 Binder.restoreCallingIdentity(origId);
1426 }
1427 }
1428
1429 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001430 * Public API to check if the client is allowed to start an activity on specified display.
1431 *
1432 * If the target display is private or virtual, some restrictions will apply.
1433 *
1434 * @param displayId Target display id.
1435 * @param intent Intent used to launch the activity.
1436 * @param resolvedType The MIME type of the intent.
1437 * @param userId The id of the user for whom the call is made.
1438 * @return {@code true} if a call to start an activity on the target display should succeed and
1439 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1440 */
1441 @Override
1442 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1443 String resolvedType, int userId) {
1444 final int callingUid = Binder.getCallingUid();
1445 final int callingPid = Binder.getCallingPid();
1446 final long origId = Binder.clearCallingIdentity();
1447
1448 try {
1449 // Collect information about the target of the Intent.
1450 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1451 0 /* startFlags */, null /* profilerInfo */, userId,
1452 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1453 UserHandle.USER_NULL));
1454 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1455
1456 synchronized (mGlobalLock) {
1457 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1458 aInfo);
1459 }
1460 } finally {
1461 Binder.restoreCallingIdentity(origId);
1462 }
1463 }
1464
1465 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 * This is the internal entry point for handling Activity.finish().
1467 *
1468 * @param token The Binder token referencing the Activity we want to finish.
1469 * @param resultCode Result code, if any, from this Activity.
1470 * @param resultData Result data (Intent), if any, from this Activity.
1471 * @param finishTask Whether to finish the task associated with this Activity.
1472 *
1473 * @return Returns true if the activity successfully finished, or false if it is still running.
1474 */
1475 @Override
1476 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1477 int finishTask) {
1478 // Refuse possible leaked file descriptors
1479 if (resultData != null && resultData.hasFileDescriptors()) {
1480 throw new IllegalArgumentException("File descriptors passed in Intent");
1481 }
1482
1483 synchronized (mGlobalLock) {
1484 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1485 if (r == null) {
1486 return true;
1487 }
1488 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001489 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001490 ActivityRecord rootR = tr.getRootActivity();
1491 if (rootR == null) {
1492 Slog.w(TAG, "Finishing task with all activities already finished");
1493 }
1494 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1495 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001496 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001497 return false;
1498 }
1499
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001500 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1501 // We should consolidate.
1502 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001504 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 if (next != null) {
1506 // ask watcher if this is allowed
1507 boolean resumeOK = true;
1508 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001509 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001511 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001512 Watchdog.getInstance().setActivityController(null);
1513 }
1514
1515 if (!resumeOK) {
1516 Slog.i(TAG, "Not finishing activity because controller resumed");
1517 return false;
1518 }
1519 }
1520 }
1521 final long origId = Binder.clearCallingIdentity();
1522 try {
1523 boolean res;
1524 final boolean finishWithRootActivity =
1525 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1526 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1527 || (finishWithRootActivity && r == rootR)) {
1528 // If requested, remove the task that is associated to this activity only if it
1529 // was the root activity in the task. The result code and data is ignored
1530 // because we don't support returning them across task boundaries. Also, to
1531 // keep backwards compatibility we remove the task from recents when finishing
1532 // task with root activity.
1533 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1534 finishWithRootActivity, "finish-activity");
1535 if (!res) {
1536 Slog.i(TAG, "Removing task failed to finish activity");
1537 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001538 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001539 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001540 } else {
1541 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1542 resultData, "app-request", true);
1543 if (!res) {
1544 Slog.i(TAG, "Failed to finish by app-request");
1545 }
1546 }
1547 return res;
1548 } finally {
1549 Binder.restoreCallingIdentity(origId);
1550 }
1551 }
1552 }
1553
1554 @Override
1555 public boolean finishActivityAffinity(IBinder token) {
1556 synchronized (mGlobalLock) {
1557 final long origId = Binder.clearCallingIdentity();
1558 try {
1559 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1560 if (r == null) {
1561 return false;
1562 }
1563
1564 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1565 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001566 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001567 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 return false;
1569 }
1570 return task.getStack().finishActivityAffinityLocked(r);
1571 } finally {
1572 Binder.restoreCallingIdentity(origId);
1573 }
1574 }
1575 }
1576
1577 @Override
1578 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1579 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001580 try {
1581 WindowProcessController proc = null;
1582 synchronized (mGlobalLock) {
1583 ActivityStack stack = ActivityRecord.getStackLocked(token);
1584 if (stack == null) {
1585 return;
1586 }
1587 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1588 false /* fromTimeout */, false /* processPausingActivities */, config);
1589 if (r != null) {
1590 proc = r.app;
1591 }
1592 if (stopProfiling && proc != null) {
1593 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001594 }
1595 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001596 } finally {
1597 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599 }
1600
1601 @Override
1602 public final void activityResumed(IBinder token) {
1603 final long origId = Binder.clearCallingIdentity();
1604 synchronized (mGlobalLock) {
1605 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001606 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001607 }
1608 Binder.restoreCallingIdentity(origId);
1609 }
1610
1611 @Override
1612 public final void activityPaused(IBinder token) {
1613 final long origId = Binder.clearCallingIdentity();
1614 synchronized (mGlobalLock) {
1615 ActivityStack stack = ActivityRecord.getStackLocked(token);
1616 if (stack != null) {
1617 stack.activityPausedLocked(token, false);
1618 }
1619 }
1620 Binder.restoreCallingIdentity(origId);
1621 }
1622
1623 @Override
1624 public final void activityStopped(IBinder token, Bundle icicle,
1625 PersistableBundle persistentState, CharSequence description) {
1626 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1627
1628 // Refuse possible leaked file descriptors
1629 if (icicle != null && icicle.hasFileDescriptors()) {
1630 throw new IllegalArgumentException("File descriptors passed in Bundle");
1631 }
1632
1633 final long origId = Binder.clearCallingIdentity();
1634
1635 synchronized (mGlobalLock) {
1636 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1637 if (r != null) {
1638 r.activityStoppedLocked(icicle, persistentState, description);
1639 }
1640 }
1641
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001642 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643
1644 Binder.restoreCallingIdentity(origId);
1645 }
1646
1647 @Override
1648 public final void activityDestroyed(IBinder token) {
1649 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1650 synchronized (mGlobalLock) {
1651 ActivityStack stack = ActivityRecord.getStackLocked(token);
1652 if (stack != null) {
1653 stack.activityDestroyedLocked(token, "activityDestroyed");
1654 }
1655 }
1656 }
1657
1658 @Override
1659 public final void activityRelaunched(IBinder token) {
1660 final long origId = Binder.clearCallingIdentity();
1661 synchronized (mGlobalLock) {
1662 mStackSupervisor.activityRelaunchedLocked(token);
1663 }
1664 Binder.restoreCallingIdentity(origId);
1665 }
1666
1667 public final void activitySlept(IBinder token) {
1668 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1669
1670 final long origId = Binder.clearCallingIdentity();
1671
1672 synchronized (mGlobalLock) {
1673 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1674 if (r != null) {
1675 mStackSupervisor.activitySleptLocked(r);
1676 }
1677 }
1678
1679 Binder.restoreCallingIdentity(origId);
1680 }
1681
1682 @Override
1683 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1684 synchronized (mGlobalLock) {
1685 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1686 if (r == null) {
1687 return;
1688 }
1689 final long origId = Binder.clearCallingIdentity();
1690 try {
1691 r.setRequestedOrientation(requestedOrientation);
1692 } finally {
1693 Binder.restoreCallingIdentity(origId);
1694 }
1695 }
1696 }
1697
1698 @Override
1699 public int getRequestedOrientation(IBinder token) {
1700 synchronized (mGlobalLock) {
1701 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1702 if (r == null) {
1703 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1704 }
1705 return r.getRequestedOrientation();
1706 }
1707 }
1708
1709 @Override
1710 public void setImmersive(IBinder token, boolean immersive) {
1711 synchronized (mGlobalLock) {
1712 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1713 if (r == null) {
1714 throw new IllegalArgumentException();
1715 }
1716 r.immersive = immersive;
1717
1718 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001719 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001721 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 }
1723 }
1724 }
1725
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001726 void applyUpdateLockStateLocked(ActivityRecord r) {
1727 // Modifications to the UpdateLock state are done on our handler, outside
1728 // the activity manager's locks. The new state is determined based on the
1729 // state *now* of the relevant activity record. The object is passed to
1730 // the handler solely for logging detail, not to be consulted/modified.
1731 final boolean nextState = r != null && r.immersive;
1732 mH.post(() -> {
1733 if (mUpdateLock.isHeld() != nextState) {
1734 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1735 "Applying new update lock state '" + nextState + "' for " + r);
1736 if (nextState) {
1737 mUpdateLock.acquire();
1738 } else {
1739 mUpdateLock.release();
1740 }
1741 }
1742 });
1743 }
1744
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 @Override
1746 public boolean isImmersive(IBinder token) {
1747 synchronized (mGlobalLock) {
1748 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1749 if (r == null) {
1750 throw new IllegalArgumentException();
1751 }
1752 return r.immersive;
1753 }
1754 }
1755
1756 @Override
1757 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001758 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001760 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761 return (r != null) ? r.immersive : false;
1762 }
1763 }
1764
1765 @Override
1766 public void overridePendingTransition(IBinder token, String packageName,
1767 int enterAnim, int exitAnim) {
1768 synchronized (mGlobalLock) {
1769 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1770 if (self == null) {
1771 return;
1772 }
1773
1774 final long origId = Binder.clearCallingIdentity();
1775
1776 if (self.isState(
1777 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001778 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001779 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001780 }
1781
1782 Binder.restoreCallingIdentity(origId);
1783 }
1784 }
1785
1786 @Override
1787 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001788 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001790 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001791 if (r == null) {
1792 return ActivityManager.COMPAT_MODE_UNKNOWN;
1793 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001794 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001795 }
1796 }
1797
1798 @Override
1799 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001800 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001804 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001805 if (r == null) {
1806 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1807 return;
1808 }
1809 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001810 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 }
1812 }
1813
1814 @Override
1815 public int getLaunchedFromUid(IBinder activityToken) {
1816 ActivityRecord srec;
1817 synchronized (mGlobalLock) {
1818 srec = ActivityRecord.forTokenLocked(activityToken);
1819 }
1820 if (srec == null) {
1821 return -1;
1822 }
1823 return srec.launchedFromUid;
1824 }
1825
1826 @Override
1827 public String getLaunchedFromPackage(IBinder activityToken) {
1828 ActivityRecord srec;
1829 synchronized (mGlobalLock) {
1830 srec = ActivityRecord.forTokenLocked(activityToken);
1831 }
1832 if (srec == null) {
1833 return null;
1834 }
1835 return srec.launchedFromPackage;
1836 }
1837
1838 @Override
1839 public boolean convertFromTranslucent(IBinder token) {
1840 final long origId = Binder.clearCallingIdentity();
1841 try {
1842 synchronized (mGlobalLock) {
1843 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1844 if (r == null) {
1845 return false;
1846 }
1847 final boolean translucentChanged = r.changeWindowTranslucency(true);
1848 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001849 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001850 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001851 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 return translucentChanged;
1853 }
1854 } finally {
1855 Binder.restoreCallingIdentity(origId);
1856 }
1857 }
1858
1859 @Override
1860 public boolean convertToTranslucent(IBinder token, Bundle options) {
1861 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1862 final long origId = Binder.clearCallingIdentity();
1863 try {
1864 synchronized (mGlobalLock) {
1865 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1866 if (r == null) {
1867 return false;
1868 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001869 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 int index = task.mActivities.lastIndexOf(r);
1871 if (index > 0) {
1872 ActivityRecord under = task.mActivities.get(index - 1);
1873 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1874 }
1875 final boolean translucentChanged = r.changeWindowTranslucency(false);
1876 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001877 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001879 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001880 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 return translucentChanged;
1882 }
1883 } finally {
1884 Binder.restoreCallingIdentity(origId);
1885 }
1886 }
1887
1888 @Override
1889 public void notifyActivityDrawn(IBinder token) {
1890 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1891 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001892 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001894 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 }
1896 }
1897 }
1898
1899 @Override
1900 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1901 synchronized (mGlobalLock) {
1902 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1903 if (r == null) {
1904 return;
1905 }
1906 r.reportFullyDrawnLocked(restoredFromBundle);
1907 }
1908 }
1909
1910 @Override
1911 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1912 synchronized (mGlobalLock) {
1913 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1914 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1915 return stack.mDisplayId;
1916 }
1917 return DEFAULT_DISPLAY;
1918 }
1919 }
1920
1921 @Override
1922 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 long ident = Binder.clearCallingIdentity();
1925 try {
1926 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001927 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001929 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001930 }
1931 return null;
1932 }
1933 } finally {
1934 Binder.restoreCallingIdentity(ident);
1935 }
1936 }
1937
1938 @Override
1939 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001940 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1942 final long callingId = Binder.clearCallingIdentity();
1943 try {
1944 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001945 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 if (stack == null) {
1947 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1948 return;
1949 }
1950 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001951 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001952 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 }
1954 }
1955 } finally {
1956 Binder.restoreCallingIdentity(callingId);
1957 }
1958 }
1959
1960 @Override
1961 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001962 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1964 final long callingId = Binder.clearCallingIdentity();
1965 try {
1966 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001967 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001968 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001969 if (task == null) {
1970 return;
1971 }
1972 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001973 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001974 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 }
1976 }
1977 } finally {
1978 Binder.restoreCallingIdentity(callingId);
1979 }
1980 }
1981
1982 @Override
1983 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001984 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 synchronized (mGlobalLock) {
1986 final long ident = Binder.clearCallingIdentity();
1987 try {
1988 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1989 "remove-task");
1990 } finally {
1991 Binder.restoreCallingIdentity(ident);
1992 }
1993 }
1994 }
1995
1996 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001997 public void removeAllVisibleRecentTasks() {
1998 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1999 synchronized (mGlobalLock) {
2000 final long ident = Binder.clearCallingIdentity();
2001 try {
2002 getRecentTasks().removeAllVisibleTasks();
2003 } finally {
2004 Binder.restoreCallingIdentity(ident);
2005 }
2006 }
2007 }
2008
2009 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2011 synchronized (mGlobalLock) {
2012 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2013 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002014 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 }
2016 }
2017 return false;
2018 }
2019
2020 @Override
2021 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2022 Intent resultData) {
2023
2024 synchronized (mGlobalLock) {
2025 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2026 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002027 return r.getActivityStack().navigateUpToLocked(
2028 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 }
2030 return false;
2031 }
2032 }
2033
2034 /**
2035 * Attempts to move a task backwards in z-order (the order of activities within the task is
2036 * unchanged).
2037 *
2038 * There are several possible results of this call:
2039 * - if the task is locked, then we will show the lock toast
2040 * - if there is a task behind the provided task, then that task is made visible and resumed as
2041 * this task is moved to the back
2042 * - otherwise, if there are no other tasks in the stack:
2043 * - if this task is in the pinned stack, then we remove the stack completely, which will
2044 * have the effect of moving the task to the top or bottom of the fullscreen stack
2045 * (depending on whether it is visible)
2046 * - otherwise, we simply return home and hide this task
2047 *
2048 * @param token A reference to the activity we wish to move
2049 * @param nonRoot If false then this only works if the activity is the root
2050 * of a task; if true it will work for any activity in a task.
2051 * @return Returns true if the move completed, false if not.
2052 */
2053 @Override
2054 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002055 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 synchronized (mGlobalLock) {
2057 final long origId = Binder.clearCallingIdentity();
2058 try {
2059 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002060 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 if (task != null) {
2062 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2063 }
2064 } finally {
2065 Binder.restoreCallingIdentity(origId);
2066 }
2067 }
2068 return false;
2069 }
2070
2071 @Override
2072 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002073 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 long ident = Binder.clearCallingIdentity();
2075 Rect rect = new Rect();
2076 try {
2077 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002078 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2080 if (task == null) {
2081 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2082 return rect;
2083 }
2084 if (task.getStack() != null) {
2085 // Return the bounds from window manager since it will be adjusted for various
2086 // things like the presense of a docked stack for tasks that aren't resizeable.
2087 task.getWindowContainerBounds(rect);
2088 } else {
2089 // Task isn't in window manager yet since it isn't associated with a stack.
2090 // Return the persist value from activity manager
2091 if (!task.matchParentBounds()) {
2092 rect.set(task.getBounds());
2093 } else if (task.mLastNonFullscreenBounds != null) {
2094 rect.set(task.mLastNonFullscreenBounds);
2095 }
2096 }
2097 }
2098 } finally {
2099 Binder.restoreCallingIdentity(ident);
2100 }
2101 return rect;
2102 }
2103
2104 @Override
2105 public ActivityManager.TaskDescription getTaskDescription(int id) {
2106 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002107 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002109 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2111 if (tr != null) {
2112 return tr.lastTaskDescription;
2113 }
2114 }
2115 return null;
2116 }
2117
2118 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002119 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2120 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2121 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2122 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2123 return;
2124 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002125 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002126 synchronized (mGlobalLock) {
2127 final long ident = Binder.clearCallingIdentity();
2128 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002129 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002130 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002131 if (task == null) {
2132 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2133 return;
2134 }
2135
2136 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2137 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2138
2139 if (!task.isActivityTypeStandardOrUndefined()) {
2140 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2141 + " non-standard task " + taskId + " to windowing mode="
2142 + windowingMode);
2143 }
2144
2145 final ActivityStack stack = task.getStack();
2146 if (toTop) {
2147 stack.moveToFront("setTaskWindowingMode", task);
2148 }
2149 stack.setWindowingMode(windowingMode);
2150 } finally {
2151 Binder.restoreCallingIdentity(ident);
2152 }
2153 }
2154 }
2155
2156 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002158 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 ActivityRecord r = getCallingRecordLocked(token);
2160 return r != null ? r.info.packageName : null;
2161 }
2162 }
2163
2164 @Override
2165 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002166 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 ActivityRecord r = getCallingRecordLocked(token);
2168 return r != null ? r.intent.getComponent() : null;
2169 }
2170 }
2171
2172 private ActivityRecord getCallingRecordLocked(IBinder token) {
2173 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2174 if (r == null) {
2175 return null;
2176 }
2177 return r.resultTo;
2178 }
2179
2180 @Override
2181 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002182 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002183
2184 synchronized (mGlobalLock) {
2185 final long origId = Binder.clearCallingIdentity();
2186 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002187 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 } finally {
2189 Binder.restoreCallingIdentity(origId);
2190 }
2191 }
2192 }
2193
2194 /**
2195 * TODO: Add mController hook
2196 */
2197 @Override
2198 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002199 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200
2201 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2202 synchronized (mGlobalLock) {
2203 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2204 false /* fromRecents */);
2205 }
2206 }
2207
2208 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2209 boolean fromRecents) {
2210
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002211 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 Binder.getCallingUid(), -1, -1, "Task to front")) {
2213 SafeActivityOptions.abort(options);
2214 return;
2215 }
2216 final long origId = Binder.clearCallingIdentity();
2217 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002218 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 if (task == null) {
2220 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002221 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 return;
2223 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002224 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002226 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 return;
2228 }
2229 ActivityOptions realOptions = options != null
2230 ? options.getOptions(mStackSupervisor)
2231 : null;
2232 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2233 false /* forceNonResizable */);
2234
2235 final ActivityRecord topActivity = task.getTopActivity();
2236 if (topActivity != null) {
2237
2238 // We are reshowing a task, use a starting window to hide the initial draw delay
2239 // so the transition can start earlier.
2240 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2241 true /* taskSwitch */, fromRecents);
2242 }
2243 } finally {
2244 Binder.restoreCallingIdentity(origId);
2245 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 }
2247
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002248 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2249 int callingPid, int callingUid, String name) {
2250 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2251 return true;
2252 }
2253
2254 if (getRecentTasks().isCallerRecents(sourceUid)) {
2255 return true;
2256 }
2257
2258 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2259 if (perm == PackageManager.PERMISSION_GRANTED) {
2260 return true;
2261 }
2262 if (checkAllowAppSwitchUid(sourceUid)) {
2263 return true;
2264 }
2265
2266 // If the actual IPC caller is different from the logical source, then
2267 // also see if they are allowed to control app switches.
2268 if (callingUid != -1 && callingUid != sourceUid) {
2269 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2270 if (perm == PackageManager.PERMISSION_GRANTED) {
2271 return true;
2272 }
2273 if (checkAllowAppSwitchUid(callingUid)) {
2274 return true;
2275 }
2276 }
2277
2278 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2279 return false;
2280 }
2281
2282 private boolean checkAllowAppSwitchUid(int uid) {
2283 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2284 if (types != null) {
2285 for (int i = types.size() - 1; i >= 0; i--) {
2286 if (types.valueAt(i).intValue() == uid) {
2287 return true;
2288 }
2289 }
2290 }
2291 return false;
2292 }
2293
2294 @Override
2295 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2296 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2297 "setActivityController()");
2298 synchronized (mGlobalLock) {
2299 mController = controller;
2300 mControllerIsAMonkey = imAMonkey;
2301 Watchdog.getInstance().setActivityController(controller);
2302 }
2303 }
2304
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002305 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 synchronized (mGlobalLock) {
2307 return mController != null && mControllerIsAMonkey;
2308 }
2309 }
2310
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 @Override
2312 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2313 synchronized (mGlobalLock) {
2314 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2315 }
2316 }
2317
2318 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002319 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2320 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2321 }
2322
2323 @Override
2324 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2325 @WindowConfiguration.ActivityType int ignoreActivityType,
2326 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2327 final int callingUid = Binder.getCallingUid();
2328 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2329
2330 synchronized (mGlobalLock) {
2331 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2332
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002333 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002334 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002335 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002336 ignoreWindowingMode, callingUid, allowed);
2337 }
2338
2339 return list;
2340 }
2341
2342 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2344 synchronized (mGlobalLock) {
2345 final long origId = Binder.clearCallingIdentity();
2346 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2347 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002348 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002349 }
2350 Binder.restoreCallingIdentity(origId);
2351 }
2352 }
2353
2354 @Override
2355 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002356 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357 ActivityStack stack = ActivityRecord.getStackLocked(token);
2358 if (stack != null) {
2359 return stack.willActivityBeVisibleLocked(token);
2360 }
2361 return false;
2362 }
2363 }
2364
2365 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002366 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002368 synchronized (mGlobalLock) {
2369 final long ident = Binder.clearCallingIdentity();
2370 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002371 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002372 if (task == null) {
2373 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2374 return;
2375 }
2376
2377 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2378 + " to stackId=" + stackId + " toTop=" + toTop);
2379
Wale Ogunwaled32da472018-11-16 07:19:28 -08002380 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002381 if (stack == null) {
2382 throw new IllegalStateException(
2383 "moveTaskToStack: No stack for stackId=" + stackId);
2384 }
2385 if (!stack.isActivityTypeStandardOrUndefined()) {
2386 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2387 + taskId + " to stack " + stackId);
2388 }
2389 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002390 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002391 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2392 }
2393 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2394 "moveTaskToStack");
2395 } finally {
2396 Binder.restoreCallingIdentity(ident);
2397 }
2398 }
2399 }
2400
2401 @Override
2402 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2403 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002404 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002405
2406 final long ident = Binder.clearCallingIdentity();
2407 try {
2408 synchronized (mGlobalLock) {
2409 if (animate) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002410 final PinnedActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002411 if (stack == null) {
2412 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2413 return;
2414 }
2415 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2416 throw new IllegalArgumentException("Stack: " + stackId
2417 + " doesn't support animated resize.");
2418 }
2419 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2420 animationDuration, false /* fromFullscreen */);
2421 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002422 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002423 if (stack == null) {
2424 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2425 return;
2426 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002427 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002428 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2429 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2430 }
2431 }
2432 } finally {
2433 Binder.restoreCallingIdentity(ident);
2434 }
2435 }
2436
2437 /**
2438 * Moves the specified task to the primary-split-screen stack.
2439 *
2440 * @param taskId Id of task to move.
2441 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2442 * exist already. See
2443 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2444 * and
2445 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2446 * @param toTop If the task and stack should be moved to the top.
2447 * @param animate Whether we should play an animation for the moving the task.
2448 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2449 * stack. Pass {@code null} to use default bounds.
2450 * @param showRecents If the recents activity should be shown on the other side of the task
2451 * going into split-screen mode.
2452 */
2453 @Override
2454 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2455 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002457 "setTaskWindowingModeSplitScreenPrimary()");
2458 synchronized (mGlobalLock) {
2459 final long ident = Binder.clearCallingIdentity();
2460 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002461 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002462 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002463 if (task == null) {
2464 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2465 return false;
2466 }
2467 if (DEBUG_STACK) Slog.d(TAG_STACK,
2468 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2469 + " to createMode=" + createMode + " toTop=" + toTop);
2470 if (!task.isActivityTypeStandardOrUndefined()) {
2471 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2472 + " non-standard task " + taskId + " to split-screen windowing mode");
2473 }
2474
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002475 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002476 final int windowingMode = task.getWindowingMode();
2477 final ActivityStack stack = task.getStack();
2478 if (toTop) {
2479 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2480 }
2481 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002482 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2483 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002484 return windowingMode != task.getWindowingMode();
2485 } finally {
2486 Binder.restoreCallingIdentity(ident);
2487 }
2488 }
2489 }
2490
2491 /**
2492 * Removes stacks in the input windowing modes from the system if they are of activity type
2493 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2494 */
2495 @Override
2496 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002497 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002498 "removeStacksInWindowingModes()");
2499
2500 synchronized (mGlobalLock) {
2501 final long ident = Binder.clearCallingIdentity();
2502 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002503 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 } finally {
2505 Binder.restoreCallingIdentity(ident);
2506 }
2507 }
2508 }
2509
2510 @Override
2511 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002512 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002513 "removeStacksWithActivityTypes()");
2514
2515 synchronized (mGlobalLock) {
2516 final long ident = Binder.clearCallingIdentity();
2517 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002518 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 } finally {
2520 Binder.restoreCallingIdentity(ident);
2521 }
2522 }
2523 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524
2525 @Override
2526 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2527 int userId) {
2528 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2530 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002531 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002532 final boolean detailed = checkGetTasksPermission(
2533 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2534 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 == PackageManager.PERMISSION_GRANTED;
2536
2537 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002538 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002539 callingUid);
2540 }
2541 }
2542
2543 @Override
2544 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002545 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 long ident = Binder.clearCallingIdentity();
2547 try {
2548 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002549 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 }
2551 } finally {
2552 Binder.restoreCallingIdentity(ident);
2553 }
2554 }
2555
2556 @Override
2557 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002558 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002559 long ident = Binder.clearCallingIdentity();
2560 try {
2561 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002562 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002563 }
2564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568
2569 @Override
2570 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002572 final long callingUid = Binder.getCallingUid();
2573 final long origId = Binder.clearCallingIdentity();
2574 try {
2575 synchronized (mGlobalLock) {
2576 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002577 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002578 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2579 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2580 }
2581 } finally {
2582 Binder.restoreCallingIdentity(origId);
2583 }
2584 }
2585
2586 @Override
2587 public void startLockTaskModeByToken(IBinder token) {
2588 synchronized (mGlobalLock) {
2589 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2590 if (r == null) {
2591 return;
2592 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002593 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002594 }
2595 }
2596
2597 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002598 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002599 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002600 // This makes inner call to look as if it was initiated by system.
2601 long ident = Binder.clearCallingIdentity();
2602 try {
2603 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002604 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002605 MATCH_TASK_IN_STACKS_ONLY);
2606 if (task == null) {
2607 return;
2608 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002609
2610 // When starting lock task mode the stack must be in front and focused
2611 task.getStack().moveToFront("startSystemLockTaskMode");
2612 startLockTaskModeLocked(task, true /* isSystemCaller */);
2613 }
2614 } finally {
2615 Binder.restoreCallingIdentity(ident);
2616 }
2617 }
2618
2619 @Override
2620 public void stopLockTaskModeByToken(IBinder token) {
2621 synchronized (mGlobalLock) {
2622 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2623 if (r == null) {
2624 return;
2625 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002626 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002627 }
2628 }
2629
2630 /**
2631 * This API should be called by SystemUI only when user perform certain action to dismiss
2632 * lock task mode. We should only dismiss pinned lock task mode in this case.
2633 */
2634 @Override
2635 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002636 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002637 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2638 }
2639
2640 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2641 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2642 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2643 return;
2644 }
2645
Wale Ogunwaled32da472018-11-16 07:19:28 -08002646 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002647 if (stack == null || task != stack.topTask()) {
2648 throw new IllegalArgumentException("Invalid task, not in foreground");
2649 }
2650
2651 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2652 // system or a specific app.
2653 // * System-initiated requests will only start the pinned mode (screen pinning)
2654 // * App-initiated requests
2655 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2656 // - will start the pinned mode, otherwise
2657 final int callingUid = Binder.getCallingUid();
2658 long ident = Binder.clearCallingIdentity();
2659 try {
2660 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002661 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002663 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002664 } finally {
2665 Binder.restoreCallingIdentity(ident);
2666 }
2667 }
2668
2669 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2670 final int callingUid = Binder.getCallingUid();
2671 long ident = Binder.clearCallingIdentity();
2672 try {
2673 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002674 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002675 }
2676 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2677 // task and jumping straight into a call in the case of emergency call back.
2678 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2679 if (tm != null) {
2680 tm.showInCallScreen(false);
2681 }
2682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
2686
2687 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002688 public void updateLockTaskPackages(int userId, String[] packages) {
2689 final int callingUid = Binder.getCallingUid();
2690 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2691 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2692 "updateLockTaskPackages()");
2693 }
2694 synchronized (this) {
2695 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2696 + Arrays.toString(packages));
2697 getLockTaskController().updateLockTaskPackages(userId, packages);
2698 }
2699 }
2700
2701 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 public boolean isInLockTaskMode() {
2703 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2704 }
2705
2706 @Override
2707 public int getLockTaskModeState() {
2708 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002709 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002710 }
2711 }
2712
2713 @Override
2714 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2715 synchronized (mGlobalLock) {
2716 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2717 if (r != null) {
2718 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002719 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002721 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002722 }
2723 }
2724 }
2725
2726 @Override
2727 public Bundle getActivityOptions(IBinder token) {
2728 final long origId = Binder.clearCallingIdentity();
2729 try {
2730 synchronized (mGlobalLock) {
2731 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2732 if (r != null) {
2733 final ActivityOptions activityOptions = r.takeOptionsLocked();
2734 return activityOptions == null ? null : activityOptions.toBundle();
2735 }
2736 return null;
2737 }
2738 } finally {
2739 Binder.restoreCallingIdentity(origId);
2740 }
2741 }
2742
2743 @Override
2744 public List<IBinder> getAppTasks(String callingPackage) {
2745 int callingUid = Binder.getCallingUid();
2746 long ident = Binder.clearCallingIdentity();
2747 try {
2748 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002749 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 }
2751 } finally {
2752 Binder.restoreCallingIdentity(ident);
2753 }
2754 }
2755
2756 @Override
2757 public void finishVoiceTask(IVoiceInteractionSession session) {
2758 synchronized (mGlobalLock) {
2759 final long origId = Binder.clearCallingIdentity();
2760 try {
2761 // TODO: VI Consider treating local voice interactions and voice tasks
2762 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002763 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 } finally {
2765 Binder.restoreCallingIdentity(origId);
2766 }
2767 }
2768
2769 }
2770
2771 @Override
2772 public boolean isTopOfTask(IBinder token) {
2773 synchronized (mGlobalLock) {
2774 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002775 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 }
2777 }
2778
2779 @Override
2780 public void notifyLaunchTaskBehindComplete(IBinder token) {
2781 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2782 }
2783
2784 @Override
2785 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002786 mH.post(() -> {
2787 synchronized (mGlobalLock) {
2788 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002789 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002790 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002791 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002792 } catch (RemoteException e) {
2793 }
2794 }
2795 }
2796
2797 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 }
2799
2800 /** Called from an app when assist data is ready. */
2801 @Override
2802 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2803 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 synchronized (pae) {
2806 pae.result = extras;
2807 pae.structure = structure;
2808 pae.content = content;
2809 if (referrer != null) {
2810 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2811 }
2812 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002813 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002814 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2815 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 structure.setHomeActivity(pae.isHome);
2817 }
2818 pae.haveResult = true;
2819 pae.notifyAll();
2820 if (pae.intent == null && pae.receiver == null) {
2821 // Caller is just waiting for the result.
2822 return;
2823 }
2824 }
2825 // We are now ready to launch the assist activity.
2826 IAssistDataReceiver sendReceiver = null;
2827 Bundle sendBundle = null;
2828 synchronized (mGlobalLock) {
2829 buildAssistBundleLocked(pae, extras);
2830 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002831 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 if (!exists) {
2833 // Timed out.
2834 return;
2835 }
2836
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002837 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 // Caller wants result sent back to them.
2839 sendBundle = new Bundle();
2840 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2841 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2842 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2843 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2844 }
2845 }
2846 if (sendReceiver != null) {
2847 try {
2848 sendReceiver.onHandleAssistData(sendBundle);
2849 } catch (RemoteException e) {
2850 }
2851 return;
2852 }
2853
2854 final long ident = Binder.clearCallingIdentity();
2855 try {
2856 if (TextUtils.equals(pae.intent.getAction(),
2857 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2858 pae.intent.putExtras(pae.extras);
2859 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2860 } else {
2861 pae.intent.replaceExtras(pae.extras);
2862 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2863 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2864 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002865 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866
2867 try {
2868 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2869 } catch (ActivityNotFoundException e) {
2870 Slog.w(TAG, "No activity to handle assist action.", e);
2871 }
2872 }
2873 } finally {
2874 Binder.restoreCallingIdentity(ident);
2875 }
2876 }
2877
2878 @Override
2879 public int addAppTask(IBinder activityToken, Intent intent,
2880 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2881 final int callingUid = Binder.getCallingUid();
2882 final long callingIdent = Binder.clearCallingIdentity();
2883
2884 try {
2885 synchronized (mGlobalLock) {
2886 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2887 if (r == null) {
2888 throw new IllegalArgumentException("Activity does not exist; token="
2889 + activityToken);
2890 }
2891 ComponentName comp = intent.getComponent();
2892 if (comp == null) {
2893 throw new IllegalArgumentException("Intent " + intent
2894 + " must specify explicit component");
2895 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002896 if (thumbnail.getWidth() != mThumbnailWidth
2897 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 throw new IllegalArgumentException("Bad thumbnail size: got "
2899 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002900 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 if (intent.getSelector() != null) {
2903 intent.setSelector(null);
2904 }
2905 if (intent.getSourceBounds() != null) {
2906 intent.setSourceBounds(null);
2907 }
2908 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2909 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2910 // The caller has added this as an auto-remove task... that makes no
2911 // sense, so turn off auto-remove.
2912 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2913 }
2914 }
2915 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2916 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2917 if (ainfo.applicationInfo.uid != callingUid) {
2918 throw new SecurityException(
2919 "Can't add task for another application: target uid="
2920 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2921 }
2922
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002923 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002925 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002927 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002928 // The app has too many tasks already and we can't add any more
2929 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2930 return INVALID_TASK_ID;
2931 }
2932 task.lastTaskDescription.copyFrom(description);
2933
2934 // TODO: Send the thumbnail to WM to store it.
2935
2936 return task.taskId;
2937 }
2938 } finally {
2939 Binder.restoreCallingIdentity(callingIdent);
2940 }
2941 }
2942
2943 @Override
2944 public Point getAppTaskThumbnailSize() {
2945 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002946 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 }
2948 }
2949
2950 @Override
2951 public void setTaskResizeable(int taskId, int resizeableMode) {
2952 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002953 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2955 if (task == null) {
2956 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2957 return;
2958 }
2959 task.setResizeMode(resizeableMode);
2960 }
2961 }
2962
2963 @Override
2964 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002965 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 long ident = Binder.clearCallingIdentity();
2967 try {
2968 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002969 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002970 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 if (task == null) {
2972 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2973 return;
2974 }
2975 // Place the task in the right stack if it isn't there already based on
2976 // the requested bounds.
2977 // The stack transition logic is:
2978 // - a null bounds on a freeform task moves that task to fullscreen
2979 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2980 // that task to freeform
2981 // - otherwise the task is not moved
2982 ActivityStack stack = task.getStack();
2983 if (!task.getWindowConfiguration().canResizeTask()) {
2984 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2985 }
2986 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2987 stack = stack.getDisplay().getOrCreateStack(
2988 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2989 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2990 stack = stack.getDisplay().getOrCreateStack(
2991 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2992 }
2993
2994 // Reparent the task to the right stack if necessary
2995 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2996 if (stack != task.getStack()) {
2997 // Defer resume until the task is resized below
2998 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2999 DEFER_RESUME, "resizeTask");
3000 preserveWindow = false;
3001 }
3002
3003 // After reparenting (which only resizes the task to the stack bounds), resize the
3004 // task to the actual bounds provided
3005 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3006 }
3007 } finally {
3008 Binder.restoreCallingIdentity(ident);
3009 }
3010 }
3011
3012 @Override
3013 public boolean releaseActivityInstance(IBinder token) {
3014 synchronized (mGlobalLock) {
3015 final long origId = Binder.clearCallingIdentity();
3016 try {
3017 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3018 if (r == null) {
3019 return false;
3020 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003021 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 } finally {
3023 Binder.restoreCallingIdentity(origId);
3024 }
3025 }
3026 }
3027
3028 @Override
3029 public void releaseSomeActivities(IApplicationThread appInt) {
3030 synchronized (mGlobalLock) {
3031 final long origId = Binder.clearCallingIdentity();
3032 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003033 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003034 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 } finally {
3036 Binder.restoreCallingIdentity(origId);
3037 }
3038 }
3039 }
3040
3041 @Override
3042 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003043 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003044 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 != PackageManager.PERMISSION_GRANTED) {
3046 throw new SecurityException("Requires permission "
3047 + android.Manifest.permission.DEVICE_POWER);
3048 }
3049
3050 synchronized (mGlobalLock) {
3051 long ident = Binder.clearCallingIdentity();
3052 if (mKeyguardShown != keyguardShowing) {
3053 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003054 final Message msg = PooledLambda.obtainMessage(
3055 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3056 keyguardShowing);
3057 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 }
3059 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003060 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003061 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 } finally {
3063 Binder.restoreCallingIdentity(ident);
3064 }
3065 }
3066
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003067 mH.post(() -> {
3068 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3069 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3070 }
3071 });
3072 }
3073
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003074 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003075 mH.post(() -> {
3076 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3077 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3078 }
3079 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 }
3081
3082 @Override
3083 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003084 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3085 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086
3087 final File passedIconFile = new File(filePath);
3088 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3089 passedIconFile.getName());
3090 if (!legitIconFile.getPath().equals(filePath)
3091 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3092 throw new IllegalArgumentException("Bad file path: " + filePath
3093 + " passed for userId " + userId);
3094 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003095 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 }
3097
3098 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003099 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3101 final ActivityOptions activityOptions = safeOptions != null
3102 ? safeOptions.getOptions(mStackSupervisor)
3103 : null;
3104 if (activityOptions == null
3105 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3106 || activityOptions.getCustomInPlaceResId() == 0) {
3107 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3108 "with valid animation");
3109 }
lumark588a3e82018-07-20 18:53:54 +08003110 // Get top display of front most application.
3111 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3112 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003113 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3114 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3115 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003116 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003117 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003118 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 }
3120
3121 @Override
3122 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003123 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 synchronized (mGlobalLock) {
3125 final long ident = Binder.clearCallingIdentity();
3126 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003127 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 if (stack == null) {
3129 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3130 return;
3131 }
3132 if (!stack.isActivityTypeStandardOrUndefined()) {
3133 throw new IllegalArgumentException(
3134 "Removing non-standard stack is not allowed.");
3135 }
3136 mStackSupervisor.removeStack(stack);
3137 } finally {
3138 Binder.restoreCallingIdentity(ident);
3139 }
3140 }
3141 }
3142
3143 @Override
3144 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003145 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146
3147 synchronized (mGlobalLock) {
3148 final long ident = Binder.clearCallingIdentity();
3149 try {
3150 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3151 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003152 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 } finally {
3154 Binder.restoreCallingIdentity(ident);
3155 }
3156 }
3157 }
3158
3159 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 public void exitFreeformMode(IBinder token) {
3161 synchronized (mGlobalLock) {
3162 long ident = Binder.clearCallingIdentity();
3163 try {
3164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3165 if (r == null) {
3166 throw new IllegalArgumentException(
3167 "exitFreeformMode: No activity record matching token=" + token);
3168 }
3169
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003170 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 if (stack == null || !stack.inFreeformWindowingMode()) {
3172 throw new IllegalStateException(
3173 "exitFreeformMode: You can only go fullscreen from freeform.");
3174 }
3175
3176 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3177 } finally {
3178 Binder.restoreCallingIdentity(ident);
3179 }
3180 }
3181 }
3182
3183 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3184 @Override
3185 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003188 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 }
3190
3191 /** Unregister a task stack listener so that it stops receiving callbacks. */
3192 @Override
3193 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003194 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003196 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197 }
3198
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003199 @Override
3200 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3201 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3202 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3203 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3204 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3205 }
3206
3207 @Override
3208 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3209 IBinder activityToken, int flags) {
3210 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3211 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3212 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3213 }
3214
3215 @Override
3216 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3217 Bundle args) {
3218 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3219 true /* focused */, true /* newSessionId */, userHandle, args,
3220 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3221 }
3222
3223 @Override
3224 public Bundle getAssistContextExtras(int requestType) {
3225 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3226 null, null, true /* focused */, true /* newSessionId */,
3227 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3228 if (pae == null) {
3229 return null;
3230 }
3231 synchronized (pae) {
3232 while (!pae.haveResult) {
3233 try {
3234 pae.wait();
3235 } catch (InterruptedException e) {
3236 }
3237 }
3238 }
3239 synchronized (mGlobalLock) {
3240 buildAssistBundleLocked(pae, pae.result);
3241 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003242 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 }
3244 return pae.extras;
3245 }
3246
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003247 /**
3248 * Binder IPC calls go through the public entry point.
3249 * This can be called with or without the global lock held.
3250 */
3251 private static int checkCallingPermission(String permission) {
3252 return checkPermission(
3253 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3254 }
3255
3256 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003257 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003258 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3259 mAmInternal.enforceCallingPermission(permission, func);
3260 }
3261 }
3262
3263 @VisibleForTesting
3264 int checkGetTasksPermission(String permission, int pid, int uid) {
3265 return checkPermission(permission, pid, uid);
3266 }
3267
3268 static int checkPermission(String permission, int pid, int uid) {
3269 if (permission == null) {
3270 return PackageManager.PERMISSION_DENIED;
3271 }
3272 return checkComponentPermission(permission, pid, uid, -1, true);
3273 }
3274
Wale Ogunwale214f3482018-10-04 11:00:47 -07003275 public static int checkComponentPermission(String permission, int pid, int uid,
3276 int owningUid, boolean exported) {
3277 return ActivityManagerService.checkComponentPermission(
3278 permission, pid, uid, owningUid, exported);
3279 }
3280
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003281 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3282 if (getRecentTasks().isCallerRecents(callingUid)) {
3283 // Always allow the recents component to get tasks
3284 return true;
3285 }
3286
3287 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3288 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3289 if (!allowed) {
3290 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3291 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3292 // Temporary compatibility: some existing apps on the system image may
3293 // still be requesting the old permission and not switched to the new
3294 // one; if so, we'll still allow them full access. This means we need
3295 // to see if they are holding the old permission and are a system app.
3296 try {
3297 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3298 allowed = true;
3299 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3300 + " is using old GET_TASKS but privileged; allowing");
3301 }
3302 } catch (RemoteException e) {
3303 }
3304 }
3305 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3306 + " does not hold REAL_GET_TASKS; limiting output");
3307 }
3308 return allowed;
3309 }
3310
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3312 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3313 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3314 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003315 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 "enqueueAssistContext()");
3317
3318 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003319 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 if (activity == null) {
3321 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3322 return null;
3323 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003324 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3326 return null;
3327 }
3328 if (focused) {
3329 if (activityToken != null) {
3330 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3331 if (activity != caller) {
3332 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3333 + " is not current top " + activity);
3334 return null;
3335 }
3336 }
3337 } else {
3338 activity = ActivityRecord.forTokenLocked(activityToken);
3339 if (activity == null) {
3340 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3341 + " couldn't be found");
3342 return null;
3343 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003344 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3346 return null;
3347 }
3348 }
3349
3350 PendingAssistExtras pae;
3351 Bundle extras = new Bundle();
3352 if (args != null) {
3353 extras.putAll(args);
3354 }
3355 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003356 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357
3358 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3359 userHandle);
3360 pae.isHome = activity.isActivityTypeHome();
3361
3362 // Increment the sessionId if necessary
3363 if (newSessionId) {
3364 mViSessionId++;
3365 }
3366 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003367 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3368 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 } catch (RemoteException e) {
3372 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3373 return null;
3374 }
3375 return pae;
3376 }
3377 }
3378
3379 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3380 if (result != null) {
3381 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3382 }
3383 if (pae.hint != null) {
3384 pae.extras.putBoolean(pae.hint, true);
3385 }
3386 }
3387
3388 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3389 IAssistDataReceiver receiver;
3390 synchronized (mGlobalLock) {
3391 mPendingAssistExtras.remove(pae);
3392 receiver = pae.receiver;
3393 }
3394 if (receiver != null) {
3395 // Caller wants result sent back to them.
3396 Bundle sendBundle = new Bundle();
3397 // At least return the receiver extras
3398 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3399 try {
3400 pae.receiver.onHandleAssistData(sendBundle);
3401 } catch (RemoteException e) {
3402 }
3403 }
3404 }
3405
3406 public class PendingAssistExtras extends Binder implements Runnable {
3407 public final ActivityRecord activity;
3408 public boolean isHome;
3409 public final Bundle extras;
3410 public final Intent intent;
3411 public final String hint;
3412 public final IAssistDataReceiver receiver;
3413 public final int userHandle;
3414 public boolean haveResult = false;
3415 public Bundle result = null;
3416 public AssistStructure structure = null;
3417 public AssistContent content = null;
3418 public Bundle receiverExtras;
3419
3420 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3421 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3422 int _userHandle) {
3423 activity = _activity;
3424 extras = _extras;
3425 intent = _intent;
3426 hint = _hint;
3427 receiver = _receiver;
3428 receiverExtras = _receiverExtras;
3429 userHandle = _userHandle;
3430 }
3431
3432 @Override
3433 public void run() {
3434 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3435 synchronized (this) {
3436 haveResult = true;
3437 notifyAll();
3438 }
3439 pendingAssistExtrasTimedOut(this);
3440 }
3441 }
3442
3443 @Override
3444 public boolean isAssistDataAllowedOnCurrentActivity() {
3445 int userId;
3446 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003447 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003448 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3449 return false;
3450 }
3451
3452 final ActivityRecord activity = focusedStack.getTopActivity();
3453 if (activity == null) {
3454 return false;
3455 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003456 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003457 }
3458 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3459 }
3460
3461 @Override
3462 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3463 long ident = Binder.clearCallingIdentity();
3464 try {
3465 synchronized (mGlobalLock) {
3466 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003467 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 if (top != caller) {
3469 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3470 + " is not current top " + top);
3471 return false;
3472 }
3473 if (!top.nowVisible) {
3474 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3475 + " is not visible");
3476 return false;
3477 }
3478 }
3479 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3480 token);
3481 } finally {
3482 Binder.restoreCallingIdentity(ident);
3483 }
3484 }
3485
3486 @Override
3487 public boolean isRootVoiceInteraction(IBinder token) {
3488 synchronized (mGlobalLock) {
3489 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3490 if (r == null) {
3491 return false;
3492 }
3493 return r.rootVoiceInteraction;
3494 }
3495 }
3496
Wale Ogunwalef6733932018-06-27 05:14:34 -07003497 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3498 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3499 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3500 if (activityToCallback == null) return;
3501 activityToCallback.setVoiceSessionLocked(voiceSession);
3502
3503 // Inform the activity
3504 try {
3505 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3506 voiceInteractor);
3507 long token = Binder.clearCallingIdentity();
3508 try {
3509 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3510 } finally {
3511 Binder.restoreCallingIdentity(token);
3512 }
3513 // TODO: VI Should we cache the activity so that it's easier to find later
3514 // rather than scan through all the stacks and activities?
3515 } catch (RemoteException re) {
3516 activityToCallback.clearVoiceSessionLocked();
3517 // TODO: VI Should this terminate the voice session?
3518 }
3519 }
3520
3521 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3522 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3523 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3524 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3525 boolean wasRunningVoice = mRunningVoice != null;
3526 mRunningVoice = session;
3527 if (!wasRunningVoice) {
3528 mVoiceWakeLock.acquire();
3529 updateSleepIfNeededLocked();
3530 }
3531 }
3532 }
3533
3534 void finishRunningVoiceLocked() {
3535 if (mRunningVoice != null) {
3536 mRunningVoice = null;
3537 mVoiceWakeLock.release();
3538 updateSleepIfNeededLocked();
3539 }
3540 }
3541
3542 @Override
3543 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3544 synchronized (mGlobalLock) {
3545 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3546 if (keepAwake) {
3547 mVoiceWakeLock.acquire();
3548 } else {
3549 mVoiceWakeLock.release();
3550 }
3551 }
3552 }
3553 }
3554
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 @Override
3556 public ComponentName getActivityClassForToken(IBinder token) {
3557 synchronized (mGlobalLock) {
3558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3559 if (r == null) {
3560 return null;
3561 }
3562 return r.intent.getComponent();
3563 }
3564 }
3565
3566 @Override
3567 public String getPackageForToken(IBinder token) {
3568 synchronized (mGlobalLock) {
3569 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3570 if (r == null) {
3571 return null;
3572 }
3573 return r.packageName;
3574 }
3575 }
3576
3577 @Override
3578 public void showLockTaskEscapeMessage(IBinder token) {
3579 synchronized (mGlobalLock) {
3580 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3581 if (r == null) {
3582 return;
3583 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003584 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003585 }
3586 }
3587
3588 @Override
3589 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 final long token = Binder.clearCallingIdentity();
3592 try {
3593 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003594 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595 }
3596 } finally {
3597 Binder.restoreCallingIdentity(token);
3598 }
3599 }
3600
3601 /**
3602 * Try to place task to provided position. The final position might be different depending on
3603 * current user and stacks state. The task will be moved to target stack if it's currently in
3604 * different stack.
3605 */
3606 @Override
3607 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003608 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 synchronized (mGlobalLock) {
3610 long ident = Binder.clearCallingIdentity();
3611 try {
3612 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3613 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003614 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003615 if (task == null) {
3616 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3617 + taskId);
3618 }
3619
Wale Ogunwaled32da472018-11-16 07:19:28 -08003620 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003621
3622 if (stack == null) {
3623 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3624 + stackId);
3625 }
3626 if (!stack.isActivityTypeStandardOrUndefined()) {
3627 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3628 + " the position of task " + taskId + " in/to non-standard stack");
3629 }
3630
3631 // TODO: Have the callers of this API call a separate reparent method if that is
3632 // what they intended to do vs. having this method also do reparenting.
3633 if (task.getStack() == stack) {
3634 // Change position in current stack.
3635 stack.positionChildAt(task, position);
3636 } else {
3637 // Reparent to new stack.
3638 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3639 !DEFER_RESUME, "positionTaskInStack");
3640 }
3641 } finally {
3642 Binder.restoreCallingIdentity(ident);
3643 }
3644 }
3645 }
3646
3647 @Override
3648 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3649 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3650 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3651 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3652 synchronized (mGlobalLock) {
3653 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3654 if (record == null) {
3655 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3656 + "found for: " + token);
3657 }
3658 record.setSizeConfigurations(horizontalSizeConfiguration,
3659 verticalSizeConfigurations, smallestSizeConfigurations);
3660 }
3661 }
3662
3663 /**
3664 * Dismisses split-screen multi-window mode.
3665 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3666 */
3667 @Override
3668 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003669 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003670 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3671 final long ident = Binder.clearCallingIdentity();
3672 try {
3673 synchronized (mGlobalLock) {
3674 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003675 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003676 if (stack == null) {
3677 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3678 return;
3679 }
3680
3681 if (toTop) {
3682 // Caller wants the current split-screen primary stack to be the top stack after
3683 // it goes fullscreen, so move it to the front.
3684 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003685 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003686 // In this case the current split-screen primary stack shouldn't be the top
3687 // stack after it goes fullscreen, but it current has focus, so we move the
3688 // focus to the top-most split-screen secondary stack next to it.
3689 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3690 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3691 if (otherStack != null) {
3692 otherStack.moveToFront("dismissSplitScreenMode_other");
3693 }
3694 }
3695
Evan Rosky10475742018-09-05 19:02:48 -07003696 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 }
3698 } finally {
3699 Binder.restoreCallingIdentity(ident);
3700 }
3701 }
3702
3703 /**
3704 * Dismisses Pip
3705 * @param animate True if the dismissal should be animated.
3706 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3707 * default animation duration should be used.
3708 */
3709 @Override
3710 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003711 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003712 final long ident = Binder.clearCallingIdentity();
3713 try {
3714 synchronized (mGlobalLock) {
3715 final PinnedActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003716 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003717 if (stack == null) {
3718 Slog.w(TAG, "dismissPip: pinned stack not found.");
3719 return;
3720 }
3721 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3722 throw new IllegalArgumentException("Stack: " + stack
3723 + " doesn't support animated resize.");
3724 }
3725 if (animate) {
3726 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3727 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3728 } else {
3729 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3730 }
3731 }
3732 } finally {
3733 Binder.restoreCallingIdentity(ident);
3734 }
3735 }
3736
3737 @Override
3738 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003739 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 synchronized (mGlobalLock) {
3741 mSuppressResizeConfigChanges = suppress;
3742 }
3743 }
3744
3745 /**
3746 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3747 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3748 * activity and clearing the task at the same time.
3749 */
3750 @Override
3751 // TODO: API should just be about changing windowing modes...
3752 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003753 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003754 "moveTasksToFullscreenStack()");
3755 synchronized (mGlobalLock) {
3756 final long origId = Binder.clearCallingIdentity();
3757 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003758 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003759 if (stack != null){
3760 if (!stack.isActivityTypeStandardOrUndefined()) {
3761 throw new IllegalArgumentException(
3762 "You can't move tasks from non-standard stacks.");
3763 }
3764 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3765 }
3766 } finally {
3767 Binder.restoreCallingIdentity(origId);
3768 }
3769 }
3770 }
3771
3772 /**
3773 * Moves the top activity in the input stackId to the pinned stack.
3774 *
3775 * @param stackId Id of stack to move the top activity to pinned stack.
3776 * @param bounds Bounds to use for pinned stack.
3777 *
3778 * @return True if the top activity of the input stack was successfully moved to the pinned
3779 * stack.
3780 */
3781 @Override
3782 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003783 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003784 "moveTopActivityToPinnedStack()");
3785 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003786 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003787 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3788 + "Device doesn't support picture-in-picture mode");
3789 }
3790
3791 long ident = Binder.clearCallingIdentity();
3792 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003793 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 } finally {
3795 Binder.restoreCallingIdentity(ident);
3796 }
3797 }
3798 }
3799
3800 @Override
3801 public boolean isInMultiWindowMode(IBinder token) {
3802 final long origId = Binder.clearCallingIdentity();
3803 try {
3804 synchronized (mGlobalLock) {
3805 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3806 if (r == null) {
3807 return false;
3808 }
3809 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3810 return r.inMultiWindowMode();
3811 }
3812 } finally {
3813 Binder.restoreCallingIdentity(origId);
3814 }
3815 }
3816
3817 @Override
3818 public boolean isInPictureInPictureMode(IBinder token) {
3819 final long origId = Binder.clearCallingIdentity();
3820 try {
3821 synchronized (mGlobalLock) {
3822 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3823 }
3824 } finally {
3825 Binder.restoreCallingIdentity(origId);
3826 }
3827 }
3828
3829 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003830 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3831 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003832 return false;
3833 }
3834
3835 // If we are animating to fullscreen then we have already dispatched the PIP mode
3836 // changed, so we should reflect that check here as well.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003837 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 final PinnedStackWindowController windowController = stack.getWindowContainerController();
Evan Rosky1ac84462018-11-13 11:25:30 -08003839 return !windowController.mContainer.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 }
3841
3842 @Override
3843 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3844 final long origId = Binder.clearCallingIdentity();
3845 try {
3846 synchronized (mGlobalLock) {
3847 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3848 "enterPictureInPictureMode", token, params);
3849
3850 // If the activity is already in picture in picture mode, then just return early
3851 if (isInPictureInPictureMode(r)) {
3852 return true;
3853 }
3854
3855 // Activity supports picture-in-picture, now check that we can enter PiP at this
3856 // point, if it is
3857 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3858 false /* beforeStopping */)) {
3859 return false;
3860 }
3861
3862 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003863 synchronized (mGlobalLock) {
3864 // Only update the saved args from the args that are set
3865 r.pictureInPictureArgs.copyOnlySet(params);
3866 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3867 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3868 // Adjust the source bounds by the insets for the transition down
3869 final Rect sourceBounds = new Rect(
3870 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003871 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003872 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003873 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003874 stack.setPictureInPictureAspectRatio(aspectRatio);
3875 stack.setPictureInPictureActions(actions);
3876 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3877 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3878 logPictureInPictureArgs(params);
3879 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 };
3881
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003882 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003883 // If the keyguard is showing or occluded, then try and dismiss it before
3884 // entering picture-in-picture (this will prompt the user to authenticate if the
3885 // device is currently locked).
3886 dismissKeyguard(token, new KeyguardDismissCallback() {
3887 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003888 public void onDismissSucceeded() {
3889 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890 }
3891 }, null /* message */);
3892 } else {
3893 // Enter picture in picture immediately otherwise
3894 enterPipRunnable.run();
3895 }
3896 return true;
3897 }
3898 } finally {
3899 Binder.restoreCallingIdentity(origId);
3900 }
3901 }
3902
3903 @Override
3904 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3905 final long origId = Binder.clearCallingIdentity();
3906 try {
3907 synchronized (mGlobalLock) {
3908 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3909 "setPictureInPictureParams", token, params);
3910
3911 // Only update the saved args from the args that are set
3912 r.pictureInPictureArgs.copyOnlySet(params);
3913 if (r.inPinnedWindowingMode()) {
3914 // If the activity is already in picture-in-picture, update the pinned stack now
3915 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3916 // be used the next time the activity enters PiP
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003917 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 if (!stack.isAnimatingBoundsToFullscreen()) {
3919 stack.setPictureInPictureAspectRatio(
3920 r.pictureInPictureArgs.getAspectRatio());
3921 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3922 }
3923 }
3924 logPictureInPictureArgs(params);
3925 }
3926 } finally {
3927 Binder.restoreCallingIdentity(origId);
3928 }
3929 }
3930
3931 @Override
3932 public int getMaxNumPictureInPictureActions(IBinder token) {
3933 // Currently, this is a static constant, but later, we may change this to be dependent on
3934 // the context of the activity
3935 return 3;
3936 }
3937
3938 private void logPictureInPictureArgs(PictureInPictureParams params) {
3939 if (params.hasSetActions()) {
3940 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3941 params.getActions().size());
3942 }
3943 if (params.hasSetAspectRatio()) {
3944 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3945 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3946 MetricsLogger.action(lm);
3947 }
3948 }
3949
3950 /**
3951 * Checks the state of the system and the activity associated with the given {@param token} to
3952 * verify that picture-in-picture is supported for that activity.
3953 *
3954 * @return the activity record for the given {@param token} if all the checks pass.
3955 */
3956 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3957 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003958 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 throw new IllegalStateException(caller
3960 + ": Device doesn't support picture-in-picture mode.");
3961 }
3962
3963 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3964 if (r == null) {
3965 throw new IllegalStateException(caller
3966 + ": Can't find activity for token=" + token);
3967 }
3968
3969 if (!r.supportsPictureInPicture()) {
3970 throw new IllegalStateException(caller
3971 + ": Current activity does not support picture-in-picture.");
3972 }
3973
3974 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003975 && !mWindowManager.isValidPictureInPictureAspectRatio(
3976 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 final float minAspectRatio = mContext.getResources().getFloat(
3978 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3979 final float maxAspectRatio = mContext.getResources().getFloat(
3980 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3981 throw new IllegalArgumentException(String.format(caller
3982 + ": Aspect ratio is too extreme (must be between %f and %f).",
3983 minAspectRatio, maxAspectRatio));
3984 }
3985
3986 // Truncate the number of actions if necessary
3987 params.truncateActions(getMaxNumPictureInPictureActions(token));
3988
3989 return r;
3990 }
3991
3992 @Override
3993 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003994 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 synchronized (mGlobalLock) {
3996 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3997 if (r == null) {
3998 throw new IllegalArgumentException("Activity does not exist; token="
3999 + activityToken);
4000 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004001 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 }
4003 }
4004
4005 @Override
4006 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4007 Rect tempDockedTaskInsetBounds,
4008 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 long ident = Binder.clearCallingIdentity();
4011 try {
4012 synchronized (mGlobalLock) {
4013 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4014 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4015 PRESERVE_WINDOWS);
4016 }
4017 } finally {
4018 Binder.restoreCallingIdentity(ident);
4019 }
4020 }
4021
4022 @Override
4023 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 final long ident = Binder.clearCallingIdentity();
4026 try {
4027 synchronized (mGlobalLock) {
4028 mStackSupervisor.setSplitScreenResizing(resizing);
4029 }
4030 } finally {
4031 Binder.restoreCallingIdentity(ident);
4032 }
4033 }
4034
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004035 /**
4036 * Check that we have the features required for VR-related API calls, and throw an exception if
4037 * not.
4038 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004039 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004040 if (!mContext.getPackageManager().hasSystemFeature(
4041 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4042 throw new UnsupportedOperationException("VR mode not supported on this device!");
4043 }
4044 }
4045
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 @Override
4047 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004048 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049
4050 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4051
4052 ActivityRecord r;
4053 synchronized (mGlobalLock) {
4054 r = ActivityRecord.isInStackLocked(token);
4055 }
4056
4057 if (r == null) {
4058 throw new IllegalArgumentException();
4059 }
4060
4061 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004062 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 VrManagerInternal.NO_ERROR) {
4064 return err;
4065 }
4066
4067 // Clear the binder calling uid since this path may call moveToTask().
4068 final long callingId = Binder.clearCallingIdentity();
4069 try {
4070 synchronized (mGlobalLock) {
4071 r.requestedVrComponent = (enabled) ? packageName : null;
4072
4073 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004074 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004075 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 }
4077 return 0;
4078 }
4079 } finally {
4080 Binder.restoreCallingIdentity(callingId);
4081 }
4082 }
4083
4084 @Override
4085 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4086 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4087 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004088 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4090 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4091 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004092 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093 || activity.voiceSession != null) {
4094 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4095 return;
4096 }
4097 if (activity.pendingVoiceInteractionStart) {
4098 Slog.w(TAG, "Pending start of voice interaction already.");
4099 return;
4100 }
4101 activity.pendingVoiceInteractionStart = true;
4102 }
4103 LocalServices.getService(VoiceInteractionManagerInternal.class)
4104 .startLocalVoiceInteraction(callingActivity, options);
4105 }
4106
4107 @Override
4108 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4109 LocalServices.getService(VoiceInteractionManagerInternal.class)
4110 .stopLocalVoiceInteraction(callingActivity);
4111 }
4112
4113 @Override
4114 public boolean supportsLocalVoiceInteraction() {
4115 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4116 .supportsLocalVoiceInteraction();
4117 }
4118
4119 /** Notifies all listeners when the pinned stack animation starts. */
4120 @Override
4121 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004122 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 }
4124
4125 /** Notifies all listeners when the pinned stack animation ends. */
4126 @Override
4127 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004128 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 }
4130
4131 @Override
4132 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004133 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004134 final long ident = Binder.clearCallingIdentity();
4135 try {
4136 synchronized (mGlobalLock) {
4137 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4138 }
4139 } finally {
4140 Binder.restoreCallingIdentity(ident);
4141 }
4142 }
4143
4144 @Override
4145 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004146 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147
4148 synchronized (mGlobalLock) {
4149 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004150 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 // Call might come when display is not yet added or has already been removed.
4152 if (DEBUG_CONFIGURATION) {
4153 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4154 + displayId);
4155 }
4156 return false;
4157 }
4158
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004159 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004161 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 }
4163
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004164 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004165 final Message msg = PooledLambda.obtainMessage(
4166 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4167 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 }
4169
4170 final long origId = Binder.clearCallingIdentity();
4171 try {
4172 if (values != null) {
4173 Settings.System.clearConfiguration(values);
4174 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004175 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4177 return mTmpUpdateConfigurationResult.changes != 0;
4178 } finally {
4179 Binder.restoreCallingIdentity(origId);
4180 }
4181 }
4182 }
4183
4184 @Override
4185 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004186 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187
4188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004189 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004190 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 }
4193
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004194 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004195 final Message msg = PooledLambda.obtainMessage(
4196 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4197 DEFAULT_DISPLAY);
4198 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004199 }
4200
4201 final long origId = Binder.clearCallingIdentity();
4202 try {
4203 if (values != null) {
4204 Settings.System.clearConfiguration(values);
4205 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 UserHandle.USER_NULL, false /* deferResume */,
4208 mTmpUpdateConfigurationResult);
4209 return mTmpUpdateConfigurationResult.changes != 0;
4210 } finally {
4211 Binder.restoreCallingIdentity(origId);
4212 }
4213 }
4214 }
4215
4216 @Override
4217 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4218 CharSequence message) {
4219 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004220 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4222 }
4223 final long callingId = Binder.clearCallingIdentity();
4224 try {
4225 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004226 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 }
4228 } finally {
4229 Binder.restoreCallingIdentity(callingId);
4230 }
4231 }
4232
4233 @Override
4234 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 "cancelTaskWindowTransition()");
4237 final long ident = Binder.clearCallingIdentity();
4238 try {
4239 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004240 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 MATCH_TASK_IN_STACKS_ONLY);
4242 if (task == null) {
4243 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4244 return;
4245 }
4246 task.cancelWindowTransition();
4247 }
4248 } finally {
4249 Binder.restoreCallingIdentity(ident);
4250 }
4251 }
4252
4253 @Override
4254 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004255 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 final long ident = Binder.clearCallingIdentity();
4257 try {
4258 final TaskRecord task;
4259 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004260 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4262 if (task == null) {
4263 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4264 return null;
4265 }
4266 }
4267 // Don't call this while holding the lock as this operation might hit the disk.
4268 return task.getSnapshot(reducedResolution);
4269 } finally {
4270 Binder.restoreCallingIdentity(ident);
4271 }
4272 }
4273
4274 @Override
4275 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4276 synchronized (mGlobalLock) {
4277 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4278 if (r == null) {
4279 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4280 + token);
4281 return;
4282 }
4283 final long origId = Binder.clearCallingIdentity();
4284 try {
4285 r.setDisablePreviewScreenshots(disable);
4286 } finally {
4287 Binder.restoreCallingIdentity(origId);
4288 }
4289 }
4290 }
4291
4292 /** Return the user id of the last resumed activity. */
4293 @Override
4294 public @UserIdInt
4295 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004296 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004297 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4298 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004299 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004300 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004302 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 }
4304 }
4305
4306 @Override
4307 public void updateLockTaskFeatures(int userId, int flags) {
4308 final int callingUid = Binder.getCallingUid();
4309 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 "updateLockTaskFeatures()");
4312 }
4313 synchronized (mGlobalLock) {
4314 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4315 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004316 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 }
4318 }
4319
4320 @Override
4321 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4322 synchronized (mGlobalLock) {
4323 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4324 if (r == null) {
4325 return;
4326 }
4327 final long origId = Binder.clearCallingIdentity();
4328 try {
4329 r.setShowWhenLocked(showWhenLocked);
4330 } finally {
4331 Binder.restoreCallingIdentity(origId);
4332 }
4333 }
4334 }
4335
4336 @Override
4337 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4338 synchronized (mGlobalLock) {
4339 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4340 if (r == null) {
4341 return;
4342 }
4343 final long origId = Binder.clearCallingIdentity();
4344 try {
4345 r.setTurnScreenOn(turnScreenOn);
4346 } finally {
4347 Binder.restoreCallingIdentity(origId);
4348 }
4349 }
4350 }
4351
4352 @Override
4353 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004354 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004355 "registerRemoteAnimations");
4356 definition.setCallingPid(Binder.getCallingPid());
4357 synchronized (mGlobalLock) {
4358 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4359 if (r == null) {
4360 return;
4361 }
4362 final long origId = Binder.clearCallingIdentity();
4363 try {
4364 r.registerRemoteAnimations(definition);
4365 } finally {
4366 Binder.restoreCallingIdentity(origId);
4367 }
4368 }
4369 }
4370
4371 @Override
4372 public void registerRemoteAnimationForNextActivityStart(String packageName,
4373 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 "registerRemoteAnimationForNextActivityStart");
4376 adapter.setCallingPid(Binder.getCallingPid());
4377 synchronized (mGlobalLock) {
4378 final long origId = Binder.clearCallingIdentity();
4379 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004380 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 packageName, adapter);
4382 } finally {
4383 Binder.restoreCallingIdentity(origId);
4384 }
4385 }
4386 }
4387
4388 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4389 @Override
4390 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4391 synchronized (mGlobalLock) {
4392 final long origId = Binder.clearCallingIdentity();
4393 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004394 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 } finally {
4396 Binder.restoreCallingIdentity(origId);
4397 }
4398 }
4399 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004400
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004401 @Override
4402 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004403 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004404 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004405 final int pid = Binder.getCallingPid();
4406 final WindowProcessController wpc = mPidMap.get(pid);
4407 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004408 }
4409 }
4410
4411 @Override
4412 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004413 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004414 != PERMISSION_GRANTED) {
4415 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4416 + Binder.getCallingPid()
4417 + ", uid=" + Binder.getCallingUid()
4418 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4419 Slog.w(TAG, msg);
4420 throw new SecurityException(msg);
4421 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004423 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004424 final int pid = Binder.getCallingPid();
4425 final WindowProcessController proc = mPidMap.get(pid);
4426 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004427 }
4428 }
4429
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 @Override
4431 public void stopAppSwitches() {
4432 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4433 synchronized (mGlobalLock) {
4434 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4435 mDidAppSwitch = false;
4436 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4437 }
4438 }
4439
4440 @Override
4441 public void resumeAppSwitches() {
4442 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4443 synchronized (mGlobalLock) {
4444 // Note that we don't execute any pending app switches... we will
4445 // let those wait until either the timeout, or the next start
4446 // activity request.
4447 mAppSwitchesAllowedTime = 0;
4448 }
4449 }
4450
4451 void onStartActivitySetDidAppSwitch() {
4452 if (mDidAppSwitch) {
4453 // This is the second allowed switch since we stopped switches, so now just generally
4454 // allow switches. Use case:
4455 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4456 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4457 // anyone to switch again).
4458 mAppSwitchesAllowedTime = 0;
4459 } else {
4460 mDidAppSwitch = true;
4461 }
4462 }
4463
4464 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004465 boolean shouldDisableNonVrUiLocked() {
4466 return mVrController.shouldDisableNonVrUiLocked();
4467 }
4468
Wale Ogunwale53783742018-09-16 10:21:51 -07004469 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004470 // VR apps are expected to run in a main display. If an app is turning on VR for
4471 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4472 // fullscreen stack before enabling VR Mode.
4473 // TODO: The goal of this code is to keep the VR app on the main display. When the
4474 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4475 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4476 // option would be a better choice here.
4477 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4478 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4479 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004480 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004481 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004482 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004483 }
4484 mH.post(() -> {
4485 if (!mVrController.onVrModeChanged(r)) {
4486 return;
4487 }
4488 synchronized (mGlobalLock) {
4489 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4490 mWindowManager.disableNonVrUi(disableNonVrUi);
4491 if (disableNonVrUi) {
4492 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4493 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004494 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004495 }
4496 }
4497 });
4498 }
4499
Wale Ogunwale53783742018-09-16 10:21:51 -07004500 @Override
4501 public int getPackageScreenCompatMode(String packageName) {
4502 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4503 synchronized (mGlobalLock) {
4504 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4505 }
4506 }
4507
4508 @Override
4509 public void setPackageScreenCompatMode(String packageName, int mode) {
4510 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4511 "setPackageScreenCompatMode");
4512 synchronized (mGlobalLock) {
4513 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4514 }
4515 }
4516
4517 @Override
4518 public boolean getPackageAskScreenCompat(String packageName) {
4519 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4520 synchronized (mGlobalLock) {
4521 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4522 }
4523 }
4524
4525 @Override
4526 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4527 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4528 "setPackageAskScreenCompat");
4529 synchronized (mGlobalLock) {
4530 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4531 }
4532 }
4533
Wale Ogunwale64258362018-10-16 15:13:37 -07004534 public static String relaunchReasonToString(int relaunchReason) {
4535 switch (relaunchReason) {
4536 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4537 return "window_resize";
4538 case RELAUNCH_REASON_FREE_RESIZE:
4539 return "free_resize";
4540 default:
4541 return null;
4542 }
4543 }
4544
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004545 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004546 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004547 }
4548
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004549 /** Pokes the task persister. */
4550 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4551 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4552 }
4553
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004554 boolean isKeyguardLocked() {
4555 return mKeyguardController.isKeyguardLocked();
4556 }
4557
Garfield Tan01548632018-11-27 10:15:48 -08004558 /**
4559 * Clears launch params for the given package.
4560 * @param packageNames the names of the packages of which the launch params are to be cleared
4561 */
4562 @Override
4563 public void clearLaunchParamsForPackages(List<String> packageNames) {
4564 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4565 "clearLaunchParamsForPackages");
4566 synchronized (mGlobalLock) {
4567 for (int i = 0; i < packageNames.size(); ++i) {
4568 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4569 }
4570 }
4571 }
4572
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004573 /**
4574 * Makes the display with the given id a single task instance display. I.e the display can only
4575 * contain one task.
4576 */
4577 @Override
4578 public void setDisplayToSingleTaskInstance(int displayId) {
4579 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4580 "setDisplayToSingleTaskInstance");
4581 final long origId = Binder.clearCallingIdentity();
4582 try {
4583 final ActivityDisplay display =
4584 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4585 if (display != null) {
4586 display.setDisplayToSingleTaskInstance();
4587 }
4588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592
Wale Ogunwale31913b52018-10-13 08:29:31 -07004593 void dumpLastANRLocked(PrintWriter pw) {
4594 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4595 if (mLastANRState == null) {
4596 pw.println(" <no ANR has occurred since boot>");
4597 } else {
4598 pw.println(mLastANRState);
4599 }
4600 }
4601
4602 void dumpLastANRTracesLocked(PrintWriter pw) {
4603 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4604
4605 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4606 if (ArrayUtils.isEmpty(files)) {
4607 pw.println(" <no ANR has occurred since boot>");
4608 return;
4609 }
4610 // Find the latest file.
4611 File latest = null;
4612 for (File f : files) {
4613 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4614 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004615 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004616 }
4617 pw.print("File: ");
4618 pw.print(latest.getName());
4619 pw.println();
4620 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4621 String line;
4622 while ((line = in.readLine()) != null) {
4623 pw.println(line);
4624 }
4625 } catch (IOException e) {
4626 pw.print("Unable to read: ");
4627 pw.print(e);
4628 pw.println();
4629 }
4630 }
4631
4632 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4633 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4634 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4635 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4636 }
4637
4638 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4639 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4640 pw.println(header);
4641
Wale Ogunwaled32da472018-11-16 07:19:28 -08004642 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004643 dumpPackage);
4644 boolean needSep = printedAnything;
4645
4646 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004647 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004648 " ResumedActivity: ");
4649 if (printed) {
4650 printedAnything = true;
4651 needSep = false;
4652 }
4653
4654 if (dumpPackage == null) {
4655 if (needSep) {
4656 pw.println();
4657 }
4658 printedAnything = true;
4659 mStackSupervisor.dump(pw, " ");
4660 }
4661
4662 if (!printedAnything) {
4663 pw.println(" (nothing)");
4664 }
4665 }
4666
4667 void dumpActivityContainersLocked(PrintWriter pw) {
4668 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004669 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004670 pw.println(" ");
4671 }
4672
4673 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4674 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4675 getActivityStartController().dump(pw, "", dumpPackage);
4676 }
4677
4678 /**
4679 * There are three things that cmd can be:
4680 * - a flattened component name that matches an existing activity
4681 * - the cmd arg isn't the flattened component name of an existing activity:
4682 * dump all activity whose component contains the cmd as a substring
4683 * - A hex number of the ActivityRecord object instance.
4684 *
4685 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4686 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4687 */
4688 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4689 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4690 ArrayList<ActivityRecord> activities;
4691
4692 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004693 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004694 dumpFocusedStackOnly);
4695 }
4696
4697 if (activities.size() <= 0) {
4698 return false;
4699 }
4700
4701 String[] newArgs = new String[args.length - opti];
4702 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4703
4704 TaskRecord lastTask = null;
4705 boolean needSep = false;
4706 for (int i = activities.size() - 1; i >= 0; i--) {
4707 ActivityRecord r = activities.get(i);
4708 if (needSep) {
4709 pw.println();
4710 }
4711 needSep = true;
4712 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004713 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004714 if (lastTask != task) {
4715 lastTask = task;
4716 pw.print("TASK "); pw.print(lastTask.affinity);
4717 pw.print(" id="); pw.print(lastTask.taskId);
4718 pw.print(" userId="); pw.println(lastTask.userId);
4719 if (dumpAll) {
4720 lastTask.dump(pw, " ");
4721 }
4722 }
4723 }
4724 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4725 }
4726 return true;
4727 }
4728
4729 /**
4730 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4731 * there is a thread associated with the activity.
4732 */
4733 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4734 final ActivityRecord r, String[] args, boolean dumpAll) {
4735 String innerPrefix = prefix + " ";
4736 synchronized (mGlobalLock) {
4737 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4738 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4739 pw.print(" pid=");
4740 if (r.hasProcess()) pw.println(r.app.getPid());
4741 else pw.println("(not running)");
4742 if (dumpAll) {
4743 r.dump(pw, innerPrefix);
4744 }
4745 }
4746 if (r.attachedToProcess()) {
4747 // flush anything that is already in the PrintWriter since the thread is going
4748 // to write to the file descriptor directly
4749 pw.flush();
4750 try {
4751 TransferPipe tp = new TransferPipe();
4752 try {
4753 r.app.getThread().dumpActivity(tp.getWriteFd(),
4754 r.appToken, innerPrefix, args);
4755 tp.go(fd);
4756 } finally {
4757 tp.kill();
4758 }
4759 } catch (IOException e) {
4760 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4761 } catch (RemoteException e) {
4762 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4763 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004764 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004765 }
4766
sanryhuang498e77e2018-12-06 14:57:01 +08004767 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4768 boolean testPssMode) {
4769 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4770 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4771 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004772 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004773 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4774 st.toString());
4775 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004776 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4777 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4778 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004779 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4780 testPssMode);
4781 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 }
4783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 int getCurrentUserId() {
4785 return mAmInternal.getCurrentUserId();
4786 }
4787
4788 private void enforceNotIsolatedCaller(String caller) {
4789 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4790 throw new SecurityException("Isolated process not allowed to call " + caller);
4791 }
4792 }
4793
Wale Ogunwalef6733932018-06-27 05:14:34 -07004794 public Configuration getConfiguration() {
4795 Configuration ci;
4796 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004797 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004798 ci.userSetLocale = false;
4799 }
4800 return ci;
4801 }
4802
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004803 /**
4804 * Current global configuration information. Contains general settings for the entire system,
4805 * also corresponds to the merged configuration of the default display.
4806 */
4807 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004808 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004809 }
4810
4811 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4812 boolean initLocale) {
4813 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4814 }
4815
4816 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4817 boolean initLocale, boolean deferResume) {
4818 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4819 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4820 UserHandle.USER_NULL, deferResume);
4821 }
4822
Wale Ogunwale59507092018-10-29 09:00:30 -07004823 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004824 final long origId = Binder.clearCallingIdentity();
4825 try {
4826 synchronized (mGlobalLock) {
4827 updateConfigurationLocked(values, null, false, true, userId,
4828 false /* deferResume */);
4829 }
4830 } finally {
4831 Binder.restoreCallingIdentity(origId);
4832 }
4833 }
4834
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004835 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4836 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4837 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4838 deferResume, null /* result */);
4839 }
4840
4841 /**
4842 * Do either or both things: (1) change the current configuration, and (2)
4843 * make sure the given activity is running with the (now) current
4844 * configuration. Returns true if the activity has been left running, or
4845 * false if <var>starting</var> is being destroyed to match the new
4846 * configuration.
4847 *
4848 * @param userId is only used when persistent parameter is set to true to persist configuration
4849 * for that particular user
4850 */
4851 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4852 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4853 ActivityTaskManagerService.UpdateConfigurationResult result) {
4854 int changes = 0;
4855 boolean kept = true;
4856
4857 if (mWindowManager != null) {
4858 mWindowManager.deferSurfaceLayout();
4859 }
4860 try {
4861 if (values != null) {
4862 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4863 deferResume);
4864 }
4865
4866 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4867 } finally {
4868 if (mWindowManager != null) {
4869 mWindowManager.continueSurfaceLayout();
4870 }
4871 }
4872
4873 if (result != null) {
4874 result.changes = changes;
4875 result.activityRelaunched = !kept;
4876 }
4877 return kept;
4878 }
4879
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004880 /** Update default (global) configuration and notify listeners about changes. */
4881 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4882 boolean persistent, int userId, boolean deferResume) {
4883 mTempConfig.setTo(getGlobalConfiguration());
4884 final int changes = mTempConfig.updateFrom(values);
4885 if (changes == 0) {
4886 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4887 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4888 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4889 // (even if there are no actual changes) to unfreeze the window.
4890 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4891 return 0;
4892 }
4893
4894 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4895 "Updating global configuration to: " + values);
4896
4897 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4898 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4899 values.colorMode,
4900 values.densityDpi,
4901 values.fontScale,
4902 values.hardKeyboardHidden,
4903 values.keyboard,
4904 values.keyboardHidden,
4905 values.mcc,
4906 values.mnc,
4907 values.navigation,
4908 values.navigationHidden,
4909 values.orientation,
4910 values.screenHeightDp,
4911 values.screenLayout,
4912 values.screenWidthDp,
4913 values.smallestScreenWidthDp,
4914 values.touchscreen,
4915 values.uiMode);
4916
4917
4918 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4919 final LocaleList locales = values.getLocales();
4920 int bestLocaleIndex = 0;
4921 if (locales.size() > 1) {
4922 if (mSupportedSystemLocales == null) {
4923 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4924 }
4925 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4926 }
4927 SystemProperties.set("persist.sys.locale",
4928 locales.get(bestLocaleIndex).toLanguageTag());
4929 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004930
4931 final Message m = PooledLambda.obtainMessage(
4932 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4933 locales.get(bestLocaleIndex));
4934 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004935 }
4936
Yunfan Chen75157d72018-07-27 14:47:21 +09004937 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004938
4939 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004940 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004941
4942 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4943 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004944 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004945
4946 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004947 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004948
4949 AttributeCache ac = AttributeCache.instance();
4950 if (ac != null) {
4951 ac.updateConfiguration(mTempConfig);
4952 }
4953
4954 // Make sure all resources in our process are updated right now, so that anyone who is going
4955 // to retrieve resource values after we return will be sure to get the new ones. This is
4956 // especially important during boot, where the first config change needs to guarantee all
4957 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004958 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004959
4960 // We need another copy of global config because we're scheduling some calls instead of
4961 // running them in place. We need to be sure that object we send will be handled unchanged.
4962 final Configuration configCopy = new Configuration(mTempConfig);
4963 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004964 final Message msg = PooledLambda.obtainMessage(
4965 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4966 this, userId, configCopy);
4967 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004968 }
4969
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004970 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004971 final int pid = mPidMap.keyAt(i);
4972 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004973 if (DEBUG_CONFIGURATION) {
4974 Slog.v(TAG_CONFIGURATION, "Update process config of "
4975 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004976 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004977 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004978 }
4979
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004980 final Message msg = PooledLambda.obtainMessage(
4981 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4982 mAmInternal, changes, initLocale);
4983 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004984
4985 // Override configuration of the default display duplicates global config, so we need to
4986 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004987 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004988 DEFAULT_DISPLAY);
4989
4990 return changes;
4991 }
4992
4993 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4994 boolean deferResume, int displayId) {
4995 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4996 displayId, null /* result */);
4997 }
4998
4999 /**
5000 * Updates override configuration specific for the selected display. If no config is provided,
5001 * new one will be computed in WM based on current display info.
5002 */
5003 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5004 ActivityRecord starting, boolean deferResume, int displayId,
5005 ActivityTaskManagerService.UpdateConfigurationResult result) {
5006 int changes = 0;
5007 boolean kept = true;
5008
5009 if (mWindowManager != null) {
5010 mWindowManager.deferSurfaceLayout();
5011 }
5012 try {
5013 if (values != null) {
5014 if (displayId == DEFAULT_DISPLAY) {
5015 // Override configuration of the default display duplicates global config, so
5016 // we're calling global config update instead for default display. It will also
5017 // apply the correct override config.
5018 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5019 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5020 } else {
5021 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5022 }
5023 }
5024
5025 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5026 } finally {
5027 if (mWindowManager != null) {
5028 mWindowManager.continueSurfaceLayout();
5029 }
5030 }
5031
5032 if (result != null) {
5033 result.changes = changes;
5034 result.activityRelaunched = !kept;
5035 }
5036 return kept;
5037 }
5038
5039 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5040 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005041 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005042 final int changes = mTempConfig.updateFrom(values);
5043 if (changes != 0) {
5044 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5045 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005046 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005047
5048 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5049 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005050 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051
Wale Ogunwale5c918702018-10-18 11:06:33 -07005052 // Post message to start process to avoid possible deadlock of calling into AMS with
5053 // the ATMS lock held.
5054 final Message msg = PooledLambda.obtainMessage(
5055 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5056 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5057 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005058 }
5059 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005060 return changes;
5061 }
5062
Wale Ogunwalef6733932018-06-27 05:14:34 -07005063 private void updateEventDispatchingLocked(boolean booted) {
5064 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5065 }
5066
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005067 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5068 final ContentResolver resolver = mContext.getContentResolver();
5069 Settings.System.putConfigurationForUser(resolver, config, userId);
5070 }
5071
5072 private void sendLocaleToMountDaemonMsg(Locale l) {
5073 try {
5074 IBinder service = ServiceManager.getService("mount");
5075 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5076 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5077 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5078 } catch (RemoteException e) {
5079 Log.e(TAG, "Error storing locale for decryption UI", e);
5080 }
5081 }
5082
Alison Cichowlas3e340502018-08-07 17:15:01 -04005083 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5084 mStartActivitySources.remove(permissionToken);
5085 mExpiredStartAsCallerTokens.add(permissionToken);
5086 }
5087
5088 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5089 mExpiredStartAsCallerTokens.remove(permissionToken);
5090 }
5091
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005092 boolean isActivityStartsLoggingEnabled() {
5093 return mAmInternal.isActivityStartsLoggingEnabled();
5094 }
5095
Michal Karpinski8596ded2018-11-14 14:43:48 +00005096 boolean isBackgroundActivityStartsEnabled() {
5097 return mAmInternal.isBackgroundActivityStartsEnabled();
5098 }
5099
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 void enableScreenAfterBoot(boolean booted) {
5101 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5102 SystemClock.uptimeMillis());
5103 mWindowManager.enableScreenAfterBoot();
5104
5105 synchronized (mGlobalLock) {
5106 updateEventDispatchingLocked(booted);
5107 }
5108 }
5109
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005110 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5111 if (r == null || !r.hasProcess()) {
5112 return KEY_DISPATCHING_TIMEOUT_MS;
5113 }
5114 return getInputDispatchingTimeoutLocked(r.app);
5115 }
5116
5117 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005118 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005119 }
5120
Wale Ogunwalef6733932018-06-27 05:14:34 -07005121 /**
5122 * Decide based on the configuration whether we should show the ANR,
5123 * crash, etc dialogs. The idea is that if there is no affordance to
5124 * press the on-screen buttons, or the user experience would be more
5125 * greatly impacted than the crash itself, we shouldn't show the dialog.
5126 *
5127 * A thought: SystemUI might also want to get told about this, the Power
5128 * dialog / global actions also might want different behaviors.
5129 */
5130 private void updateShouldShowDialogsLocked(Configuration config) {
5131 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5132 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5133 && config.navigation == Configuration.NAVIGATION_NONAV);
5134 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5135 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5136 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5137 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5138 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5139 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5140 HIDE_ERROR_DIALOGS, 0) != 0;
5141 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5142 }
5143
5144 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5145 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5146 FONT_SCALE, 1.0f, userId);
5147
5148 synchronized (this) {
5149 if (getGlobalConfiguration().fontScale == scaleFactor) {
5150 return;
5151 }
5152
5153 final Configuration configuration
5154 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5155 configuration.fontScale = scaleFactor;
5156 updatePersistentConfiguration(configuration, userId);
5157 }
5158 }
5159
5160 // Actually is sleeping or shutting down or whatever else in the future
5161 // is an inactive state.
5162 boolean isSleepingOrShuttingDownLocked() {
5163 return isSleepingLocked() || mShuttingDown;
5164 }
5165
5166 boolean isSleepingLocked() {
5167 return mSleeping;
5168 }
5169
Riddle Hsu16567132018-08-16 21:37:47 +08005170 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005171 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005172 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005173 if (task.isActivityTypeStandard()) {
5174 if (mCurAppTimeTracker != r.appTimeTracker) {
5175 // We are switching app tracking. Complete the current one.
5176 if (mCurAppTimeTracker != null) {
5177 mCurAppTimeTracker.stop();
5178 mH.obtainMessage(
5179 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005180 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005181 mCurAppTimeTracker = null;
5182 }
5183 if (r.appTimeTracker != null) {
5184 mCurAppTimeTracker = r.appTimeTracker;
5185 startTimeTrackingFocusedActivityLocked();
5186 }
5187 } else {
5188 startTimeTrackingFocusedActivityLocked();
5189 }
5190 } else {
5191 r.appTimeTracker = null;
5192 }
5193 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5194 // TODO: Probably not, because we don't want to resume voice on switching
5195 // back to this activity
5196 if (task.voiceInteractor != null) {
5197 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5198 } else {
5199 finishRunningVoiceLocked();
5200
5201 if (mLastResumedActivity != null) {
5202 final IVoiceInteractionSession session;
5203
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005204 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005205 if (lastResumedActivityTask != null
5206 && lastResumedActivityTask.voiceSession != null) {
5207 session = lastResumedActivityTask.voiceSession;
5208 } else {
5209 session = mLastResumedActivity.voiceSession;
5210 }
5211
5212 if (session != null) {
5213 // We had been in a voice interaction session, but now focused has
5214 // move to something different. Just finish the session, we can't
5215 // return to it and retain the proper state and synchronization with
5216 // the voice interaction service.
5217 finishVoiceTask(session);
5218 }
5219 }
5220 }
5221
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005222 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5223 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005224 }
5225 updateResumedAppTrace(r);
5226 mLastResumedActivity = r;
5227
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005228 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005229
5230 applyUpdateLockStateLocked(r);
5231 applyUpdateVrModeLocked(r);
5232
5233 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005234 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005235 r == null ? "NULL" : r.shortComponentName,
5236 reason);
5237 }
5238
5239 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5240 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005241 final ActivityTaskManagerInternal.SleepToken token =
5242 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005243 updateSleepIfNeededLocked();
5244 return token;
5245 }
5246 }
5247
5248 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005249 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005250 final boolean wasSleeping = mSleeping;
5251 boolean updateOomAdj = false;
5252
5253 if (!shouldSleep) {
5254 // If wasSleeping is true, we need to wake up activity manager state from when
5255 // we started sleeping. In either case, we need to apply the sleep tokens, which
5256 // will wake up stacks or put them to sleep as appropriate.
5257 if (wasSleeping) {
5258 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005259 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5260 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005261 startTimeTrackingFocusedActivityLocked();
5262 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5263 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5264 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005265 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005266 if (wasSleeping) {
5267 updateOomAdj = true;
5268 }
5269 } else if (!mSleeping && shouldSleep) {
5270 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005271 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5272 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 if (mCurAppTimeTracker != null) {
5274 mCurAppTimeTracker.stop();
5275 }
5276 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5277 mStackSupervisor.goingToSleepLocked();
5278 updateResumedAppTrace(null /* resumed */);
5279 updateOomAdj = true;
5280 }
5281 if (updateOomAdj) {
5282 mH.post(mAmInternal::updateOomAdj);
5283 }
5284 }
5285
5286 void updateOomAdj() {
5287 mH.post(mAmInternal::updateOomAdj);
5288 }
5289
Wale Ogunwale53783742018-09-16 10:21:51 -07005290 void updateCpuStats() {
5291 mH.post(mAmInternal::updateCpuStats);
5292 }
5293
Hui Yu03d12402018-12-06 18:00:37 -08005294 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5295 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005296 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5297 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005298 mH.sendMessage(m);
5299 }
5300
Hui Yu03d12402018-12-06 18:00:37 -08005301 void updateActivityUsageStats(ActivityRecord activity, int event) {
5302 final Message m = PooledLambda.obtainMessage(
5303 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5304 activity.mActivityComponent, activity.mUserId, event, activity.appToken);
5305 mH.sendMessage(m);
5306 }
5307
Wale Ogunwale53783742018-09-16 10:21:51 -07005308 void setBooting(boolean booting) {
5309 mAmInternal.setBooting(booting);
5310 }
5311
5312 boolean isBooting() {
5313 return mAmInternal.isBooting();
5314 }
5315
5316 void setBooted(boolean booted) {
5317 mAmInternal.setBooted(booted);
5318 }
5319
5320 boolean isBooted() {
5321 return mAmInternal.isBooted();
5322 }
5323
5324 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5325 mH.post(() -> {
5326 if (finishBooting) {
5327 mAmInternal.finishBooting();
5328 }
5329 if (enableScreen) {
5330 mInternal.enableScreenAfterBoot(isBooted());
5331 }
5332 });
5333 }
5334
5335 void setHeavyWeightProcess(ActivityRecord root) {
5336 mHeavyWeightProcess = root.app;
5337 final Message m = PooledLambda.obtainMessage(
5338 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005339 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005340 mH.sendMessage(m);
5341 }
5342
5343 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5344 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5345 return;
5346 }
5347
5348 mHeavyWeightProcess = null;
5349 final Message m = PooledLambda.obtainMessage(
5350 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5351 proc.mUserId);
5352 mH.sendMessage(m);
5353 }
5354
5355 private void cancelHeavyWeightProcessNotification(int userId) {
5356 final INotificationManager inm = NotificationManager.getService();
5357 if (inm == null) {
5358 return;
5359 }
5360 try {
5361 inm.cancelNotificationWithTag("android", null,
5362 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5363 } catch (RuntimeException e) {
5364 Slog.w(TAG, "Error canceling notification for service", e);
5365 } catch (RemoteException e) {
5366 }
5367
5368 }
5369
5370 private void postHeavyWeightProcessNotification(
5371 WindowProcessController proc, Intent intent, int userId) {
5372 if (proc == null) {
5373 return;
5374 }
5375
5376 final INotificationManager inm = NotificationManager.getService();
5377 if (inm == null) {
5378 return;
5379 }
5380
5381 try {
5382 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5383 String text = mContext.getString(R.string.heavy_weight_notification,
5384 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5385 Notification notification =
5386 new Notification.Builder(context,
5387 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5388 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5389 .setWhen(0)
5390 .setOngoing(true)
5391 .setTicker(text)
5392 .setColor(mContext.getColor(
5393 com.android.internal.R.color.system_notification_accent_color))
5394 .setContentTitle(text)
5395 .setContentText(
5396 mContext.getText(R.string.heavy_weight_notification_detail))
5397 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5398 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5399 new UserHandle(userId)))
5400 .build();
5401 try {
5402 inm.enqueueNotificationWithTag("android", "android", null,
5403 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5404 } catch (RuntimeException e) {
5405 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5406 } catch (RemoteException e) {
5407 }
5408 } catch (PackageManager.NameNotFoundException e) {
5409 Slog.w(TAG, "Unable to create context for heavy notification", e);
5410 }
5411
5412 }
5413
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005414 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5415 IBinder token, String resultWho, int requestCode, Intent[] intents,
5416 String[] resolvedTypes, int flags, Bundle bOptions) {
5417
5418 ActivityRecord activity = null;
5419 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5420 activity = ActivityRecord.isInStackLocked(token);
5421 if (activity == null) {
5422 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5423 return null;
5424 }
5425 if (activity.finishing) {
5426 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5427 return null;
5428 }
5429 }
5430
5431 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5432 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5433 bOptions);
5434 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5435 if (noCreate) {
5436 return rec;
5437 }
5438 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5439 if (activity.pendingResults == null) {
5440 activity.pendingResults = new HashSet<>();
5441 }
5442 activity.pendingResults.add(rec.ref);
5443 }
5444 return rec;
5445 }
5446
Andrii Kulian52d255c2018-07-13 11:32:19 -07005447 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005449 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005450 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5451 mCurAppTimeTracker.start(resumedActivity.packageName);
5452 }
5453 }
5454
5455 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5456 if (mTracedResumedActivity != null) {
5457 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5458 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5459 }
5460 if (resumed != null) {
5461 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5462 constructResumedTraceName(resumed.packageName), 0);
5463 }
5464 mTracedResumedActivity = resumed;
5465 }
5466
5467 private String constructResumedTraceName(String packageName) {
5468 return "focused app: " + packageName;
5469 }
5470
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005471 /** Applies latest configuration and/or visibility updates if needed. */
5472 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5473 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005474 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005475 // mainStack is null during startup.
5476 if (mainStack != null) {
5477 if (changes != 0 && starting == null) {
5478 // If the configuration changed, and the caller is not already
5479 // in the process of starting an activity, then find the top
5480 // activity to check if its configuration needs to change.
5481 starting = mainStack.topRunningActivityLocked();
5482 }
5483
5484 if (starting != null) {
5485 kept = starting.ensureActivityConfiguration(changes,
5486 false /* preserveWindow */);
5487 // And we need to make sure at this point that all other activities
5488 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005489 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005490 !PRESERVE_WINDOWS);
5491 }
5492 }
5493
5494 return kept;
5495 }
5496
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005497 void scheduleAppGcsLocked() {
5498 mH.post(() -> mAmInternal.scheduleAppGcs());
5499 }
5500
Wale Ogunwale53783742018-09-16 10:21:51 -07005501 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5502 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5503 }
5504
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005505 /**
5506 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5507 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5508 * on demand.
5509 */
5510 IPackageManager getPackageManager() {
5511 return AppGlobals.getPackageManager();
5512 }
5513
5514 PackageManagerInternal getPackageManagerInternalLocked() {
5515 if (mPmInternal == null) {
5516 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5517 }
5518 return mPmInternal;
5519 }
5520
Wale Ogunwale008163e2018-07-23 23:11:08 -07005521 AppWarnings getAppWarningsLocked() {
5522 return mAppWarnings;
5523 }
5524
Wale Ogunwale214f3482018-10-04 11:00:47 -07005525 Intent getHomeIntent() {
5526 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5527 intent.setComponent(mTopComponent);
5528 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5529 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5530 intent.addCategory(Intent.CATEGORY_HOME);
5531 }
5532 return intent;
5533 }
5534
Chilun2ef71f72018-11-16 17:57:15 +08005535 /**
5536 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5537 * activities.
5538 *
5539 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5540 * component defined in config_secondaryHomeComponent.
5541 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5542 */
5543 Intent getSecondaryHomeIntent(String preferredPackage) {
5544 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5545 if (preferredPackage == null) {
5546 // Using the component stored in config if no package name.
5547 final String secondaryHomeComponent = mContext.getResources().getString(
5548 com.android.internal.R.string.config_secondaryHomeComponent);
5549 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5550 } else {
5551 intent.setPackage(preferredPackage);
5552 }
5553 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5554 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5555 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5556 }
5557 return intent;
5558 }
5559
Wale Ogunwale214f3482018-10-04 11:00:47 -07005560 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5561 if (info == null) return null;
5562 ApplicationInfo newInfo = new ApplicationInfo(info);
5563 newInfo.initForUser(userId);
5564 return newInfo;
5565 }
5566
Wale Ogunwale9c103022018-10-18 07:44:54 -07005567 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005568 if (uid == SYSTEM_UID) {
5569 // The system gets to run in any process. If there are multiple processes with the same
5570 // uid, just pick the first (this should never happen).
5571 final SparseArray<WindowProcessController> procs =
5572 mProcessNames.getMap().get(processName);
5573 if (procs == null) return null;
5574 final int procCount = procs.size();
5575 for (int i = 0; i < procCount; i++) {
5576 final int procUid = procs.keyAt(i);
5577 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5578 // Don't use an app process or different user process for system component.
5579 continue;
5580 }
5581 return procs.valueAt(i);
5582 }
5583 }
5584
5585 return mProcessNames.get(processName, uid);
5586 }
5587
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005588 WindowProcessController getProcessController(IApplicationThread thread) {
5589 if (thread == null) {
5590 return null;
5591 }
5592
5593 final IBinder threadBinder = thread.asBinder();
5594 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5595 for (int i = pmap.size()-1; i >= 0; i--) {
5596 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5597 for (int j = procs.size() - 1; j >= 0; j--) {
5598 final WindowProcessController proc = procs.valueAt(j);
5599 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5600 return proc;
5601 }
5602 }
5603 }
5604
5605 return null;
5606 }
5607
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005608 int getUidStateLocked(int uid) {
5609 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5610 }
5611
Wale Ogunwale9de19442018-10-18 19:05:03 -07005612 /**
5613 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5614 * the whitelist
5615 */
5616 String getPendingTempWhitelistTagForUidLocked(int uid) {
5617 return mPendingTempWhitelist.get(uid);
5618 }
5619
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005620 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5621 if (true || Build.IS_USER) {
5622 return;
5623 }
5624
5625 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5626 StrictMode.allowThreadDiskWrites();
5627 try {
5628 File tracesDir = new File("/data/anr");
5629 File tracesFile = null;
5630 try {
5631 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5632
5633 StringBuilder sb = new StringBuilder();
5634 Time tobj = new Time();
5635 tobj.set(System.currentTimeMillis());
5636 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5637 sb.append(": ");
5638 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5639 sb.append(" since ");
5640 sb.append(msg);
5641 FileOutputStream fos = new FileOutputStream(tracesFile);
5642 fos.write(sb.toString().getBytes());
5643 if (app == null) {
5644 fos.write("\n*** No application process!".getBytes());
5645 }
5646 fos.close();
5647 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5648 } catch (IOException e) {
5649 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5650 return;
5651 }
5652
5653 if (app != null && app.getPid() > 0) {
5654 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5655 firstPids.add(app.getPid());
5656 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5657 }
5658
5659 File lastTracesFile = null;
5660 File curTracesFile = null;
5661 for (int i=9; i>=0; i--) {
5662 String name = String.format(Locale.US, "slow%02d.txt", i);
5663 curTracesFile = new File(tracesDir, name);
5664 if (curTracesFile.exists()) {
5665 if (lastTracesFile != null) {
5666 curTracesFile.renameTo(lastTracesFile);
5667 } else {
5668 curTracesFile.delete();
5669 }
5670 }
5671 lastTracesFile = curTracesFile;
5672 }
5673 tracesFile.renameTo(curTracesFile);
5674 } finally {
5675 StrictMode.setThreadPolicy(oldPolicy);
5676 }
5677 }
5678
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005679 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005680 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005681
5682
Wale Ogunwale98875612018-10-12 07:53:02 -07005683 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5684 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005685
Riddle Hsud93a6c42018-11-29 21:50:06 +08005686 H(Looper looper) {
5687 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005688 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005689
5690 @Override
5691 public void handleMessage(Message msg) {
5692 switch (msg.what) {
5693 case REPORT_TIME_TRACKER_MSG: {
5694 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5695 tracker.deliverResult(mContext);
5696 } break;
5697 }
5698 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005699 }
5700
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005701 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005702 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005703
5704 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005705 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005706 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005707
5708 @Override
5709 public void handleMessage(Message msg) {
5710 switch (msg.what) {
5711 case DISMISS_DIALOG_UI_MSG: {
5712 final Dialog d = (Dialog) msg.obj;
5713 d.dismiss();
5714 break;
5715 }
5716 }
5717 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005718 }
5719
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005720 final class LocalService extends ActivityTaskManagerInternal {
5721 @Override
5722 public SleepToken acquireSleepToken(String tag, int displayId) {
5723 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005724 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005725 }
5726
5727 @Override
5728 public ComponentName getHomeActivityForUser(int userId) {
5729 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005730 final ActivityRecord homeActivity =
5731 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005732 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005733 }
5734 }
5735
5736 @Override
5737 public void onLocalVoiceInteractionStarted(IBinder activity,
5738 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5739 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005740 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005741 }
5742 }
5743
5744 @Override
5745 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5746 synchronized (mGlobalLock) {
5747 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5748 reasons, timestamp);
5749 }
5750 }
5751
5752 @Override
5753 public void notifyAppTransitionFinished() {
5754 synchronized (mGlobalLock) {
5755 mStackSupervisor.notifyAppTransitionDone();
5756 }
5757 }
5758
5759 @Override
5760 public void notifyAppTransitionCancelled() {
5761 synchronized (mGlobalLock) {
5762 mStackSupervisor.notifyAppTransitionDone();
5763 }
5764 }
5765
5766 @Override
5767 public List<IBinder> getTopVisibleActivities() {
5768 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005769 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005770 }
5771 }
5772
5773 @Override
5774 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5775 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005776 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005777 }
5778 }
5779
5780 @Override
5781 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5782 Bundle bOptions) {
5783 Preconditions.checkNotNull(intents, "intents");
5784 final String[] resolvedTypes = new String[intents.length];
5785
5786 // UID of the package on user userId.
5787 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5788 // packageUid may not be initialized.
5789 int packageUid = 0;
5790 final long ident = Binder.clearCallingIdentity();
5791
5792 try {
5793 for (int i = 0; i < intents.length; i++) {
5794 resolvedTypes[i] =
5795 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5796 }
5797
5798 packageUid = AppGlobals.getPackageManager().getPackageUid(
5799 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5800 } catch (RemoteException e) {
5801 // Shouldn't happen.
5802 } finally {
5803 Binder.restoreCallingIdentity(ident);
5804 }
5805
5806 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005807 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005808 packageUid, packageName,
5809 intents, resolvedTypes, null /* resultTo */,
5810 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005811 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005812 }
5813 }
5814
5815 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005816 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5817 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5818 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5819 synchronized (mGlobalLock) {
5820 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5821 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5822 originatingPendingIntent);
5823 }
5824 }
5825
5826 @Override
5827 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5828 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5829 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5830 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5831 PendingIntentRecord originatingPendingIntent) {
5832 synchronized (mGlobalLock) {
5833 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5834 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5835 requestCode, startFlags, options, userId, inTask, reason,
5836 validateIncomingUser, originatingPendingIntent);
5837 }
5838 }
5839
5840 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005841 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5842 Intent intent, Bundle options, int userId) {
5843 return ActivityTaskManagerService.this.startActivityAsUser(
5844 caller, callerPacakge, intent,
5845 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5846 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5847 false /*validateIncomingUser*/);
5848 }
5849
5850 @Override
lumark588a3e82018-07-20 18:53:54 +08005851 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005852 synchronized (mGlobalLock) {
5853
5854 // We might change the visibilities here, so prepare an empty app transition which
5855 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005856 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005857 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005858 if (activityDisplay == null) {
5859 return;
5860 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005861 final DisplayContent dc = activityDisplay.mDisplayContent;
5862 final boolean wasTransitionSet =
5863 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005864 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005865 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005866 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005867 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005868
5869 // If there was a transition set already we don't want to interfere with it as we
5870 // might be starting it too early.
5871 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005872 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005873 }
5874 }
5875 if (callback != null) {
5876 callback.run();
5877 }
5878 }
5879
5880 @Override
5881 public void notifyKeyguardTrustedChanged() {
5882 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005883 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005884 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005885 }
5886 }
5887 }
5888
5889 /**
5890 * Called after virtual display Id is updated by
5891 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5892 * {@param vrVr2dDisplayId}.
5893 */
5894 @Override
5895 public void setVr2dDisplayId(int vr2dDisplayId) {
5896 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5897 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005898 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005899 }
5900 }
5901
5902 @Override
5903 public void setFocusedActivity(IBinder token) {
5904 synchronized (mGlobalLock) {
5905 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5906 if (r == null) {
5907 throw new IllegalArgumentException(
5908 "setFocusedActivity: No activity record matching token=" + token);
5909 }
Louis Chang19443452018-10-09 12:10:21 +08005910 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005911 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005912 }
5913 }
5914 }
5915
5916 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005917 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005918 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005919 }
5920
5921 @Override
5922 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005923 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005924 }
5925
5926 @Override
5927 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005928 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 }
5930
5931 @Override
5932 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5933 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5934 }
5935
5936 @Override
5937 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005938 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005939 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005940
5941 @Override
5942 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5943 synchronized (mGlobalLock) {
5944 mActiveVoiceInteractionServiceComponent = component;
5945 }
5946 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005947
5948 @Override
5949 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5950 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5951 return;
5952 }
5953 synchronized (mGlobalLock) {
5954 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5955 if (types == null) {
5956 if (uid < 0) {
5957 return;
5958 }
5959 types = new ArrayMap<>();
5960 mAllowAppSwitchUids.put(userId, types);
5961 }
5962 if (uid < 0) {
5963 types.remove(type);
5964 } else {
5965 types.put(type, uid);
5966 }
5967 }
5968 }
5969
5970 @Override
5971 public void onUserStopped(int userId) {
5972 synchronized (mGlobalLock) {
5973 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5974 mAllowAppSwitchUids.remove(userId);
5975 }
5976 }
5977
5978 @Override
5979 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5980 synchronized (mGlobalLock) {
5981 return ActivityTaskManagerService.this.isGetTasksAllowed(
5982 caller, callingPid, callingUid);
5983 }
5984 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005985
5986 @Override
5987 public void onProcessAdded(WindowProcessController proc) {
5988 synchronized (mGlobalLock) {
5989 mProcessNames.put(proc.mName, proc.mUid, proc);
5990 }
5991 }
5992
5993 @Override
5994 public void onProcessRemoved(String name, int uid) {
5995 synchronized (mGlobalLock) {
5996 mProcessNames.remove(name, uid);
5997 }
5998 }
5999
6000 @Override
6001 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6002 synchronized (mGlobalLock) {
6003 if (proc == mHomeProcess) {
6004 mHomeProcess = null;
6005 }
6006 if (proc == mPreviousProcess) {
6007 mPreviousProcess = null;
6008 }
6009 }
6010 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006011
6012 @Override
6013 public int getTopProcessState() {
6014 synchronized (mGlobalLock) {
6015 return mTopProcessState;
6016 }
6017 }
6018
6019 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006020 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6021 synchronized (mGlobalLock) {
6022 return proc == mHeavyWeightProcess;
6023 }
6024 }
6025
6026 @Override
6027 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6028 synchronized (mGlobalLock) {
6029 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6030 }
6031 }
6032
6033 @Override
6034 public void finishHeavyWeightApp() {
6035 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006036 if (mHeavyWeightProcess != null) {
6037 mHeavyWeightProcess.finishActivities();
6038 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006039 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6040 mHeavyWeightProcess);
6041 }
6042 }
6043
6044 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006045 public boolean isSleeping() {
6046 synchronized (mGlobalLock) {
6047 return isSleepingLocked();
6048 }
6049 }
6050
6051 @Override
6052 public boolean isShuttingDown() {
6053 synchronized (mGlobalLock) {
6054 return mShuttingDown;
6055 }
6056 }
6057
6058 @Override
6059 public boolean shuttingDown(boolean booted, int timeout) {
6060 synchronized (mGlobalLock) {
6061 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006062 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006063 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006064 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006065 return mStackSupervisor.shutdownLocked(timeout);
6066 }
6067 }
6068
6069 @Override
6070 public void enableScreenAfterBoot(boolean booted) {
6071 synchronized (mGlobalLock) {
6072 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6073 SystemClock.uptimeMillis());
6074 mWindowManager.enableScreenAfterBoot();
6075 updateEventDispatchingLocked(booted);
6076 }
6077 }
6078
6079 @Override
6080 public boolean showStrictModeViolationDialog() {
6081 synchronized (mGlobalLock) {
6082 return mShowDialogs && !mSleeping && !mShuttingDown;
6083 }
6084 }
6085
6086 @Override
6087 public void showSystemReadyErrorDialogsIfNeeded() {
6088 synchronized (mGlobalLock) {
6089 try {
6090 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6091 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6092 + " data partition or your device will be unstable.");
6093 mUiHandler.post(() -> {
6094 if (mShowDialogs) {
6095 AlertDialog d = new BaseErrorDialog(mUiContext);
6096 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6097 d.setCancelable(false);
6098 d.setTitle(mUiContext.getText(R.string.android_system_label));
6099 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6100 d.setButton(DialogInterface.BUTTON_POSITIVE,
6101 mUiContext.getText(R.string.ok),
6102 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6103 d.show();
6104 }
6105 });
6106 }
6107 } catch (RemoteException e) {
6108 }
6109
6110 if (!Build.isBuildConsistent()) {
6111 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6112 mUiHandler.post(() -> {
6113 if (mShowDialogs) {
6114 AlertDialog d = new BaseErrorDialog(mUiContext);
6115 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6116 d.setCancelable(false);
6117 d.setTitle(mUiContext.getText(R.string.android_system_label));
6118 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6119 d.setButton(DialogInterface.BUTTON_POSITIVE,
6120 mUiContext.getText(R.string.ok),
6121 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6122 d.show();
6123 }
6124 });
6125 }
6126 }
6127 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006128
6129 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006130 public void onProcessMapped(int pid, WindowProcessController proc) {
6131 synchronized (mGlobalLock) {
6132 mPidMap.put(pid, proc);
6133 }
6134 }
6135
6136 @Override
6137 public void onProcessUnMapped(int pid) {
6138 synchronized (mGlobalLock) {
6139 mPidMap.remove(pid);
6140 }
6141 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006142
6143 @Override
6144 public void onPackageDataCleared(String name) {
6145 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006146 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006147 mAppWarnings.onPackageDataCleared(name);
6148 }
6149 }
6150
6151 @Override
6152 public void onPackageUninstalled(String name) {
6153 synchronized (mGlobalLock) {
6154 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006155 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006156 }
6157 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006158
6159 @Override
6160 public void onPackageAdded(String name, boolean replacing) {
6161 synchronized (mGlobalLock) {
6162 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6163 }
6164 }
6165
6166 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006167 public void onPackageReplaced(ApplicationInfo aInfo) {
6168 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006169 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006170 }
6171 }
6172
6173 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006174 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6175 synchronized (mGlobalLock) {
6176 return compatibilityInfoForPackageLocked(ai);
6177 }
6178 }
6179
Yunfan Chen75157d72018-07-27 14:47:21 +09006180 /**
6181 * Set the corresponding display information for the process global configuration. To be
6182 * called when we need to show IME on a different display.
6183 *
6184 * @param pid The process id associated with the IME window.
6185 * @param displayId The ID of the display showing the IME.
6186 */
6187 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006188 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006189 if (pid == MY_PID || pid < 0) {
6190 if (DEBUG_CONFIGURATION) {
6191 Slog.w(TAG,
6192 "Trying to update display configuration for system/invalid process.");
6193 }
6194 return;
6195 }
6196 mH.post(() -> {
6197 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006198 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006199 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006200 if (activityDisplay == null) {
6201 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006202 if (DEBUG_CONFIGURATION) {
6203 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006204 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006205 }
6206 return;
6207 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006208 final WindowProcessController process = mPidMap.get(pid);
6209 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006210 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006211 Slog.w(TAG, "Trying to update display configuration for invalid "
6212 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006213 }
6214 return;
6215 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006216 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006217 }
6218 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006219
Yunfan Chen75157d72018-07-27 14:47:21 +09006220 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006221
6222 @Override
6223 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6224 int requestCode, int resultCode, Intent data) {
6225 synchronized (mGlobalLock) {
6226 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006227 if (r != null && r.getActivityStack() != null) {
6228 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6229 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006230 }
6231 }
6232 }
6233
6234 @Override
6235 public void clearPendingResultForActivity(IBinder activityToken,
6236 WeakReference<PendingIntentRecord> pir) {
6237 synchronized (mGlobalLock) {
6238 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6239 if (r != null && r.pendingResults != null) {
6240 r.pendingResults.remove(pir);
6241 }
6242 }
6243 }
6244
6245 @Override
6246 public IIntentSender getIntentSender(int type, String packageName,
6247 int callingUid, int userId, IBinder token, String resultWho,
6248 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6249 Bundle bOptions) {
6250 synchronized (mGlobalLock) {
6251 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6252 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6253 }
6254 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006255
6256 @Override
6257 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6258 synchronized (mGlobalLock) {
6259 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6260 if (r == null) {
6261 return null;
6262 }
6263 if (r.mServiceConnectionsHolder == null) {
6264 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6265 ActivityTaskManagerService.this, r);
6266 }
6267
6268 return r.mServiceConnectionsHolder;
6269 }
6270 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006271
6272 @Override
6273 public Intent getHomeIntent() {
6274 synchronized (mGlobalLock) {
6275 return ActivityTaskManagerService.this.getHomeIntent();
6276 }
6277 }
6278
6279 @Override
6280 public boolean startHomeActivity(int userId, String reason) {
6281 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006282 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006283 }
6284 }
6285
6286 @Override
6287 public boolean startHomeOnAllDisplays(int userId, String reason) {
6288 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006289 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006290 }
6291 }
6292
6293 @Override
6294 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6295 synchronized (mGlobalLock) {
6296 if (mFactoryTest == FACTORY_TEST_OFF) {
6297 return false;
6298 }
6299 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6300 && wpc.mName.equals(mTopComponent.getPackageName())) {
6301 return true;
6302 }
6303 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6304 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6305 }
6306 }
6307
6308 @Override
6309 public void updateTopComponentForFactoryTest() {
6310 synchronized (mGlobalLock) {
6311 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6312 return;
6313 }
6314 final ResolveInfo ri = mContext.getPackageManager()
6315 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6316 final CharSequence errorMsg;
6317 if (ri != null) {
6318 final ActivityInfo ai = ri.activityInfo;
6319 final ApplicationInfo app = ai.applicationInfo;
6320 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6321 mTopAction = Intent.ACTION_FACTORY_TEST;
6322 mTopData = null;
6323 mTopComponent = new ComponentName(app.packageName, ai.name);
6324 errorMsg = null;
6325 } else {
6326 errorMsg = mContext.getResources().getText(
6327 com.android.internal.R.string.factorytest_not_system);
6328 }
6329 } else {
6330 errorMsg = mContext.getResources().getText(
6331 com.android.internal.R.string.factorytest_no_action);
6332 }
6333 if (errorMsg == null) {
6334 return;
6335 }
6336
6337 mTopAction = null;
6338 mTopData = null;
6339 mTopComponent = null;
6340 mUiHandler.post(() -> {
6341 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6342 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006343 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006344 });
6345 }
6346 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006347
6348 @Override
6349 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6350 Runnable finishInstrumentationCallback) {
6351 synchronized (mGlobalLock) {
6352 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006353 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006354
6355 wpc.clearRecentTasks();
6356 wpc.clearActivities();
6357
6358 if (wpc.isInstrumenting()) {
6359 finishInstrumentationCallback.run();
6360 }
6361
Jorim Jaggid0752812018-10-16 16:07:20 +02006362 if (!restarting && hasVisibleActivities) {
6363 mWindowManager.deferSurfaceLayout();
6364 try {
6365 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6366 // If there was nothing to resume, and we are not already restarting
6367 // this process, but there is a visible activity that is hosted by the
6368 // process...then make sure all visible activities are running, taking
6369 // care of restarting this process.
6370 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6371 !PRESERVE_WINDOWS);
6372 }
6373 } finally {
6374 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006375 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006376 }
6377 }
6378 }
6379
6380 @Override
6381 public void closeSystemDialogs(String reason) {
6382 enforceNotIsolatedCaller("closeSystemDialogs");
6383
6384 final int pid = Binder.getCallingPid();
6385 final int uid = Binder.getCallingUid();
6386 final long origId = Binder.clearCallingIdentity();
6387 try {
6388 synchronized (mGlobalLock) {
6389 // Only allow this from foreground processes, so that background
6390 // applications can't abuse it to prevent system UI from being shown.
6391 if (uid >= FIRST_APPLICATION_UID) {
6392 final WindowProcessController proc = mPidMap.get(pid);
6393 if (!proc.isPerceptible()) {
6394 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6395 + " from background process " + proc);
6396 return;
6397 }
6398 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006399 mWindowManager.closeSystemDialogs(reason);
6400
Wale Ogunwaled32da472018-11-16 07:19:28 -08006401 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006402 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006403 // Call into AM outside the synchronized block.
6404 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006405 } finally {
6406 Binder.restoreCallingIdentity(origId);
6407 }
6408 }
6409
6410 @Override
6411 public void cleanupDisabledPackageComponents(
6412 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6413 synchronized (mGlobalLock) {
6414 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006415 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006416 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006417 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006418 mStackSupervisor.scheduleIdleLocked();
6419 }
6420
6421 // Clean-up disabled tasks
6422 getRecentTasks().cleanupDisabledPackageTasksLocked(
6423 packageName, disabledClasses, userId);
6424 }
6425 }
6426
6427 @Override
6428 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6429 int userId) {
6430 synchronized (mGlobalLock) {
6431
6432 boolean didSomething =
6433 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006434 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006435 null, doit, evenPersistent, userId);
6436 return didSomething;
6437 }
6438 }
6439
6440 @Override
6441 public void resumeTopActivities(boolean scheduleIdle) {
6442 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006443 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006444 if (scheduleIdle) {
6445 mStackSupervisor.scheduleIdleLocked();
6446 }
6447 }
6448 }
6449
6450 @Override
6451 public void preBindApplication(WindowProcessController wpc) {
6452 synchronized (mGlobalLock) {
6453 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6454 }
6455 }
6456
6457 @Override
6458 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6459 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006460 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006461 }
6462 }
6463
6464 @Override
6465 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6466 try {
6467 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6468 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6469 }
6470 } catch (RemoteException ex) {
6471 throw new SecurityException("Fail to check is caller a privileged app", ex);
6472 }
6473
6474 synchronized (mGlobalLock) {
6475 final long ident = Binder.clearCallingIdentity();
6476 try {
6477 if (mAmInternal.shouldConfirmCredentials(userId)) {
6478 if (mKeyguardController.isKeyguardLocked()) {
6479 // Showing launcher to avoid user entering credential twice.
6480 startHomeActivity(currentUserId, "notifyLockedProfile");
6481 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006482 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006483 }
6484 } finally {
6485 Binder.restoreCallingIdentity(ident);
6486 }
6487 }
6488 }
6489
6490 @Override
6491 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6492 mAmInternal.enforceCallingPermission(
6493 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6494
6495 synchronized (mGlobalLock) {
6496 final long ident = Binder.clearCallingIdentity();
6497 try {
6498 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6499 FLAG_ACTIVITY_TASK_ON_HOME);
6500 ActivityOptions activityOptions = options != null
6501 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006502 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006503 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006504 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006505 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006506 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006507 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6508 UserHandle.CURRENT);
6509 } finally {
6510 Binder.restoreCallingIdentity(ident);
6511 }
6512 }
6513 }
6514
6515 @Override
6516 public void writeActivitiesToProto(ProtoOutputStream proto) {
6517 synchronized (mGlobalLock) {
6518 // The output proto of "activity --proto activities"
6519 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006520 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006521 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6522 }
6523 }
6524
6525 @Override
6526 public void saveANRState(String reason) {
6527 synchronized (mGlobalLock) {
6528 final StringWriter sw = new StringWriter();
6529 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6530 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6531 if (reason != null) {
6532 pw.println(" Reason: " + reason);
6533 }
6534 pw.println();
6535 getActivityStartController().dump(pw, " ", null);
6536 pw.println();
6537 pw.println("-------------------------------------------------------------------------------");
6538 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6539 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6540 "" /* header */);
6541 pw.println();
6542 pw.close();
6543
6544 mLastANRState = sw.toString();
6545 }
6546 }
6547
6548 @Override
6549 public void clearSavedANRState() {
6550 synchronized (mGlobalLock) {
6551 mLastANRState = null;
6552 }
6553 }
6554
6555 @Override
6556 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6557 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6558 synchronized (mGlobalLock) {
6559 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6560 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6561 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6562 dumpLastANRLocked(pw);
6563 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6564 dumpLastANRTracesLocked(pw);
6565 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6566 dumpActivityStarterLocked(pw, dumpPackage);
6567 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6568 dumpActivityContainersLocked(pw);
6569 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6570 if (getRecentTasks() != null) {
6571 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6572 }
6573 }
6574 }
6575 }
6576
6577 @Override
6578 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6579 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6580 int wakefulness) {
6581 synchronized (mGlobalLock) {
6582 if (mHomeProcess != null && (dumpPackage == null
6583 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6584 if (needSep) {
6585 pw.println();
6586 needSep = false;
6587 }
6588 pw.println(" mHomeProcess: " + mHomeProcess);
6589 }
6590 if (mPreviousProcess != null && (dumpPackage == null
6591 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6592 if (needSep) {
6593 pw.println();
6594 needSep = false;
6595 }
6596 pw.println(" mPreviousProcess: " + mPreviousProcess);
6597 }
6598 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6599 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6600 StringBuilder sb = new StringBuilder(128);
6601 sb.append(" mPreviousProcessVisibleTime: ");
6602 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6603 pw.println(sb);
6604 }
6605 if (mHeavyWeightProcess != null && (dumpPackage == null
6606 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6607 if (needSep) {
6608 pw.println();
6609 needSep = false;
6610 }
6611 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6612 }
6613 if (dumpPackage == null) {
6614 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006615 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006616 }
6617 if (dumpAll) {
6618 if (dumpPackage == null) {
6619 pw.println(" mConfigWillChange: "
6620 + getTopDisplayFocusedStack().mConfigWillChange);
6621 }
6622 if (mCompatModePackages.getPackages().size() > 0) {
6623 boolean printed = false;
6624 for (Map.Entry<String, Integer> entry
6625 : mCompatModePackages.getPackages().entrySet()) {
6626 String pkg = entry.getKey();
6627 int mode = entry.getValue();
6628 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6629 continue;
6630 }
6631 if (!printed) {
6632 pw.println(" mScreenCompatPackages:");
6633 printed = true;
6634 }
6635 pw.println(" " + pkg + ": " + mode);
6636 }
6637 }
6638 }
6639
6640 if (dumpPackage == null) {
6641 pw.println(" mWakefulness="
6642 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006643 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006644 if (mRunningVoice != null) {
6645 pw.println(" mRunningVoice=" + mRunningVoice);
6646 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6647 }
6648 pw.println(" mSleeping=" + mSleeping);
6649 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6650 pw.println(" mVrController=" + mVrController);
6651 }
6652 if (mCurAppTimeTracker != null) {
6653 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6654 }
6655 if (mAllowAppSwitchUids.size() > 0) {
6656 boolean printed = false;
6657 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6658 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6659 for (int j = 0; j < types.size(); j++) {
6660 if (dumpPackage == null ||
6661 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6662 if (needSep) {
6663 pw.println();
6664 needSep = false;
6665 }
6666 if (!printed) {
6667 pw.println(" mAllowAppSwitchUids:");
6668 printed = true;
6669 }
6670 pw.print(" User ");
6671 pw.print(mAllowAppSwitchUids.keyAt(i));
6672 pw.print(": Type ");
6673 pw.print(types.keyAt(j));
6674 pw.print(" = ");
6675 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6676 pw.println();
6677 }
6678 }
6679 }
6680 }
6681 if (dumpPackage == null) {
6682 if (mController != null) {
6683 pw.println(" mController=" + mController
6684 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6685 }
6686 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6687 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6688 }
6689
6690 return needSep;
6691 }
6692 }
6693
6694 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006695 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6696 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006697 synchronized (mGlobalLock) {
6698 if (dumpPackage == null) {
6699 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6700 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006701 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6702 if (mRunningVoice != null) {
6703 final long vrToken = proto.start(
6704 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6705 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6706 mRunningVoice.toString());
6707 mVoiceWakeLock.writeToProto(
6708 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6709 proto.end(vrToken);
6710 }
6711 mVrController.writeToProto(proto,
6712 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 if (mController != null) {
6714 final long token = proto.start(CONTROLLER);
6715 proto.write(CONTROLLER, mController.toString());
6716 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6717 proto.end(token);
6718 }
6719 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6720 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6721 }
6722
6723 if (mHomeProcess != null && (dumpPackage == null
6724 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006725 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006726 }
6727
6728 if (mPreviousProcess != null && (dumpPackage == null
6729 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006730 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6732 }
6733
6734 if (mHeavyWeightProcess != null && (dumpPackage == null
6735 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006736 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 }
6738
6739 for (Map.Entry<String, Integer> entry
6740 : mCompatModePackages.getPackages().entrySet()) {
6741 String pkg = entry.getKey();
6742 int mode = entry.getValue();
6743 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6744 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6745 proto.write(PACKAGE, pkg);
6746 proto.write(MODE, mode);
6747 proto.end(compatToken);
6748 }
6749 }
6750
6751 if (mCurAppTimeTracker != null) {
6752 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6753 }
6754
6755 }
6756 }
6757
6758 @Override
6759 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6760 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6761 boolean dumpFocusedStackOnly) {
6762 synchronized (mGlobalLock) {
6763 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6764 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6765 }
6766 }
6767
6768 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006769 public void dumpForOom(PrintWriter pw) {
6770 synchronized (mGlobalLock) {
6771 pw.println(" mHomeProcess: " + mHomeProcess);
6772 pw.println(" mPreviousProcess: " + mPreviousProcess);
6773 if (mHeavyWeightProcess != null) {
6774 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6775 }
6776 }
6777 }
6778
6779 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006780 public boolean canGcNow() {
6781 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006782 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 }
6784 }
6785
6786 @Override
6787 public WindowProcessController getTopApp() {
6788 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006789 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 return top != null ? top.app : null;
6791 }
6792 }
6793
6794 @Override
6795 public void rankTaskLayersIfNeeded() {
6796 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006797 if (mRootActivityContainer != null) {
6798 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 }
6800 }
6801 }
6802
6803 @Override
6804 public void scheduleDestroyAllActivities(String reason) {
6805 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006806 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 }
6808 }
6809
6810 @Override
6811 public void removeUser(int userId) {
6812 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006813 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 }
6815 }
6816
6817 @Override
6818 public boolean switchUser(int userId, UserState userState) {
6819 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006820 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 }
6822 }
6823
6824 @Override
6825 public void onHandleAppCrash(WindowProcessController wpc) {
6826 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006827 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006828 }
6829 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006830
6831 @Override
6832 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6833 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006834 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006835 }
6836 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006837
6838 @Override
6839 public void onUidActive(int uid, int procState) {
6840 synchronized (mGlobalLock) {
6841 mActiveUids.put(uid, procState);
6842 }
6843 }
6844
6845 @Override
6846 public void onUidInactive(int uid) {
6847 synchronized (mGlobalLock) {
6848 mActiveUids.remove(uid);
6849 }
6850 }
6851
6852 @Override
6853 public void onActiveUidsCleared() {
6854 synchronized (mGlobalLock) {
6855 mActiveUids.clear();
6856 }
6857 }
6858
6859 @Override
6860 public void onUidProcStateChanged(int uid, int procState) {
6861 synchronized (mGlobalLock) {
6862 if (mActiveUids.get(uid) != null) {
6863 mActiveUids.put(uid, procState);
6864 }
6865 }
6866 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006867
6868 @Override
6869 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6870 synchronized (mGlobalLock) {
6871 mPendingTempWhitelist.put(uid, tag);
6872 }
6873 }
6874
6875 @Override
6876 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6877 synchronized (mGlobalLock) {
6878 mPendingTempWhitelist.remove(uid);
6879 }
6880 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006881
6882 @Override
6883 public boolean handleAppCrashInActivityController(String processName, int pid,
6884 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6885 Runnable killCrashingAppCallback) {
6886 synchronized (mGlobalLock) {
6887 if (mController == null) {
6888 return false;
6889 }
6890
6891 try {
6892 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6893 stackTrace)) {
6894 killCrashingAppCallback.run();
6895 return true;
6896 }
6897 } catch (RemoteException e) {
6898 mController = null;
6899 Watchdog.getInstance().setActivityController(null);
6900 }
6901 return false;
6902 }
6903 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006904
6905 @Override
6906 public void removeRecentTasksByPackageName(String packageName, int userId) {
6907 synchronized (mGlobalLock) {
6908 mRecentTasks.removeTasksByPackageName(packageName, userId);
6909 }
6910 }
6911
6912 @Override
6913 public void cleanupRecentTasksForUser(int userId) {
6914 synchronized (mGlobalLock) {
6915 mRecentTasks.cleanupLocked(userId);
6916 }
6917 }
6918
6919 @Override
6920 public void loadRecentTasksForUser(int userId) {
6921 synchronized (mGlobalLock) {
6922 mRecentTasks.loadUserRecentsLocked(userId);
6923 }
6924 }
6925
6926 @Override
6927 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6928 synchronized (mGlobalLock) {
6929 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6930 }
6931 }
6932
6933 @Override
6934 public void flushRecentTasks() {
6935 mRecentTasks.flush();
6936 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006937
6938 @Override
6939 public WindowProcessController getHomeProcess() {
6940 synchronized (mGlobalLock) {
6941 return mHomeProcess;
6942 }
6943 }
6944
6945 @Override
6946 public WindowProcessController getPreviousProcess() {
6947 synchronized (mGlobalLock) {
6948 return mPreviousProcess;
6949 }
6950 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006951
6952 @Override
6953 public void clearLockedTasks(String reason) {
6954 synchronized (mGlobalLock) {
6955 getLockTaskController().clearLockedTasks(reason);
6956 }
6957 }
6958
6959 @Override
6960 public void updateUserConfiguration() {
6961 synchronized (mGlobalLock) {
6962 final Configuration configuration = new Configuration(getGlobalConfiguration());
6963 final int currentUserId = mAmInternal.getCurrentUserId();
6964 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6965 configuration, currentUserId, Settings.System.canWrite(mContext));
6966 updateConfigurationLocked(configuration, null /* starting */,
6967 false /* initLocale */, false /* persistent */, currentUserId,
6968 false /* deferResume */);
6969 }
6970 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006971
6972 @Override
6973 public boolean canShowErrorDialogs() {
6974 synchronized (mGlobalLock) {
6975 return mShowDialogs && !mSleeping && !mShuttingDown
6976 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6977 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6978 mAmInternal.getCurrentUserId())
6979 && !(UserManager.isDeviceInDemoMode(mContext)
6980 && mAmInternal.getCurrentUser().isDemo());
6981 }
6982 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006983
6984 @Override
6985 public void setProfileApp(String profileApp) {
6986 synchronized (mGlobalLock) {
6987 mProfileApp = profileApp;
6988 }
6989 }
6990
6991 @Override
6992 public void setProfileProc(WindowProcessController wpc) {
6993 synchronized (mGlobalLock) {
6994 mProfileProc = wpc;
6995 }
6996 }
6997
6998 @Override
6999 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7000 synchronized (mGlobalLock) {
7001 mProfilerInfo = profilerInfo;
7002 }
7003 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007004
7005 @Override
7006 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7007 synchronized (mGlobalLock) {
7008 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7009 }
7010 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007011 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007012}