blob: 37db6711fac010c592d66192a5ec4f14da7f93c4 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Wale Ogunwale59507092018-10-29 09:00:30 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
86 .PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
89 .MODE;
90import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
91 .PACKAGE;
92import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
93import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070094import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
95import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
96import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
116import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
117import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800119import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
120import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700121import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
122import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800123import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
124import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800125import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
126import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
127import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.annotation.Nullable;
132import android.annotation.UserIdInt;
133import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700134import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700135import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.ActivityOptions;
137import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700138import android.app.ActivityThread;
139import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700141import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700142import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700143import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.IApplicationThread;
145import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800193import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700248import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700277import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700279import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700280import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400282import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700285import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Map;
287import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288
289/**
290 * System service for managing activities and their containers (task, stacks, displays,... ).
291 *
292 * {@hide}
293 */
294public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700295 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700297 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
298 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
299 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
300 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
301 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700302 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700307 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 /** Used to indicate that an app transition should be animated. */
310 static final boolean ANIMATE = true;
311
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700312 /** Hardware-reported OpenGLES version. */
313 final int GL_ES_VERSION;
314
Wale Ogunwale31913b52018-10-13 08:29:31 -0700315 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
316 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
317 public static final String DUMP_LASTANR_CMD = "lastanr" ;
318 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
319 public static final String DUMP_STARTER_CMD = "starter" ;
320 public static final String DUMP_CONTAINERS_CMD = "containers" ;
321 public static final String DUMP_RECENTS_CMD = "recents" ;
322 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
323
Wale Ogunwale64258362018-10-16 15:13:37 -0700324 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
325 public static final int RELAUNCH_REASON_NONE = 0;
326 /** This activity is being relaunched due to windowing mode change. */
327 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
328 /** This activity is being relaunched due to a free-resize operation. */
329 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
330
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700331 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700332
Wale Ogunwalef6733932018-06-27 05:14:34 -0700333 /**
334 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
335 * change at runtime. Use mContext for non-UI purposes.
336 */
337 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700338 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700339 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700342 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700343 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800344 @VisibleForTesting
345 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 PowerManagerInternal mPowerManagerInternal;
347 private UsageStatsManagerInternal mUsageStatsInternal;
348
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700349 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 IntentFirewall mIntentFirewall;
351
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700352 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800353 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700354 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800355 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700356 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700357 private UserManagerService mUserManager;
358 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700359 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700360 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
361 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700362 /** All processes currently running that might have a window organized by name. */
363 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700364 /** All processes we currently have running mapped by pid */
365 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700366 /** This is the process holding what we currently consider to be the "home" activity. */
367 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700368 /** The currently running heavy-weight process, if any. */
369 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700370 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700371 /**
372 * This is the process holding the activity the user last visited that is in a different process
373 * from the one they are currently in.
374 */
375 WindowProcessController mPreviousProcess;
376 /** The time at which the previous process was last visible. */
377 long mPreviousProcessVisibleTime;
378
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700379 /** List of intents that were used to start the most recent tasks. */
380 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700381 /** State of external calls telling us if the device is awake or asleep. */
382 private boolean mKeyguardShown = false;
383
384 // Wrapper around VoiceInteractionServiceManager
385 private AssistUtils mAssistUtils;
386
387 // VoiceInteraction session ID that changes for each new request except when
388 // being called for multi-window assist in a single session.
389 private int mViSessionId = 1000;
390
391 // How long to wait in getAssistContextExtras for the activity and foreground services
392 // to respond with the result.
393 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
394
395 // How long top wait when going through the modern assist (which doesn't need to block
396 // on getting this result before starting to launch its UI).
397 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
398
399 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
400 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
401
Alison Cichowlas3e340502018-08-07 17:15:01 -0400402 // Permission tokens are used to temporarily granted a trusted app the ability to call
403 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
404 // showing any appropriate error messages to the user.
405 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
406 10 * MINUTE_IN_MILLIS;
407
408 // How long before the service actually expires a token. This is slightly longer than
409 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
410 // expiration exception.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
412 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
413
414 // How long the service will remember expired tokens, for the purpose of providing error
415 // messaging when a client uses an expired token.
416 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
417 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
418
419 // Activity tokens of system activities that are delegating their call to
420 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
421 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
422
423 // Permission tokens that have expired, but we remember for error reporting.
424 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700426 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
427
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700428 // Keeps track of the active voice interaction service component, notified from
429 // VoiceInteractionManagerService
430 ComponentName mActiveVoiceInteractionServiceComponent;
431
Wale Ogunwalee2172292018-10-25 10:11:10 -0700432 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700433 KeyguardController mKeyguardController;
434 private final ClientLifecycleManager mLifecycleManager;
435 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700436 /** The controller for all operations related to locktask. */
437 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700438 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700440 boolean mSuppressResizeConfigChanges;
441
442 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
443 new UpdateConfigurationResult();
444
445 static final class UpdateConfigurationResult {
446 // Configuration changes that were updated.
447 int changes;
448 // If the activity was relaunched to match the new configuration.
449 boolean activityRelaunched;
450
451 void reset() {
452 changes = 0;
453 activityRelaunched = false;
454 }
455 }
456
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700457 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700458 private int mConfigurationSeq;
459 // To cache the list of supported system locales
460 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700461
462 /**
463 * Temp object used when global and/or display override configuration is updated. It is also
464 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
465 * anyone...
466 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700467 private Configuration mTempConfig = new Configuration();
468
Wale Ogunwalef6733932018-06-27 05:14:34 -0700469 /** Temporary to avoid allocations. */
470 final StringBuilder mStringBuilder = new StringBuilder(256);
471
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700472 // Amount of time after a call to stopAppSwitches() during which we will
473 // prevent further untrusted switches from happening.
474 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
475
476 /**
477 * The time at which we will allow normal application switches again,
478 * after a call to {@link #stopAppSwitches()}.
479 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700480 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 /**
482 * This is set to true after the first switch after mAppSwitchesAllowedTime
483 * is set; any switches after that will clear the time.
484 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700485 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486
487 IActivityController mController = null;
488 boolean mControllerIsAMonkey = false;
489
Wale Ogunwale214f3482018-10-04 11:00:47 -0700490 final int mFactoryTest;
491
492 /** Used to control how we initialize the service. */
493 ComponentName mTopComponent;
494 String mTopAction = Intent.ACTION_MAIN;
495 String mTopData;
496
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800497 /** Profiling app information. */
498 String mProfileApp = null;
499 WindowProcessController mProfileProc = null;
500 ProfilerInfo mProfilerInfo = null;
501
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700503 * Dump of the activity state at the time of the last ANR. Cleared after
504 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
505 */
506 String mLastANRState;
507
508 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509 * Used to retain an update lock when the foreground activity is in
510 * immersive mode.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
514 /**
515 * Packages that are being allowed to perform unrestricted app switches. Mapping is
516 * User -> Type -> uid.
517 */
518 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
519
520 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700521 private int mThumbnailWidth;
522 private int mThumbnailHeight;
523 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700524
525 /**
526 * Flag that indicates if multi-window is enabled.
527 *
528 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
529 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
530 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
531 * At least one of the forms of multi-window must be enabled in order for this flag to be
532 * initialized to 'true'.
533 *
534 * @see #mSupportsSplitScreenMultiWindow
535 * @see #mSupportsFreeformWindowManagement
536 * @see #mSupportsPictureInPicture
537 * @see #mSupportsMultiDisplay
538 */
539 boolean mSupportsMultiWindow;
540 boolean mSupportsSplitScreenMultiWindow;
541 boolean mSupportsFreeformWindowManagement;
542 boolean mSupportsPictureInPicture;
543 boolean mSupportsMultiDisplay;
544 boolean mForceResizableActivities;
545
546 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
547
548 // VR Vr2d Display Id.
549 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700550
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 /**
552 * Set while we are wanting to sleep, to prevent any
553 * activities from being started/resumed.
554 *
555 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
556 *
557 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
558 * while in the sleep state until there is a pending transition out of sleep, in which case
559 * mSleeping is set to false, and remains false while awake.
560 *
561 * Whether mSleeping can quickly toggled between true/false without the device actually
562 * display changing states is undefined.
563 */
564 private boolean mSleeping = false;
565
566 /**
567 * The process state used for processes that are running the top activities.
568 * This changes between TOP and TOP_SLEEPING to following mSleeping.
569 */
570 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
571
572 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
573 // automatically. Important for devices without direct input devices.
574 private boolean mShowDialogs = true;
575
576 /** Set if we are shutting down the system, similar to sleeping. */
577 boolean mShuttingDown = false;
578
579 /**
580 * We want to hold a wake lock while running a voice interaction session, since
581 * this may happen with the screen off and we need to keep the CPU running to
582 * be able to continue to interact with the user.
583 */
584 PowerManager.WakeLock mVoiceWakeLock;
585
586 /**
587 * Set while we are running a voice interaction. This overrides sleeping while it is active.
588 */
589 IVoiceInteractionSession mRunningVoice;
590
591 /**
592 * The last resumed activity. This is identical to the current resumed activity most
593 * of the time but could be different when we're pausing one activity before we resume
594 * another activity.
595 */
596 ActivityRecord mLastResumedActivity;
597
598 /**
599 * The activity that is currently being traced as the active resumed activity.
600 *
601 * @see #updateResumedAppTrace
602 */
603 private @Nullable ActivityRecord mTracedResumedActivity;
604
605 /** If non-null, we are tracking the time the user spends in the currently focused app. */
606 AppTimeTracker mCurAppTimeTracker;
607
Wale Ogunwale008163e2018-07-23 23:11:08 -0700608 private AppWarnings mAppWarnings;
609
Wale Ogunwale53783742018-09-16 10:21:51 -0700610 /**
611 * Packages that the user has asked to have run in screen size
612 * compatibility mode instead of filling the screen.
613 */
614 CompatModePackages mCompatModePackages;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 private FontScaleSettingObserver mFontScaleSettingObserver;
617
618 private final class FontScaleSettingObserver extends ContentObserver {
619 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
620 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
621
622 public FontScaleSettingObserver() {
623 super(mH);
624 final ContentResolver resolver = mContext.getContentResolver();
625 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
626 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
627 UserHandle.USER_ALL);
628 }
629
630 @Override
631 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
632 if (mFontScaleUri.equals(uri)) {
633 updateFontScaleIfNeeded(userId);
634 } else if (mHideErrorDialogsUri.equals(uri)) {
635 synchronized (mGlobalLock) {
636 updateShouldShowDialogsLocked(getGlobalConfiguration());
637 }
638 }
639 }
640 }
641
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700642 ActivityTaskManagerService(Context context) {
643 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700644 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700645 mSystemThread = ActivityThread.currentActivityThread();
646 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700647 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800648 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700649 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700650 }
651
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700652 public void onSystemReady() {
653 synchronized (mGlobalLock) {
654 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
655 PackageManager.FEATURE_CANT_SAVE_STATE);
656 mAssistUtils = new AssistUtils(mContext);
657 mVrController.onSystemReady();
658 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700659 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700660 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700661 }
662
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700663 public void onInitPowerManagement() {
664 synchronized (mGlobalLock) {
665 mStackSupervisor.initPowerManagement();
666 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
667 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
668 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
669 mVoiceWakeLock.setReferenceCounted(false);
670 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 }
672
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700673 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700674 mFontScaleSettingObserver = new FontScaleSettingObserver();
675 }
676
Wale Ogunwale59507092018-10-29 09:00:30 -0700677 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700678 final boolean freeformWindowManagement =
679 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
680 || Settings.Global.getInt(
681 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
682
683 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
684 final boolean supportsPictureInPicture = supportsMultiWindow &&
685 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
686 final boolean supportsSplitScreenMultiWindow =
687 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
688 final boolean supportsMultiDisplay = mContext.getPackageManager()
689 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700690 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
691 final boolean forceResizable = Settings.Global.getInt(
692 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700693 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700694
695 // Transfer any global setting for forcing RTL layout, into a System Property
696 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
697
698 final Configuration configuration = new Configuration();
699 Settings.System.getConfiguration(resolver, configuration);
700 if (forceRtl) {
701 // This will take care of setting the correct layout direction flags
702 configuration.setLayoutDirection(configuration.locale);
703 }
704
705 synchronized (mGlobalLock) {
706 mForceResizableActivities = forceResizable;
707 final boolean multiWindowFormEnabled = freeformWindowManagement
708 || supportsSplitScreenMultiWindow
709 || supportsPictureInPicture
710 || supportsMultiDisplay;
711 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
712 mSupportsMultiWindow = true;
713 mSupportsFreeformWindowManagement = freeformWindowManagement;
714 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
715 mSupportsPictureInPicture = supportsPictureInPicture;
716 mSupportsMultiDisplay = supportsMultiDisplay;
717 } else {
718 mSupportsMultiWindow = false;
719 mSupportsFreeformWindowManagement = false;
720 mSupportsSplitScreenMultiWindow = false;
721 mSupportsPictureInPicture = false;
722 mSupportsMultiDisplay = false;
723 }
724 mWindowManager.setForceResizableTasks(mForceResizableActivities);
725 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700726 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
727 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728 // This happens before any activities are started, so we can change global configuration
729 // in-place.
730 updateConfigurationLocked(configuration, null, true);
731 final Configuration globalConfig = getGlobalConfiguration();
732 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
733
734 // Load resources only after the current configuration has been set.
735 final Resources res = mContext.getResources();
736 mThumbnailWidth = res.getDimensionPixelSize(
737 com.android.internal.R.dimen.thumbnail_width);
738 mThumbnailHeight = res.getDimensionPixelSize(
739 com.android.internal.R.dimen.thumbnail_height);
740
741 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
742 mFullscreenThumbnailScale = (float) res
743 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
744 (float) globalConfig.screenWidthDp;
745 } else {
746 mFullscreenThumbnailScale = res.getFraction(
747 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
748 }
749 }
750 }
751
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800752 public WindowManagerGlobalLock getGlobalLock() {
753 return mGlobalLock;
754 }
755
Riddle Hsud93a6c42018-11-29 21:50:06 +0800756 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
757 Looper looper) {
758 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700759 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700760 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700761 final File systemDir = SystemServiceManager.ensureSystemDir();
762 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
763 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700764 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700765
766 mTempConfig.setToDefaults();
767 mTempConfig.setLocales(LocaleList.getDefault());
768 mConfigurationSeq = mTempConfig.seq = 1;
769 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800770 mRootActivityContainer = new RootActivityContainer(this);
771 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700772
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700773 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700775 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700776 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700777 mRecentTasks = createRecentTasks();
778 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700780 mKeyguardController = mStackSupervisor.getKeyguardController();
781 }
782
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700783 public void onActivityManagerInternalAdded() {
784 synchronized (mGlobalLock) {
785 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
786 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
787 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700788 }
789
Yunfan Chen75157d72018-07-27 14:47:21 +0900790 int increaseConfigurationSeqLocked() {
791 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
792 return mConfigurationSeq;
793 }
794
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700795 protected ActivityStackSupervisor createStackSupervisor() {
796 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
797 supervisor.initialize();
798 return supervisor;
799 }
800
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700801 public void setWindowManager(WindowManagerService wm) {
802 synchronized (mGlobalLock) {
803 mWindowManager = wm;
804 mLockTaskController.setWindowManager(wm);
805 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800806 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700807 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
811 synchronized (mGlobalLock) {
812 mUsageStatsInternal = usageStatsManager;
813 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700814 }
815
Wale Ogunwalef6733932018-06-27 05:14:34 -0700816 UserManagerService getUserManager() {
817 if (mUserManager == null) {
818 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
819 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
820 }
821 return mUserManager;
822 }
823
824 AppOpsService getAppOpsService() {
825 if (mAppOpsService == null) {
826 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
827 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
828 }
829 return mAppOpsService;
830 }
831
832 boolean hasUserRestriction(String restriction, int userId) {
833 return getUserManager().hasUserRestriction(restriction, userId);
834 }
835
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700836 protected RecentTasks createRecentTasks() {
837 return new RecentTasks(this, mStackSupervisor);
838 }
839
840 RecentTasks getRecentTasks() {
841 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700842 }
843
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700844 ClientLifecycleManager getLifecycleManager() {
845 return mLifecycleManager;
846 }
847
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700848 ActivityStartController getActivityStartController() {
849 return mActivityStartController;
850 }
851
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700852 TaskChangeNotificationController getTaskChangeNotificationController() {
853 return mTaskChangeNotificationController;
854 }
855
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700856 LockTaskController getLockTaskController() {
857 return mLockTaskController;
858 }
859
Yunfan Chen75157d72018-07-27 14:47:21 +0900860 /**
861 * Return the global configuration used by the process corresponding to the input pid. This is
862 * usually the global configuration with some overrides specific to that process.
863 */
864 Configuration getGlobalConfigurationForCallingPid() {
865 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800866 return getGlobalConfigurationForPid(pid);
867 }
868
869 /**
870 * Return the global configuration used by the process corresponding to the given pid.
871 */
872 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900873 if (pid == MY_PID || pid < 0) {
874 return getGlobalConfiguration();
875 }
876 synchronized (mGlobalLock) {
877 final WindowProcessController app = mPidMap.get(pid);
878 return app != null ? app.getConfiguration() : getGlobalConfiguration();
879 }
880 }
881
882 /**
883 * Return the device configuration info used by the process corresponding to the input pid.
884 * The value is consistent with the global configuration for the process.
885 */
886 @Override
887 public ConfigurationInfo getDeviceConfigurationInfo() {
888 ConfigurationInfo config = new ConfigurationInfo();
889 synchronized (mGlobalLock) {
890 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
891 config.reqTouchScreen = globalConfig.touchscreen;
892 config.reqKeyboardType = globalConfig.keyboard;
893 config.reqNavigation = globalConfig.navigation;
894 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
895 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
896 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
897 }
898 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
899 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
900 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
901 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700902 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900903 }
904 return config;
905 }
906
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700907 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700908 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700909 }
910
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700911 public static final class Lifecycle extends SystemService {
912 private final ActivityTaskManagerService mService;
913
914 public Lifecycle(Context context) {
915 super(context);
916 mService = new ActivityTaskManagerService(context);
917 }
918
919 @Override
920 public void onStart() {
921 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700922 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700923 }
924
Garfield Tan891146c2018-10-09 12:14:00 -0700925 @Override
926 public void onUnlockUser(int userId) {
927 synchronized (mService.getGlobalLock()) {
928 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
929 }
930 }
931
932 @Override
933 public void onCleanupUser(int userId) {
934 synchronized (mService.getGlobalLock()) {
935 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
936 }
937 }
938
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700939 public ActivityTaskManagerService getService() {
940 return mService;
941 }
942 }
943
944 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700945 public final int startActivity(IApplicationThread caller, String callingPackage,
946 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
947 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
948 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
949 resultWho, requestCode, startFlags, profilerInfo, bOptions,
950 UserHandle.getCallingUserId());
951 }
952
953 @Override
954 public final int startActivities(IApplicationThread caller, String callingPackage,
955 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
956 int userId) {
957 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700958 enforceNotIsolatedCaller(reason);
959 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700960 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700961 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100962 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
963 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700964 }
965
966 @Override
967 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
968 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
969 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
970 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
971 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
972 true /*validateIncomingUser*/);
973 }
974
975 int startActivityAsUser(IApplicationThread caller, String callingPackage,
976 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
977 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
978 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700979 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700981 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700982 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
983
984 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700985 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 .setCaller(caller)
987 .setCallingPackage(callingPackage)
988 .setResolvedType(resolvedType)
989 .setResultTo(resultTo)
990 .setResultWho(resultWho)
991 .setRequestCode(requestCode)
992 .setStartFlags(startFlags)
993 .setProfilerInfo(profilerInfo)
994 .setActivityOptions(bOptions)
995 .setMayWait(userId)
996 .execute();
997
998 }
999
1000 @Override
1001 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1002 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001003 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1004 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001005 // Refuse possible leaked file descriptors
1006 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1007 throw new IllegalArgumentException("File descriptors passed in Intent");
1008 }
1009
1010 if (!(target instanceof PendingIntentRecord)) {
1011 throw new IllegalArgumentException("Bad PendingIntent object");
1012 }
1013
1014 PendingIntentRecord pir = (PendingIntentRecord)target;
1015
1016 synchronized (mGlobalLock) {
1017 // If this is coming from the currently resumed activity, it is
1018 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001019 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 if (stack.mResumedActivity != null &&
1021 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001022 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 }
1024 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001025 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1031 Bundle bOptions) {
1032 // Refuse possible leaked file descriptors
1033 if (intent != null && intent.hasFileDescriptors()) {
1034 throw new IllegalArgumentException("File descriptors passed in Intent");
1035 }
1036 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1037
1038 synchronized (mGlobalLock) {
1039 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1040 if (r == null) {
1041 SafeActivityOptions.abort(options);
1042 return false;
1043 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001044 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // The caller is not running... d'oh!
1046 SafeActivityOptions.abort(options);
1047 return false;
1048 }
1049 intent = new Intent(intent);
1050 // The caller is not allowed to change the data.
1051 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1052 // And we are resetting to find the next component...
1053 intent.setComponent(null);
1054
1055 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1056
1057 ActivityInfo aInfo = null;
1058 try {
1059 List<ResolveInfo> resolves =
1060 AppGlobals.getPackageManager().queryIntentActivities(
1061 intent, r.resolvedType,
1062 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1063 UserHandle.getCallingUserId()).getList();
1064
1065 // Look for the original activity in the list...
1066 final int N = resolves != null ? resolves.size() : 0;
1067 for (int i=0; i<N; i++) {
1068 ResolveInfo rInfo = resolves.get(i);
1069 if (rInfo.activityInfo.packageName.equals(r.packageName)
1070 && rInfo.activityInfo.name.equals(r.info.name)) {
1071 // We found the current one... the next matching is
1072 // after it.
1073 i++;
1074 if (i<N) {
1075 aInfo = resolves.get(i).activityInfo;
1076 }
1077 if (debug) {
1078 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1079 + "/" + r.info.name);
1080 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1081 ? "null" : aInfo.packageName + "/" + aInfo.name));
1082 }
1083 break;
1084 }
1085 }
1086 } catch (RemoteException e) {
1087 }
1088
1089 if (aInfo == null) {
1090 // Nobody who is next!
1091 SafeActivityOptions.abort(options);
1092 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1093 return false;
1094 }
1095
1096 intent.setComponent(new ComponentName(
1097 aInfo.applicationInfo.packageName, aInfo.name));
1098 intent.setFlags(intent.getFlags()&~(
1099 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1100 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1101 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1102 FLAG_ACTIVITY_NEW_TASK));
1103
1104 // Okay now we need to start the new activity, replacing the currently running activity.
1105 // This is a little tricky because we want to start the new one as if the current one is
1106 // finished, but not finish the current one first so that there is no flicker.
1107 // And thus...
1108 final boolean wasFinishing = r.finishing;
1109 r.finishing = true;
1110
1111 // Propagate reply information over to the new activity.
1112 final ActivityRecord resultTo = r.resultTo;
1113 final String resultWho = r.resultWho;
1114 final int requestCode = r.requestCode;
1115 r.resultTo = null;
1116 if (resultTo != null) {
1117 resultTo.removeResultsLocked(r, resultWho, requestCode);
1118 }
1119
1120 final long origId = Binder.clearCallingIdentity();
1121 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001122 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 .setResolvedType(r.resolvedType)
1126 .setActivityInfo(aInfo)
1127 .setResultTo(resultTo != null ? resultTo.appToken : null)
1128 .setResultWho(resultWho)
1129 .setRequestCode(requestCode)
1130 .setCallingPid(-1)
1131 .setCallingUid(r.launchedFromUid)
1132 .setCallingPackage(r.launchedFromPackage)
1133 .setRealCallingPid(-1)
1134 .setRealCallingUid(r.launchedFromUid)
1135 .setActivityOptions(options)
1136 .execute();
1137 Binder.restoreCallingIdentity(origId);
1138
1139 r.finishing = wasFinishing;
1140 if (res != ActivityManager.START_SUCCESS) {
1141 return false;
1142 }
1143 return true;
1144 }
1145 }
1146
1147 @Override
1148 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1149 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1150 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1151 final WaitResult res = new WaitResult();
1152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001153 enforceNotIsolatedCaller("startActivityAndWait");
1154 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1155 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001156 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001157 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001158 .setCaller(caller)
1159 .setCallingPackage(callingPackage)
1160 .setResolvedType(resolvedType)
1161 .setResultTo(resultTo)
1162 .setResultWho(resultWho)
1163 .setRequestCode(requestCode)
1164 .setStartFlags(startFlags)
1165 .setActivityOptions(bOptions)
1166 .setMayWait(userId)
1167 .setProfilerInfo(profilerInfo)
1168 .setWaitResult(res)
1169 .execute();
1170 }
1171 return res;
1172 }
1173
1174 @Override
1175 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1176 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1177 int startFlags, Configuration config, Bundle bOptions, int userId) {
1178 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001179 enforceNotIsolatedCaller("startActivityWithConfig");
1180 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1181 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001183 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001184 .setCaller(caller)
1185 .setCallingPackage(callingPackage)
1186 .setResolvedType(resolvedType)
1187 .setResultTo(resultTo)
1188 .setResultWho(resultWho)
1189 .setRequestCode(requestCode)
1190 .setStartFlags(startFlags)
1191 .setGlobalConfiguration(config)
1192 .setActivityOptions(bOptions)
1193 .setMayWait(userId)
1194 .execute();
1195 }
1196 }
1197
Alison Cichowlas3e340502018-08-07 17:15:01 -04001198
1199 @Override
1200 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1201 int callingUid = Binder.getCallingUid();
1202 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1203 throw new SecurityException("Only the system process can request a permission token, "
1204 + "received request from uid: " + callingUid);
1205 }
1206 IBinder permissionToken = new Binder();
1207 synchronized (mGlobalLock) {
1208 mStartActivitySources.put(permissionToken, delegatorToken);
1209 }
1210
1211 Message expireMsg = PooledLambda.obtainMessage(
1212 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1213 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1214
1215 Message forgetMsg = PooledLambda.obtainMessage(
1216 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1217 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1218
1219 return permissionToken;
1220 }
1221
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 @Override
1223 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1224 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001225 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1226 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001228 // permission grants) as any app that may launch one of your own activities. So we only
1229 // allow this in two cases:
1230 // 1) The caller is an activity that is part of the core framework, and then only when it
1231 // is running as the system.
1232 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1233 // can only be requested by a system activity, which may then delegate this call to
1234 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 final ActivityRecord sourceRecord;
1236 final int targetUid;
1237 final String targetPackage;
1238 final boolean isResolver;
1239 synchronized (mGlobalLock) {
1240 if (resultTo == null) {
1241 throw new SecurityException("Must be called from an activity");
1242 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001243 final IBinder sourceToken;
1244 if (permissionToken != null) {
1245 // To even attempt to use a permissionToken, an app must also have this signature
1246 // permission.
1247 mAmInternal.enforceCallingPermission(
1248 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1249 "startActivityAsCaller");
1250 // If called with a permissionToken, we want the sourceRecord from the delegator
1251 // activity that requested this token.
1252 sourceToken = mStartActivitySources.remove(permissionToken);
1253 if (sourceToken == null) {
1254 // Invalid permissionToken, check if it recently expired.
1255 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1256 throw new SecurityException("Called with expired permission token: "
1257 + permissionToken);
1258 } else {
1259 throw new SecurityException("Called with invalid permission token: "
1260 + permissionToken);
1261 }
1262 }
1263 } else {
1264 // This method was called directly by the source.
1265 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267
Wale Ogunwaled32da472018-11-16 07:19:28 -08001268 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269 if (sourceRecord == null) {
1270 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 }
1272 if (sourceRecord.app == null) {
1273 throw new SecurityException("Called without a process attached to activity");
1274 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001275
1276 // Whether called directly or from a delegate, the source activity must be from the
1277 // android package.
1278 if (!sourceRecord.info.packageName.equals("android")) {
1279 throw new SecurityException("Must be called from an activity that is "
1280 + "declared in the android package");
1281 }
1282
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001283 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 // This is still okay, as long as this activity is running under the
1285 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001286 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001288 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 + " must be system uid or original calling uid "
1290 + sourceRecord.launchedFromUid);
1291 }
1292 }
1293 if (ignoreTargetSecurity) {
1294 if (intent.getComponent() == null) {
1295 throw new SecurityException(
1296 "Component must be specified with ignoreTargetSecurity");
1297 }
1298 if (intent.getSelector() != null) {
1299 throw new SecurityException(
1300 "Selector not allowed with ignoreTargetSecurity");
1301 }
1302 }
1303 targetUid = sourceRecord.launchedFromUid;
1304 targetPackage = sourceRecord.launchedFromPackage;
1305 isResolver = sourceRecord.isResolverOrChildActivity();
1306 }
1307
1308 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001309 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 }
1311
1312 // TODO: Switch to user app stacks here.
1313 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001314 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001315 .setCallingUid(targetUid)
1316 .setCallingPackage(targetPackage)
1317 .setResolvedType(resolvedType)
1318 .setResultTo(resultTo)
1319 .setResultWho(resultWho)
1320 .setRequestCode(requestCode)
1321 .setStartFlags(startFlags)
1322 .setActivityOptions(bOptions)
1323 .setMayWait(userId)
1324 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1325 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1326 .execute();
1327 } catch (SecurityException e) {
1328 // XXX need to figure out how to propagate to original app.
1329 // A SecurityException here is generally actually a fault of the original
1330 // calling activity (such as a fairly granting permissions), so propagate it
1331 // back to them.
1332 /*
1333 StringBuilder msg = new StringBuilder();
1334 msg.append("While launching");
1335 msg.append(intent.toString());
1336 msg.append(": ");
1337 msg.append(e.getMessage());
1338 */
1339 throw e;
1340 }
1341 }
1342
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001343 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1344 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1345 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1346 }
1347
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 @Override
1349 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1350 Intent intent, String resolvedType, IVoiceInteractionSession session,
1351 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1352 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 if (session == null || interactor == null) {
1355 throw new NullPointerException("null session or interactor");
1356 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001357 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001359 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 .setCallingUid(callingUid)
1361 .setCallingPackage(callingPackage)
1362 .setResolvedType(resolvedType)
1363 .setVoiceSession(session)
1364 .setVoiceInteractor(interactor)
1365 .setStartFlags(startFlags)
1366 .setProfilerInfo(profilerInfo)
1367 .setActivityOptions(bOptions)
1368 .setMayWait(userId)
1369 .execute();
1370 }
1371
1372 @Override
1373 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1374 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001375 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1376 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(callingUid)
1380 .setCallingPackage(callingPackage)
1381 .setResolvedType(resolvedType)
1382 .setActivityOptions(bOptions)
1383 .setMayWait(userId)
1384 .execute();
1385 }
1386
1387 @Override
1388 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1389 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001390 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 final int callingPid = Binder.getCallingPid();
1392 final long origId = Binder.clearCallingIdentity();
1393 try {
1394 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001395 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1396 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397
1398 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1400 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1402 recentsUid, assistDataReceiver);
1403 }
1404 } finally {
1405 Binder.restoreCallingIdentity(origId);
1406 }
1407 }
1408
1409 @Override
1410 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 "startActivityFromRecents()");
1413
1414 final int callingPid = Binder.getCallingPid();
1415 final int callingUid = Binder.getCallingUid();
1416 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1417 final long origId = Binder.clearCallingIdentity();
1418 try {
1419 synchronized (mGlobalLock) {
1420 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1421 safeOptions);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(origId);
1425 }
1426 }
1427
1428 /**
1429 * This is the internal entry point for handling Activity.finish().
1430 *
1431 * @param token The Binder token referencing the Activity we want to finish.
1432 * @param resultCode Result code, if any, from this Activity.
1433 * @param resultData Result data (Intent), if any, from this Activity.
1434 * @param finishTask Whether to finish the task associated with this Activity.
1435 *
1436 * @return Returns true if the activity successfully finished, or false if it is still running.
1437 */
1438 @Override
1439 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1440 int finishTask) {
1441 // Refuse possible leaked file descriptors
1442 if (resultData != null && resultData.hasFileDescriptors()) {
1443 throw new IllegalArgumentException("File descriptors passed in Intent");
1444 }
1445
1446 synchronized (mGlobalLock) {
1447 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1448 if (r == null) {
1449 return true;
1450 }
1451 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001452 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 ActivityRecord rootR = tr.getRootActivity();
1454 if (rootR == null) {
1455 Slog.w(TAG, "Finishing task with all activities already finished");
1456 }
1457 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1458 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001459 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 return false;
1461 }
1462
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1464 // We should consolidate.
1465 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001467 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 if (next != null) {
1469 // ask watcher if this is allowed
1470 boolean resumeOK = true;
1471 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001472 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001474 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 Watchdog.getInstance().setActivityController(null);
1476 }
1477
1478 if (!resumeOK) {
1479 Slog.i(TAG, "Not finishing activity because controller resumed");
1480 return false;
1481 }
1482 }
1483 }
1484 final long origId = Binder.clearCallingIdentity();
1485 try {
1486 boolean res;
1487 final boolean finishWithRootActivity =
1488 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1489 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1490 || (finishWithRootActivity && r == rootR)) {
1491 // If requested, remove the task that is associated to this activity only if it
1492 // was the root activity in the task. The result code and data is ignored
1493 // because we don't support returning them across task boundaries. Also, to
1494 // keep backwards compatibility we remove the task from recents when finishing
1495 // task with root activity.
1496 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1497 finishWithRootActivity, "finish-activity");
1498 if (!res) {
1499 Slog.i(TAG, "Removing task failed to finish activity");
1500 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001501 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001502 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 } else {
1504 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1505 resultData, "app-request", true);
1506 if (!res) {
1507 Slog.i(TAG, "Failed to finish by app-request");
1508 }
1509 }
1510 return res;
1511 } finally {
1512 Binder.restoreCallingIdentity(origId);
1513 }
1514 }
1515 }
1516
1517 @Override
1518 public boolean finishActivityAffinity(IBinder token) {
1519 synchronized (mGlobalLock) {
1520 final long origId = Binder.clearCallingIdentity();
1521 try {
1522 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1523 if (r == null) {
1524 return false;
1525 }
1526
1527 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1528 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001529 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001530 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001531 return false;
1532 }
1533 return task.getStack().finishActivityAffinityLocked(r);
1534 } finally {
1535 Binder.restoreCallingIdentity(origId);
1536 }
1537 }
1538 }
1539
1540 @Override
1541 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1542 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001543 try {
1544 WindowProcessController proc = null;
1545 synchronized (mGlobalLock) {
1546 ActivityStack stack = ActivityRecord.getStackLocked(token);
1547 if (stack == null) {
1548 return;
1549 }
1550 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1551 false /* fromTimeout */, false /* processPausingActivities */, config);
1552 if (r != null) {
1553 proc = r.app;
1554 }
1555 if (stopProfiling && proc != null) {
1556 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 }
1558 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001559 } finally {
1560 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001562 }
1563
1564 @Override
1565 public final void activityResumed(IBinder token) {
1566 final long origId = Binder.clearCallingIdentity();
1567 synchronized (mGlobalLock) {
1568 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001569 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 }
1571 Binder.restoreCallingIdentity(origId);
1572 }
1573
1574 @Override
1575 public final void activityPaused(IBinder token) {
1576 final long origId = Binder.clearCallingIdentity();
1577 synchronized (mGlobalLock) {
1578 ActivityStack stack = ActivityRecord.getStackLocked(token);
1579 if (stack != null) {
1580 stack.activityPausedLocked(token, false);
1581 }
1582 }
1583 Binder.restoreCallingIdentity(origId);
1584 }
1585
1586 @Override
1587 public final void activityStopped(IBinder token, Bundle icicle,
1588 PersistableBundle persistentState, CharSequence description) {
1589 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1590
1591 // Refuse possible leaked file descriptors
1592 if (icicle != null && icicle.hasFileDescriptors()) {
1593 throw new IllegalArgumentException("File descriptors passed in Bundle");
1594 }
1595
1596 final long origId = Binder.clearCallingIdentity();
1597
1598 synchronized (mGlobalLock) {
1599 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1600 if (r != null) {
1601 r.activityStoppedLocked(icicle, persistentState, description);
1602 }
1603 }
1604
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001605 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606
1607 Binder.restoreCallingIdentity(origId);
1608 }
1609
1610 @Override
1611 public final void activityDestroyed(IBinder token) {
1612 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1613 synchronized (mGlobalLock) {
1614 ActivityStack stack = ActivityRecord.getStackLocked(token);
1615 if (stack != null) {
1616 stack.activityDestroyedLocked(token, "activityDestroyed");
1617 }
1618 }
1619 }
1620
1621 @Override
1622 public final void activityRelaunched(IBinder token) {
1623 final long origId = Binder.clearCallingIdentity();
1624 synchronized (mGlobalLock) {
1625 mStackSupervisor.activityRelaunchedLocked(token);
1626 }
1627 Binder.restoreCallingIdentity(origId);
1628 }
1629
1630 public final void activitySlept(IBinder token) {
1631 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1632
1633 final long origId = Binder.clearCallingIdentity();
1634
1635 synchronized (mGlobalLock) {
1636 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1637 if (r != null) {
1638 mStackSupervisor.activitySleptLocked(r);
1639 }
1640 }
1641
1642 Binder.restoreCallingIdentity(origId);
1643 }
1644
1645 @Override
1646 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1647 synchronized (mGlobalLock) {
1648 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1649 if (r == null) {
1650 return;
1651 }
1652 final long origId = Binder.clearCallingIdentity();
1653 try {
1654 r.setRequestedOrientation(requestedOrientation);
1655 } finally {
1656 Binder.restoreCallingIdentity(origId);
1657 }
1658 }
1659 }
1660
1661 @Override
1662 public int getRequestedOrientation(IBinder token) {
1663 synchronized (mGlobalLock) {
1664 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1665 if (r == null) {
1666 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1667 }
1668 return r.getRequestedOrientation();
1669 }
1670 }
1671
1672 @Override
1673 public void setImmersive(IBinder token, boolean immersive) {
1674 synchronized (mGlobalLock) {
1675 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1676 if (r == null) {
1677 throw new IllegalArgumentException();
1678 }
1679 r.immersive = immersive;
1680
1681 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001682 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001683 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001684 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 }
1686 }
1687 }
1688
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001689 void applyUpdateLockStateLocked(ActivityRecord r) {
1690 // Modifications to the UpdateLock state are done on our handler, outside
1691 // the activity manager's locks. The new state is determined based on the
1692 // state *now* of the relevant activity record. The object is passed to
1693 // the handler solely for logging detail, not to be consulted/modified.
1694 final boolean nextState = r != null && r.immersive;
1695 mH.post(() -> {
1696 if (mUpdateLock.isHeld() != nextState) {
1697 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1698 "Applying new update lock state '" + nextState + "' for " + r);
1699 if (nextState) {
1700 mUpdateLock.acquire();
1701 } else {
1702 mUpdateLock.release();
1703 }
1704 }
1705 });
1706 }
1707
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708 @Override
1709 public boolean isImmersive(IBinder token) {
1710 synchronized (mGlobalLock) {
1711 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1712 if (r == null) {
1713 throw new IllegalArgumentException();
1714 }
1715 return r.immersive;
1716 }
1717 }
1718
1719 @Override
1720 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001721 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001723 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 return (r != null) ? r.immersive : false;
1725 }
1726 }
1727
1728 @Override
1729 public void overridePendingTransition(IBinder token, String packageName,
1730 int enterAnim, int exitAnim) {
1731 synchronized (mGlobalLock) {
1732 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1733 if (self == null) {
1734 return;
1735 }
1736
1737 final long origId = Binder.clearCallingIdentity();
1738
1739 if (self.isState(
1740 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001741 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1742 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001743 }
1744
1745 Binder.restoreCallingIdentity(origId);
1746 }
1747 }
1748
1749 @Override
1750 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001751 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001753 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001754 if (r == null) {
1755 return ActivityManager.COMPAT_MODE_UNKNOWN;
1756 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001757 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 }
1759 }
1760
1761 @Override
1762 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001763 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001765 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001767 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001768 if (r == null) {
1769 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1770 return;
1771 }
1772 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001773 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 }
1775 }
1776
1777 @Override
1778 public int getLaunchedFromUid(IBinder activityToken) {
1779 ActivityRecord srec;
1780 synchronized (mGlobalLock) {
1781 srec = ActivityRecord.forTokenLocked(activityToken);
1782 }
1783 if (srec == null) {
1784 return -1;
1785 }
1786 return srec.launchedFromUid;
1787 }
1788
1789 @Override
1790 public String getLaunchedFromPackage(IBinder activityToken) {
1791 ActivityRecord srec;
1792 synchronized (mGlobalLock) {
1793 srec = ActivityRecord.forTokenLocked(activityToken);
1794 }
1795 if (srec == null) {
1796 return null;
1797 }
1798 return srec.launchedFromPackage;
1799 }
1800
1801 @Override
1802 public boolean convertFromTranslucent(IBinder token) {
1803 final long origId = Binder.clearCallingIdentity();
1804 try {
1805 synchronized (mGlobalLock) {
1806 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1807 if (r == null) {
1808 return false;
1809 }
1810 final boolean translucentChanged = r.changeWindowTranslucency(true);
1811 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001812 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001814 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001815 return translucentChanged;
1816 }
1817 } finally {
1818 Binder.restoreCallingIdentity(origId);
1819 }
1820 }
1821
1822 @Override
1823 public boolean convertToTranslucent(IBinder token, Bundle options) {
1824 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1825 final long origId = Binder.clearCallingIdentity();
1826 try {
1827 synchronized (mGlobalLock) {
1828 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1829 if (r == null) {
1830 return false;
1831 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001832 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 int index = task.mActivities.lastIndexOf(r);
1834 if (index > 0) {
1835 ActivityRecord under = task.mActivities.get(index - 1);
1836 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1837 }
1838 final boolean translucentChanged = r.changeWindowTranslucency(false);
1839 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001840 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001841 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001842 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001843 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 return translucentChanged;
1845 }
1846 } finally {
1847 Binder.restoreCallingIdentity(origId);
1848 }
1849 }
1850
1851 @Override
1852 public void notifyActivityDrawn(IBinder token) {
1853 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1854 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001855 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001857 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 }
1859 }
1860 }
1861
1862 @Override
1863 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1864 synchronized (mGlobalLock) {
1865 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1866 if (r == null) {
1867 return;
1868 }
1869 r.reportFullyDrawnLocked(restoredFromBundle);
1870 }
1871 }
1872
1873 @Override
1874 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1875 synchronized (mGlobalLock) {
1876 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1877 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1878 return stack.mDisplayId;
1879 }
1880 return DEFAULT_DISPLAY;
1881 }
1882 }
1883
1884 @Override
1885 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001886 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001887 long ident = Binder.clearCallingIdentity();
1888 try {
1889 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001890 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001891 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001892 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 }
1894 return null;
1895 }
1896 } finally {
1897 Binder.restoreCallingIdentity(ident);
1898 }
1899 }
1900
1901 @Override
1902 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1905 final long callingId = Binder.clearCallingIdentity();
1906 try {
1907 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001908 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001909 if (stack == null) {
1910 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1911 return;
1912 }
1913 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001914 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001915 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 }
1917 }
1918 } finally {
1919 Binder.restoreCallingIdentity(callingId);
1920 }
1921 }
1922
1923 @Override
1924 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1927 final long callingId = Binder.clearCallingIdentity();
1928 try {
1929 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001930 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001931 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001932 if (task == null) {
1933 return;
1934 }
1935 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001936 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001937 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 }
1939 }
1940 } finally {
1941 Binder.restoreCallingIdentity(callingId);
1942 }
1943 }
1944
1945 @Override
1946 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 synchronized (mGlobalLock) {
1949 final long ident = Binder.clearCallingIdentity();
1950 try {
1951 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1952 "remove-task");
1953 } finally {
1954 Binder.restoreCallingIdentity(ident);
1955 }
1956 }
1957 }
1958
1959 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001960 public void removeAllVisibleRecentTasks() {
1961 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1962 synchronized (mGlobalLock) {
1963 final long ident = Binder.clearCallingIdentity();
1964 try {
1965 getRecentTasks().removeAllVisibleTasks();
1966 } finally {
1967 Binder.restoreCallingIdentity(ident);
1968 }
1969 }
1970 }
1971
1972 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001973 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1974 synchronized (mGlobalLock) {
1975 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1976 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001977 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 }
1979 }
1980 return false;
1981 }
1982
1983 @Override
1984 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1985 Intent resultData) {
1986
1987 synchronized (mGlobalLock) {
1988 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1989 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001990 return r.getActivityStack().navigateUpToLocked(
1991 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 }
1993 return false;
1994 }
1995 }
1996
1997 /**
1998 * Attempts to move a task backwards in z-order (the order of activities within the task is
1999 * unchanged).
2000 *
2001 * There are several possible results of this call:
2002 * - if the task is locked, then we will show the lock toast
2003 * - if there is a task behind the provided task, then that task is made visible and resumed as
2004 * this task is moved to the back
2005 * - otherwise, if there are no other tasks in the stack:
2006 * - if this task is in the pinned stack, then we remove the stack completely, which will
2007 * have the effect of moving the task to the top or bottom of the fullscreen stack
2008 * (depending on whether it is visible)
2009 * - otherwise, we simply return home and hide this task
2010 *
2011 * @param token A reference to the activity we wish to move
2012 * @param nonRoot If false then this only works if the activity is the root
2013 * of a task; if true it will work for any activity in a task.
2014 * @return Returns true if the move completed, false if not.
2015 */
2016 @Override
2017 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002018 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002019 synchronized (mGlobalLock) {
2020 final long origId = Binder.clearCallingIdentity();
2021 try {
2022 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002023 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002024 if (task != null) {
2025 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2026 }
2027 } finally {
2028 Binder.restoreCallingIdentity(origId);
2029 }
2030 }
2031 return false;
2032 }
2033
2034 @Override
2035 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002036 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 long ident = Binder.clearCallingIdentity();
2038 Rect rect = new Rect();
2039 try {
2040 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002041 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2043 if (task == null) {
2044 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2045 return rect;
2046 }
2047 if (task.getStack() != null) {
2048 // Return the bounds from window manager since it will be adjusted for various
2049 // things like the presense of a docked stack for tasks that aren't resizeable.
2050 task.getWindowContainerBounds(rect);
2051 } else {
2052 // Task isn't in window manager yet since it isn't associated with a stack.
2053 // Return the persist value from activity manager
2054 if (!task.matchParentBounds()) {
2055 rect.set(task.getBounds());
2056 } else if (task.mLastNonFullscreenBounds != null) {
2057 rect.set(task.mLastNonFullscreenBounds);
2058 }
2059 }
2060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(ident);
2063 }
2064 return rect;
2065 }
2066
2067 @Override
2068 public ActivityManager.TaskDescription getTaskDescription(int id) {
2069 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002072 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2074 if (tr != null) {
2075 return tr.lastTaskDescription;
2076 }
2077 }
2078 return null;
2079 }
2080
2081 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002082 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2083 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2084 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2085 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2086 return;
2087 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002088 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002089 synchronized (mGlobalLock) {
2090 final long ident = Binder.clearCallingIdentity();
2091 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002092 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002093 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002094 if (task == null) {
2095 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2096 return;
2097 }
2098
2099 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2100 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2101
2102 if (!task.isActivityTypeStandardOrUndefined()) {
2103 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2104 + " non-standard task " + taskId + " to windowing mode="
2105 + windowingMode);
2106 }
2107
2108 final ActivityStack stack = task.getStack();
2109 if (toTop) {
2110 stack.moveToFront("setTaskWindowingMode", task);
2111 }
2112 stack.setWindowingMode(windowingMode);
2113 } finally {
2114 Binder.restoreCallingIdentity(ident);
2115 }
2116 }
2117 }
2118
2119 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002120 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002121 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 ActivityRecord r = getCallingRecordLocked(token);
2123 return r != null ? r.info.packageName : null;
2124 }
2125 }
2126
2127 @Override
2128 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002129 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 ActivityRecord r = getCallingRecordLocked(token);
2131 return r != null ? r.intent.getComponent() : null;
2132 }
2133 }
2134
2135 private ActivityRecord getCallingRecordLocked(IBinder token) {
2136 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2137 if (r == null) {
2138 return null;
2139 }
2140 return r.resultTo;
2141 }
2142
2143 @Override
2144 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002145 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002146
2147 synchronized (mGlobalLock) {
2148 final long origId = Binder.clearCallingIdentity();
2149 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002150 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151 } finally {
2152 Binder.restoreCallingIdentity(origId);
2153 }
2154 }
2155 }
2156
2157 /**
2158 * TODO: Add mController hook
2159 */
2160 @Override
2161 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002162 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163
2164 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2165 synchronized (mGlobalLock) {
2166 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2167 false /* fromRecents */);
2168 }
2169 }
2170
2171 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2172 boolean fromRecents) {
2173
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002174 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 Binder.getCallingUid(), -1, -1, "Task to front")) {
2176 SafeActivityOptions.abort(options);
2177 return;
2178 }
2179 final long origId = Binder.clearCallingIdentity();
2180 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002181 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 if (task == null) {
2183 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002184 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 return;
2186 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002187 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002189 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 return;
2191 }
2192 ActivityOptions realOptions = options != null
2193 ? options.getOptions(mStackSupervisor)
2194 : null;
2195 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2196 false /* forceNonResizable */);
2197
2198 final ActivityRecord topActivity = task.getTopActivity();
2199 if (topActivity != null) {
2200
2201 // We are reshowing a task, use a starting window to hide the initial draw delay
2202 // so the transition can start earlier.
2203 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2204 true /* taskSwitch */, fromRecents);
2205 }
2206 } finally {
2207 Binder.restoreCallingIdentity(origId);
2208 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 }
2210
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002211 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2212 int callingPid, int callingUid, String name) {
2213 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2214 return true;
2215 }
2216
2217 if (getRecentTasks().isCallerRecents(sourceUid)) {
2218 return true;
2219 }
2220
2221 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2222 if (perm == PackageManager.PERMISSION_GRANTED) {
2223 return true;
2224 }
2225 if (checkAllowAppSwitchUid(sourceUid)) {
2226 return true;
2227 }
2228
2229 // If the actual IPC caller is different from the logical source, then
2230 // also see if they are allowed to control app switches.
2231 if (callingUid != -1 && callingUid != sourceUid) {
2232 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2233 if (perm == PackageManager.PERMISSION_GRANTED) {
2234 return true;
2235 }
2236 if (checkAllowAppSwitchUid(callingUid)) {
2237 return true;
2238 }
2239 }
2240
2241 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2242 return false;
2243 }
2244
2245 private boolean checkAllowAppSwitchUid(int uid) {
2246 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2247 if (types != null) {
2248 for (int i = types.size() - 1; i >= 0; i--) {
2249 if (types.valueAt(i).intValue() == uid) {
2250 return true;
2251 }
2252 }
2253 }
2254 return false;
2255 }
2256
2257 @Override
2258 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2259 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2260 "setActivityController()");
2261 synchronized (mGlobalLock) {
2262 mController = controller;
2263 mControllerIsAMonkey = imAMonkey;
2264 Watchdog.getInstance().setActivityController(controller);
2265 }
2266 }
2267
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002268 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002269 synchronized (mGlobalLock) {
2270 return mController != null && mControllerIsAMonkey;
2271 }
2272 }
2273
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002274 @Override
2275 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2276 synchronized (mGlobalLock) {
2277 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2278 }
2279 }
2280
2281 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002282 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2283 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2284 }
2285
2286 @Override
2287 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2288 @WindowConfiguration.ActivityType int ignoreActivityType,
2289 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2290 final int callingUid = Binder.getCallingUid();
2291 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2292
2293 synchronized (mGlobalLock) {
2294 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2295
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002296 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002297 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002298 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002299 ignoreWindowingMode, callingUid, allowed);
2300 }
2301
2302 return list;
2303 }
2304
2305 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2307 synchronized (mGlobalLock) {
2308 final long origId = Binder.clearCallingIdentity();
2309 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2310 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002311 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 }
2313 Binder.restoreCallingIdentity(origId);
2314 }
2315 }
2316
2317 @Override
2318 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002319 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 ActivityStack stack = ActivityRecord.getStackLocked(token);
2321 if (stack != null) {
2322 return stack.willActivityBeVisibleLocked(token);
2323 }
2324 return false;
2325 }
2326 }
2327
2328 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002329 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002330 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002331 synchronized (mGlobalLock) {
2332 final long ident = Binder.clearCallingIdentity();
2333 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002334 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 if (task == null) {
2336 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2337 return;
2338 }
2339
2340 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2341 + " to stackId=" + stackId + " toTop=" + toTop);
2342
Wale Ogunwaled32da472018-11-16 07:19:28 -08002343 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002344 if (stack == null) {
2345 throw new IllegalStateException(
2346 "moveTaskToStack: No stack for stackId=" + stackId);
2347 }
2348 if (!stack.isActivityTypeStandardOrUndefined()) {
2349 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2350 + taskId + " to stack " + stackId);
2351 }
2352 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002353 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002354 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2355 }
2356 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2357 "moveTaskToStack");
2358 } finally {
2359 Binder.restoreCallingIdentity(ident);
2360 }
2361 }
2362 }
2363
2364 @Override
2365 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2366 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002368
2369 final long ident = Binder.clearCallingIdentity();
2370 try {
2371 synchronized (mGlobalLock) {
2372 if (animate) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002373 final PinnedActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002374 if (stack == null) {
2375 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2376 return;
2377 }
2378 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2379 throw new IllegalArgumentException("Stack: " + stackId
2380 + " doesn't support animated resize.");
2381 }
2382 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2383 animationDuration, false /* fromFullscreen */);
2384 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002385 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002386 if (stack == null) {
2387 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2388 return;
2389 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002390 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002391 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2392 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2393 }
2394 }
2395 } finally {
2396 Binder.restoreCallingIdentity(ident);
2397 }
2398 }
2399
2400 /**
2401 * Moves the specified task to the primary-split-screen stack.
2402 *
2403 * @param taskId Id of task to move.
2404 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2405 * exist already. See
2406 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2407 * and
2408 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2409 * @param toTop If the task and stack should be moved to the top.
2410 * @param animate Whether we should play an animation for the moving the task.
2411 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2412 * stack. Pass {@code null} to use default bounds.
2413 * @param showRecents If the recents activity should be shown on the other side of the task
2414 * going into split-screen mode.
2415 */
2416 @Override
2417 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2418 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002420 "setTaskWindowingModeSplitScreenPrimary()");
2421 synchronized (mGlobalLock) {
2422 final long ident = Binder.clearCallingIdentity();
2423 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002424 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002425 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002426 if (task == null) {
2427 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2428 return false;
2429 }
2430 if (DEBUG_STACK) Slog.d(TAG_STACK,
2431 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2432 + " to createMode=" + createMode + " toTop=" + toTop);
2433 if (!task.isActivityTypeStandardOrUndefined()) {
2434 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2435 + " non-standard task " + taskId + " to split-screen windowing mode");
2436 }
2437
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002438 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 final int windowingMode = task.getWindowingMode();
2440 final ActivityStack stack = task.getStack();
2441 if (toTop) {
2442 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2443 }
2444 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002445 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2446 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002447 return windowingMode != task.getWindowingMode();
2448 } finally {
2449 Binder.restoreCallingIdentity(ident);
2450 }
2451 }
2452 }
2453
2454 /**
2455 * Removes stacks in the input windowing modes from the system if they are of activity type
2456 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2457 */
2458 @Override
2459 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002460 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002461 "removeStacksInWindowingModes()");
2462
2463 synchronized (mGlobalLock) {
2464 final long ident = Binder.clearCallingIdentity();
2465 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002466 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002467 } finally {
2468 Binder.restoreCallingIdentity(ident);
2469 }
2470 }
2471 }
2472
2473 @Override
2474 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002475 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002476 "removeStacksWithActivityTypes()");
2477
2478 synchronized (mGlobalLock) {
2479 final long ident = Binder.clearCallingIdentity();
2480 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002481 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002482 } finally {
2483 Binder.restoreCallingIdentity(ident);
2484 }
2485 }
2486 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002487
2488 @Override
2489 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2490 int userId) {
2491 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002492 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2493 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002494 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002495 final boolean detailed = checkGetTasksPermission(
2496 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2497 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002498 == PackageManager.PERMISSION_GRANTED;
2499
2500 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002501 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002502 callingUid);
2503 }
2504 }
2505
2506 @Override
2507 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002508 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 long ident = Binder.clearCallingIdentity();
2510 try {
2511 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002512 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002513 }
2514 } finally {
2515 Binder.restoreCallingIdentity(ident);
2516 }
2517 }
2518
2519 @Override
2520 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002521 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002522 long ident = Binder.clearCallingIdentity();
2523 try {
2524 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002525 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002526 }
2527 } finally {
2528 Binder.restoreCallingIdentity(ident);
2529 }
2530 }
2531
2532 @Override
2533 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002534 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 final long callingUid = Binder.getCallingUid();
2536 final long origId = Binder.clearCallingIdentity();
2537 try {
2538 synchronized (mGlobalLock) {
2539 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002540 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002541 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2542 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2543 }
2544 } finally {
2545 Binder.restoreCallingIdentity(origId);
2546 }
2547 }
2548
2549 @Override
2550 public void startLockTaskModeByToken(IBinder token) {
2551 synchronized (mGlobalLock) {
2552 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2553 if (r == null) {
2554 return;
2555 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002556 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 }
2558 }
2559
2560 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002561 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002562 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002563 // This makes inner call to look as if it was initiated by system.
2564 long ident = Binder.clearCallingIdentity();
2565 try {
2566 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002567 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002568 MATCH_TASK_IN_STACKS_ONLY);
2569 if (task == null) {
2570 return;
2571 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002572
2573 // When starting lock task mode the stack must be in front and focused
2574 task.getStack().moveToFront("startSystemLockTaskMode");
2575 startLockTaskModeLocked(task, true /* isSystemCaller */);
2576 }
2577 } finally {
2578 Binder.restoreCallingIdentity(ident);
2579 }
2580 }
2581
2582 @Override
2583 public void stopLockTaskModeByToken(IBinder token) {
2584 synchronized (mGlobalLock) {
2585 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2586 if (r == null) {
2587 return;
2588 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002589 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002590 }
2591 }
2592
2593 /**
2594 * This API should be called by SystemUI only when user perform certain action to dismiss
2595 * lock task mode. We should only dismiss pinned lock task mode in this case.
2596 */
2597 @Override
2598 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002599 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002600 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2601 }
2602
2603 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2604 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2605 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2606 return;
2607 }
2608
Wale Ogunwaled32da472018-11-16 07:19:28 -08002609 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002610 if (stack == null || task != stack.topTask()) {
2611 throw new IllegalArgumentException("Invalid task, not in foreground");
2612 }
2613
2614 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2615 // system or a specific app.
2616 // * System-initiated requests will only start the pinned mode (screen pinning)
2617 // * App-initiated requests
2618 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2619 // - will start the pinned mode, otherwise
2620 final int callingUid = Binder.getCallingUid();
2621 long ident = Binder.clearCallingIdentity();
2622 try {
2623 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002624 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002625
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002626 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002627 } finally {
2628 Binder.restoreCallingIdentity(ident);
2629 }
2630 }
2631
2632 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2633 final int callingUid = Binder.getCallingUid();
2634 long ident = Binder.clearCallingIdentity();
2635 try {
2636 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002637 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002638 }
2639 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2640 // task and jumping straight into a call in the case of emergency call back.
2641 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2642 if (tm != null) {
2643 tm.showInCallScreen(false);
2644 }
2645 } finally {
2646 Binder.restoreCallingIdentity(ident);
2647 }
2648 }
2649
2650 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002651 public void updateLockTaskPackages(int userId, String[] packages) {
2652 final int callingUid = Binder.getCallingUid();
2653 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2654 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2655 "updateLockTaskPackages()");
2656 }
2657 synchronized (this) {
2658 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2659 + Arrays.toString(packages));
2660 getLockTaskController().updateLockTaskPackages(userId, packages);
2661 }
2662 }
2663
2664 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 public boolean isInLockTaskMode() {
2666 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2667 }
2668
2669 @Override
2670 public int getLockTaskModeState() {
2671 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002672 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002673 }
2674 }
2675
2676 @Override
2677 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2678 synchronized (mGlobalLock) {
2679 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2680 if (r != null) {
2681 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002682 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002683 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002684 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002685 }
2686 }
2687 }
2688
2689 @Override
2690 public Bundle getActivityOptions(IBinder token) {
2691 final long origId = Binder.clearCallingIdentity();
2692 try {
2693 synchronized (mGlobalLock) {
2694 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2695 if (r != null) {
2696 final ActivityOptions activityOptions = r.takeOptionsLocked();
2697 return activityOptions == null ? null : activityOptions.toBundle();
2698 }
2699 return null;
2700 }
2701 } finally {
2702 Binder.restoreCallingIdentity(origId);
2703 }
2704 }
2705
2706 @Override
2707 public List<IBinder> getAppTasks(String callingPackage) {
2708 int callingUid = Binder.getCallingUid();
2709 long ident = Binder.clearCallingIdentity();
2710 try {
2711 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002712 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713 }
2714 } finally {
2715 Binder.restoreCallingIdentity(ident);
2716 }
2717 }
2718
2719 @Override
2720 public void finishVoiceTask(IVoiceInteractionSession session) {
2721 synchronized (mGlobalLock) {
2722 final long origId = Binder.clearCallingIdentity();
2723 try {
2724 // TODO: VI Consider treating local voice interactions and voice tasks
2725 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002726 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002727 } finally {
2728 Binder.restoreCallingIdentity(origId);
2729 }
2730 }
2731
2732 }
2733
2734 @Override
2735 public boolean isTopOfTask(IBinder token) {
2736 synchronized (mGlobalLock) {
2737 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002738 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739 }
2740 }
2741
2742 @Override
2743 public void notifyLaunchTaskBehindComplete(IBinder token) {
2744 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2745 }
2746
2747 @Override
2748 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002749 mH.post(() -> {
2750 synchronized (mGlobalLock) {
2751 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002752 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002753 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002754 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002755 } catch (RemoteException e) {
2756 }
2757 }
2758 }
2759
2760 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 }
2762
2763 /** Called from an app when assist data is ready. */
2764 @Override
2765 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2766 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002767 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 synchronized (pae) {
2769 pae.result = extras;
2770 pae.structure = structure;
2771 pae.content = content;
2772 if (referrer != null) {
2773 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2774 }
2775 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002776 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002777 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2778 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 structure.setHomeActivity(pae.isHome);
2780 }
2781 pae.haveResult = true;
2782 pae.notifyAll();
2783 if (pae.intent == null && pae.receiver == null) {
2784 // Caller is just waiting for the result.
2785 return;
2786 }
2787 }
2788 // We are now ready to launch the assist activity.
2789 IAssistDataReceiver sendReceiver = null;
2790 Bundle sendBundle = null;
2791 synchronized (mGlobalLock) {
2792 buildAssistBundleLocked(pae, extras);
2793 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002794 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 if (!exists) {
2796 // Timed out.
2797 return;
2798 }
2799
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 // Caller wants result sent back to them.
2802 sendBundle = new Bundle();
2803 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2804 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2805 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2806 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2807 }
2808 }
2809 if (sendReceiver != null) {
2810 try {
2811 sendReceiver.onHandleAssistData(sendBundle);
2812 } catch (RemoteException e) {
2813 }
2814 return;
2815 }
2816
2817 final long ident = Binder.clearCallingIdentity();
2818 try {
2819 if (TextUtils.equals(pae.intent.getAction(),
2820 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2821 pae.intent.putExtras(pae.extras);
2822 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2823 } else {
2824 pae.intent.replaceExtras(pae.extras);
2825 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2826 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2827 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002828 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829
2830 try {
2831 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2832 } catch (ActivityNotFoundException e) {
2833 Slog.w(TAG, "No activity to handle assist action.", e);
2834 }
2835 }
2836 } finally {
2837 Binder.restoreCallingIdentity(ident);
2838 }
2839 }
2840
2841 @Override
2842 public int addAppTask(IBinder activityToken, Intent intent,
2843 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2844 final int callingUid = Binder.getCallingUid();
2845 final long callingIdent = Binder.clearCallingIdentity();
2846
2847 try {
2848 synchronized (mGlobalLock) {
2849 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2850 if (r == null) {
2851 throw new IllegalArgumentException("Activity does not exist; token="
2852 + activityToken);
2853 }
2854 ComponentName comp = intent.getComponent();
2855 if (comp == null) {
2856 throw new IllegalArgumentException("Intent " + intent
2857 + " must specify explicit component");
2858 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002859 if (thumbnail.getWidth() != mThumbnailWidth
2860 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002861 throw new IllegalArgumentException("Bad thumbnail size: got "
2862 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002863 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 }
2865 if (intent.getSelector() != null) {
2866 intent.setSelector(null);
2867 }
2868 if (intent.getSourceBounds() != null) {
2869 intent.setSourceBounds(null);
2870 }
2871 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2872 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2873 // The caller has added this as an auto-remove task... that makes no
2874 // sense, so turn off auto-remove.
2875 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2876 }
2877 }
2878 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2879 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2880 if (ainfo.applicationInfo.uid != callingUid) {
2881 throw new SecurityException(
2882 "Can't add task for another application: target uid="
2883 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2884 }
2885
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002886 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002888 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002889 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002890 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 // The app has too many tasks already and we can't add any more
2892 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2893 return INVALID_TASK_ID;
2894 }
2895 task.lastTaskDescription.copyFrom(description);
2896
2897 // TODO: Send the thumbnail to WM to store it.
2898
2899 return task.taskId;
2900 }
2901 } finally {
2902 Binder.restoreCallingIdentity(callingIdent);
2903 }
2904 }
2905
2906 @Override
2907 public Point getAppTaskThumbnailSize() {
2908 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002909 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 }
2911 }
2912
2913 @Override
2914 public void setTaskResizeable(int taskId, int resizeableMode) {
2915 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002916 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2918 if (task == null) {
2919 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2920 return;
2921 }
2922 task.setResizeMode(resizeableMode);
2923 }
2924 }
2925
2926 @Override
2927 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002928 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 long ident = Binder.clearCallingIdentity();
2930 try {
2931 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002932 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002933 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934 if (task == null) {
2935 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2936 return;
2937 }
2938 // Place the task in the right stack if it isn't there already based on
2939 // the requested bounds.
2940 // The stack transition logic is:
2941 // - a null bounds on a freeform task moves that task to fullscreen
2942 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2943 // that task to freeform
2944 // - otherwise the task is not moved
2945 ActivityStack stack = task.getStack();
2946 if (!task.getWindowConfiguration().canResizeTask()) {
2947 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2948 }
2949 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2950 stack = stack.getDisplay().getOrCreateStack(
2951 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2952 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2953 stack = stack.getDisplay().getOrCreateStack(
2954 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2955 }
2956
2957 // Reparent the task to the right stack if necessary
2958 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2959 if (stack != task.getStack()) {
2960 // Defer resume until the task is resized below
2961 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2962 DEFER_RESUME, "resizeTask");
2963 preserveWindow = false;
2964 }
2965
2966 // After reparenting (which only resizes the task to the stack bounds), resize the
2967 // task to the actual bounds provided
2968 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2969 }
2970 } finally {
2971 Binder.restoreCallingIdentity(ident);
2972 }
2973 }
2974
2975 @Override
2976 public boolean releaseActivityInstance(IBinder token) {
2977 synchronized (mGlobalLock) {
2978 final long origId = Binder.clearCallingIdentity();
2979 try {
2980 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2981 if (r == null) {
2982 return false;
2983 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002984 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 } finally {
2986 Binder.restoreCallingIdentity(origId);
2987 }
2988 }
2989 }
2990
2991 @Override
2992 public void releaseSomeActivities(IApplicationThread appInt) {
2993 synchronized (mGlobalLock) {
2994 final long origId = Binder.clearCallingIdentity();
2995 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002996 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002997 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002998 } finally {
2999 Binder.restoreCallingIdentity(origId);
3000 }
3001 }
3002 }
3003
3004 @Override
3005 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003006 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003007 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 != PackageManager.PERMISSION_GRANTED) {
3009 throw new SecurityException("Requires permission "
3010 + android.Manifest.permission.DEVICE_POWER);
3011 }
3012
3013 synchronized (mGlobalLock) {
3014 long ident = Binder.clearCallingIdentity();
3015 if (mKeyguardShown != keyguardShowing) {
3016 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003017 final Message msg = PooledLambda.obtainMessage(
3018 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3019 keyguardShowing);
3020 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 }
3022 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003023 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003024 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 } finally {
3026 Binder.restoreCallingIdentity(ident);
3027 }
3028 }
3029
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003030 mH.post(() -> {
3031 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3032 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3033 }
3034 });
3035 }
3036
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003037 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003038 mH.post(() -> {
3039 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3040 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3041 }
3042 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 }
3044
3045 @Override
3046 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003047 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3048 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003049
3050 final File passedIconFile = new File(filePath);
3051 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3052 passedIconFile.getName());
3053 if (!legitIconFile.getPath().equals(filePath)
3054 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3055 throw new IllegalArgumentException("Bad file path: " + filePath
3056 + " passed for userId " + userId);
3057 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003058 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 }
3060
3061 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003062 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003063 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3064 final ActivityOptions activityOptions = safeOptions != null
3065 ? safeOptions.getOptions(mStackSupervisor)
3066 : null;
3067 if (activityOptions == null
3068 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3069 || activityOptions.getCustomInPlaceResId() == 0) {
3070 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3071 "with valid animation");
3072 }
lumark588a3e82018-07-20 18:53:54 +08003073 // Get top display of front most application.
3074 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3075 if (focusedStack != null) {
3076 final DisplayWindowController dwc =
3077 focusedStack.getDisplay().getWindowContainerController();
3078 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3079 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3080 activityOptions.getCustomInPlaceResId());
3081 dwc.executeAppTransition();
3082 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 }
3084
3085 @Override
3086 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003087 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003088 synchronized (mGlobalLock) {
3089 final long ident = Binder.clearCallingIdentity();
3090 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003091 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 if (stack == null) {
3093 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3094 return;
3095 }
3096 if (!stack.isActivityTypeStandardOrUndefined()) {
3097 throw new IllegalArgumentException(
3098 "Removing non-standard stack is not allowed.");
3099 }
3100 mStackSupervisor.removeStack(stack);
3101 } finally {
3102 Binder.restoreCallingIdentity(ident);
3103 }
3104 }
3105 }
3106
3107 @Override
3108 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003109 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110
3111 synchronized (mGlobalLock) {
3112 final long ident = Binder.clearCallingIdentity();
3113 try {
3114 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3115 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003116 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 } finally {
3118 Binder.restoreCallingIdentity(ident);
3119 }
3120 }
3121 }
3122
3123 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 public void exitFreeformMode(IBinder token) {
3125 synchronized (mGlobalLock) {
3126 long ident = Binder.clearCallingIdentity();
3127 try {
3128 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3129 if (r == null) {
3130 throw new IllegalArgumentException(
3131 "exitFreeformMode: No activity record matching token=" + token);
3132 }
3133
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003134 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 if (stack == null || !stack.inFreeformWindowingMode()) {
3136 throw new IllegalStateException(
3137 "exitFreeformMode: You can only go fullscreen from freeform.");
3138 }
3139
3140 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3141 } finally {
3142 Binder.restoreCallingIdentity(ident);
3143 }
3144 }
3145 }
3146
3147 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3148 @Override
3149 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003152 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 }
3154
3155 /** Unregister a task stack listener so that it stops receiving callbacks. */
3156 @Override
3157 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003158 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003160 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 }
3162
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 @Override
3164 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3165 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3166 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3167 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3168 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3169 }
3170
3171 @Override
3172 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3173 IBinder activityToken, int flags) {
3174 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3175 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3176 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3177 }
3178
3179 @Override
3180 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3181 Bundle args) {
3182 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3183 true /* focused */, true /* newSessionId */, userHandle, args,
3184 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3185 }
3186
3187 @Override
3188 public Bundle getAssistContextExtras(int requestType) {
3189 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3190 null, null, true /* focused */, true /* newSessionId */,
3191 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3192 if (pae == null) {
3193 return null;
3194 }
3195 synchronized (pae) {
3196 while (!pae.haveResult) {
3197 try {
3198 pae.wait();
3199 } catch (InterruptedException e) {
3200 }
3201 }
3202 }
3203 synchronized (mGlobalLock) {
3204 buildAssistBundleLocked(pae, pae.result);
3205 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003206 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 }
3208 return pae.extras;
3209 }
3210
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 /**
3212 * Binder IPC calls go through the public entry point.
3213 * This can be called with or without the global lock held.
3214 */
3215 private static int checkCallingPermission(String permission) {
3216 return checkPermission(
3217 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3218 }
3219
3220 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003221 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003222 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3223 mAmInternal.enforceCallingPermission(permission, func);
3224 }
3225 }
3226
3227 @VisibleForTesting
3228 int checkGetTasksPermission(String permission, int pid, int uid) {
3229 return checkPermission(permission, pid, uid);
3230 }
3231
3232 static int checkPermission(String permission, int pid, int uid) {
3233 if (permission == null) {
3234 return PackageManager.PERMISSION_DENIED;
3235 }
3236 return checkComponentPermission(permission, pid, uid, -1, true);
3237 }
3238
Wale Ogunwale214f3482018-10-04 11:00:47 -07003239 public static int checkComponentPermission(String permission, int pid, int uid,
3240 int owningUid, boolean exported) {
3241 return ActivityManagerService.checkComponentPermission(
3242 permission, pid, uid, owningUid, exported);
3243 }
3244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3246 if (getRecentTasks().isCallerRecents(callingUid)) {
3247 // Always allow the recents component to get tasks
3248 return true;
3249 }
3250
3251 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3252 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3253 if (!allowed) {
3254 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3255 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3256 // Temporary compatibility: some existing apps on the system image may
3257 // still be requesting the old permission and not switched to the new
3258 // one; if so, we'll still allow them full access. This means we need
3259 // to see if they are holding the old permission and are a system app.
3260 try {
3261 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3262 allowed = true;
3263 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3264 + " is using old GET_TASKS but privileged; allowing");
3265 }
3266 } catch (RemoteException e) {
3267 }
3268 }
3269 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3270 + " does not hold REAL_GET_TASKS; limiting output");
3271 }
3272 return allowed;
3273 }
3274
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3276 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3277 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3278 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003279 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003280 "enqueueAssistContext()");
3281
3282 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003283 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 if (activity == null) {
3285 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3286 return null;
3287 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003288 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003289 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3290 return null;
3291 }
3292 if (focused) {
3293 if (activityToken != null) {
3294 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3295 if (activity != caller) {
3296 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3297 + " is not current top " + activity);
3298 return null;
3299 }
3300 }
3301 } else {
3302 activity = ActivityRecord.forTokenLocked(activityToken);
3303 if (activity == null) {
3304 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3305 + " couldn't be found");
3306 return null;
3307 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003308 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3310 return null;
3311 }
3312 }
3313
3314 PendingAssistExtras pae;
3315 Bundle extras = new Bundle();
3316 if (args != null) {
3317 extras.putAll(args);
3318 }
3319 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003320 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321
3322 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3323 userHandle);
3324 pae.isHome = activity.isActivityTypeHome();
3325
3326 // Increment the sessionId if necessary
3327 if (newSessionId) {
3328 mViSessionId++;
3329 }
3330 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003331 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3332 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003334 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 } catch (RemoteException e) {
3336 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3337 return null;
3338 }
3339 return pae;
3340 }
3341 }
3342
3343 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3344 if (result != null) {
3345 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3346 }
3347 if (pae.hint != null) {
3348 pae.extras.putBoolean(pae.hint, true);
3349 }
3350 }
3351
3352 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3353 IAssistDataReceiver receiver;
3354 synchronized (mGlobalLock) {
3355 mPendingAssistExtras.remove(pae);
3356 receiver = pae.receiver;
3357 }
3358 if (receiver != null) {
3359 // Caller wants result sent back to them.
3360 Bundle sendBundle = new Bundle();
3361 // At least return the receiver extras
3362 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3363 try {
3364 pae.receiver.onHandleAssistData(sendBundle);
3365 } catch (RemoteException e) {
3366 }
3367 }
3368 }
3369
3370 public class PendingAssistExtras extends Binder implements Runnable {
3371 public final ActivityRecord activity;
3372 public boolean isHome;
3373 public final Bundle extras;
3374 public final Intent intent;
3375 public final String hint;
3376 public final IAssistDataReceiver receiver;
3377 public final int userHandle;
3378 public boolean haveResult = false;
3379 public Bundle result = null;
3380 public AssistStructure structure = null;
3381 public AssistContent content = null;
3382 public Bundle receiverExtras;
3383
3384 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3385 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3386 int _userHandle) {
3387 activity = _activity;
3388 extras = _extras;
3389 intent = _intent;
3390 hint = _hint;
3391 receiver = _receiver;
3392 receiverExtras = _receiverExtras;
3393 userHandle = _userHandle;
3394 }
3395
3396 @Override
3397 public void run() {
3398 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3399 synchronized (this) {
3400 haveResult = true;
3401 notifyAll();
3402 }
3403 pendingAssistExtrasTimedOut(this);
3404 }
3405 }
3406
3407 @Override
3408 public boolean isAssistDataAllowedOnCurrentActivity() {
3409 int userId;
3410 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003411 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3413 return false;
3414 }
3415
3416 final ActivityRecord activity = focusedStack.getTopActivity();
3417 if (activity == null) {
3418 return false;
3419 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003420 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 }
3422 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3423 }
3424
3425 @Override
3426 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3427 long ident = Binder.clearCallingIdentity();
3428 try {
3429 synchronized (mGlobalLock) {
3430 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003431 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 if (top != caller) {
3433 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3434 + " is not current top " + top);
3435 return false;
3436 }
3437 if (!top.nowVisible) {
3438 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3439 + " is not visible");
3440 return false;
3441 }
3442 }
3443 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3444 token);
3445 } finally {
3446 Binder.restoreCallingIdentity(ident);
3447 }
3448 }
3449
3450 @Override
3451 public boolean isRootVoiceInteraction(IBinder token) {
3452 synchronized (mGlobalLock) {
3453 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3454 if (r == null) {
3455 return false;
3456 }
3457 return r.rootVoiceInteraction;
3458 }
3459 }
3460
Wale Ogunwalef6733932018-06-27 05:14:34 -07003461 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3462 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3463 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3464 if (activityToCallback == null) return;
3465 activityToCallback.setVoiceSessionLocked(voiceSession);
3466
3467 // Inform the activity
3468 try {
3469 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3470 voiceInteractor);
3471 long token = Binder.clearCallingIdentity();
3472 try {
3473 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3474 } finally {
3475 Binder.restoreCallingIdentity(token);
3476 }
3477 // TODO: VI Should we cache the activity so that it's easier to find later
3478 // rather than scan through all the stacks and activities?
3479 } catch (RemoteException re) {
3480 activityToCallback.clearVoiceSessionLocked();
3481 // TODO: VI Should this terminate the voice session?
3482 }
3483 }
3484
3485 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3486 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3487 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3488 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3489 boolean wasRunningVoice = mRunningVoice != null;
3490 mRunningVoice = session;
3491 if (!wasRunningVoice) {
3492 mVoiceWakeLock.acquire();
3493 updateSleepIfNeededLocked();
3494 }
3495 }
3496 }
3497
3498 void finishRunningVoiceLocked() {
3499 if (mRunningVoice != null) {
3500 mRunningVoice = null;
3501 mVoiceWakeLock.release();
3502 updateSleepIfNeededLocked();
3503 }
3504 }
3505
3506 @Override
3507 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3508 synchronized (mGlobalLock) {
3509 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3510 if (keepAwake) {
3511 mVoiceWakeLock.acquire();
3512 } else {
3513 mVoiceWakeLock.release();
3514 }
3515 }
3516 }
3517 }
3518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 @Override
3520 public ComponentName getActivityClassForToken(IBinder token) {
3521 synchronized (mGlobalLock) {
3522 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3523 if (r == null) {
3524 return null;
3525 }
3526 return r.intent.getComponent();
3527 }
3528 }
3529
3530 @Override
3531 public String getPackageForToken(IBinder token) {
3532 synchronized (mGlobalLock) {
3533 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3534 if (r == null) {
3535 return null;
3536 }
3537 return r.packageName;
3538 }
3539 }
3540
3541 @Override
3542 public void showLockTaskEscapeMessage(IBinder token) {
3543 synchronized (mGlobalLock) {
3544 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3545 if (r == null) {
3546 return;
3547 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003548 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003549 }
3550 }
3551
3552 @Override
3553 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003554 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 final long token = Binder.clearCallingIdentity();
3556 try {
3557 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003558 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 }
3560 } finally {
3561 Binder.restoreCallingIdentity(token);
3562 }
3563 }
3564
3565 /**
3566 * Try to place task to provided position. The final position might be different depending on
3567 * current user and stacks state. The task will be moved to target stack if it's currently in
3568 * different stack.
3569 */
3570 @Override
3571 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003572 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003573 synchronized (mGlobalLock) {
3574 long ident = Binder.clearCallingIdentity();
3575 try {
3576 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3577 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003578 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579 if (task == null) {
3580 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3581 + taskId);
3582 }
3583
Wale Ogunwaled32da472018-11-16 07:19:28 -08003584 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003585
3586 if (stack == null) {
3587 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3588 + stackId);
3589 }
3590 if (!stack.isActivityTypeStandardOrUndefined()) {
3591 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3592 + " the position of task " + taskId + " in/to non-standard stack");
3593 }
3594
3595 // TODO: Have the callers of this API call a separate reparent method if that is
3596 // what they intended to do vs. having this method also do reparenting.
3597 if (task.getStack() == stack) {
3598 // Change position in current stack.
3599 stack.positionChildAt(task, position);
3600 } else {
3601 // Reparent to new stack.
3602 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3603 !DEFER_RESUME, "positionTaskInStack");
3604 }
3605 } finally {
3606 Binder.restoreCallingIdentity(ident);
3607 }
3608 }
3609 }
3610
3611 @Override
3612 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3613 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3614 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3615 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3616 synchronized (mGlobalLock) {
3617 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3618 if (record == null) {
3619 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3620 + "found for: " + token);
3621 }
3622 record.setSizeConfigurations(horizontalSizeConfiguration,
3623 verticalSizeConfigurations, smallestSizeConfigurations);
3624 }
3625 }
3626
3627 /**
3628 * Dismisses split-screen multi-window mode.
3629 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3630 */
3631 @Override
3632 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003633 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003634 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3635 final long ident = Binder.clearCallingIdentity();
3636 try {
3637 synchronized (mGlobalLock) {
3638 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003639 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640 if (stack == null) {
3641 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3642 return;
3643 }
3644
3645 if (toTop) {
3646 // Caller wants the current split-screen primary stack to be the top stack after
3647 // it goes fullscreen, so move it to the front.
3648 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003649 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 // In this case the current split-screen primary stack shouldn't be the top
3651 // stack after it goes fullscreen, but it current has focus, so we move the
3652 // focus to the top-most split-screen secondary stack next to it.
3653 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3654 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3655 if (otherStack != null) {
3656 otherStack.moveToFront("dismissSplitScreenMode_other");
3657 }
3658 }
3659
Evan Rosky10475742018-09-05 19:02:48 -07003660 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003661 }
3662 } finally {
3663 Binder.restoreCallingIdentity(ident);
3664 }
3665 }
3666
3667 /**
3668 * Dismisses Pip
3669 * @param animate True if the dismissal should be animated.
3670 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3671 * default animation duration should be used.
3672 */
3673 @Override
3674 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003675 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003676 final long ident = Binder.clearCallingIdentity();
3677 try {
3678 synchronized (mGlobalLock) {
3679 final PinnedActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003680 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681 if (stack == null) {
3682 Slog.w(TAG, "dismissPip: pinned stack not found.");
3683 return;
3684 }
3685 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3686 throw new IllegalArgumentException("Stack: " + stack
3687 + " doesn't support animated resize.");
3688 }
3689 if (animate) {
3690 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3691 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3692 } else {
3693 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3694 }
3695 }
3696 } finally {
3697 Binder.restoreCallingIdentity(ident);
3698 }
3699 }
3700
3701 @Override
3702 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003703 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003704 synchronized (mGlobalLock) {
3705 mSuppressResizeConfigChanges = suppress;
3706 }
3707 }
3708
3709 /**
3710 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3711 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3712 * activity and clearing the task at the same time.
3713 */
3714 @Override
3715 // TODO: API should just be about changing windowing modes...
3716 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003717 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718 "moveTasksToFullscreenStack()");
3719 synchronized (mGlobalLock) {
3720 final long origId = Binder.clearCallingIdentity();
3721 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003722 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003723 if (stack != null){
3724 if (!stack.isActivityTypeStandardOrUndefined()) {
3725 throw new IllegalArgumentException(
3726 "You can't move tasks from non-standard stacks.");
3727 }
3728 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3729 }
3730 } finally {
3731 Binder.restoreCallingIdentity(origId);
3732 }
3733 }
3734 }
3735
3736 /**
3737 * Moves the top activity in the input stackId to the pinned stack.
3738 *
3739 * @param stackId Id of stack to move the top activity to pinned stack.
3740 * @param bounds Bounds to use for pinned stack.
3741 *
3742 * @return True if the top activity of the input stack was successfully moved to the pinned
3743 * stack.
3744 */
3745 @Override
3746 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003747 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 "moveTopActivityToPinnedStack()");
3749 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003750 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3752 + "Device doesn't support picture-in-picture mode");
3753 }
3754
3755 long ident = Binder.clearCallingIdentity();
3756 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003757 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003758 } finally {
3759 Binder.restoreCallingIdentity(ident);
3760 }
3761 }
3762 }
3763
3764 @Override
3765 public boolean isInMultiWindowMode(IBinder token) {
3766 final long origId = Binder.clearCallingIdentity();
3767 try {
3768 synchronized (mGlobalLock) {
3769 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3770 if (r == null) {
3771 return false;
3772 }
3773 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3774 return r.inMultiWindowMode();
3775 }
3776 } finally {
3777 Binder.restoreCallingIdentity(origId);
3778 }
3779 }
3780
3781 @Override
3782 public boolean isInPictureInPictureMode(IBinder token) {
3783 final long origId = Binder.clearCallingIdentity();
3784 try {
3785 synchronized (mGlobalLock) {
3786 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3787 }
3788 } finally {
3789 Binder.restoreCallingIdentity(origId);
3790 }
3791 }
3792
3793 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003794 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3795 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 return false;
3797 }
3798
3799 // If we are animating to fullscreen then we have already dispatched the PIP mode
3800 // changed, so we should reflect that check here as well.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003801 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003802 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3803 return !windowController.isAnimatingBoundsToFullscreen();
3804 }
3805
3806 @Override
3807 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3808 final long origId = Binder.clearCallingIdentity();
3809 try {
3810 synchronized (mGlobalLock) {
3811 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3812 "enterPictureInPictureMode", token, params);
3813
3814 // If the activity is already in picture in picture mode, then just return early
3815 if (isInPictureInPictureMode(r)) {
3816 return true;
3817 }
3818
3819 // Activity supports picture-in-picture, now check that we can enter PiP at this
3820 // point, if it is
3821 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3822 false /* beforeStopping */)) {
3823 return false;
3824 }
3825
3826 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003827 synchronized (mGlobalLock) {
3828 // Only update the saved args from the args that are set
3829 r.pictureInPictureArgs.copyOnlySet(params);
3830 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3831 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3832 // Adjust the source bounds by the insets for the transition down
3833 final Rect sourceBounds = new Rect(
3834 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003835 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003836 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003837 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003838 stack.setPictureInPictureAspectRatio(aspectRatio);
3839 stack.setPictureInPictureActions(actions);
3840 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3841 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3842 logPictureInPictureArgs(params);
3843 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 };
3845
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003846 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 // If the keyguard is showing or occluded, then try and dismiss it before
3848 // entering picture-in-picture (this will prompt the user to authenticate if the
3849 // device is currently locked).
3850 dismissKeyguard(token, new KeyguardDismissCallback() {
3851 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003852 public void onDismissSucceeded() {
3853 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854 }
3855 }, null /* message */);
3856 } else {
3857 // Enter picture in picture immediately otherwise
3858 enterPipRunnable.run();
3859 }
3860 return true;
3861 }
3862 } finally {
3863 Binder.restoreCallingIdentity(origId);
3864 }
3865 }
3866
3867 @Override
3868 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3869 final long origId = Binder.clearCallingIdentity();
3870 try {
3871 synchronized (mGlobalLock) {
3872 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3873 "setPictureInPictureParams", token, params);
3874
3875 // Only update the saved args from the args that are set
3876 r.pictureInPictureArgs.copyOnlySet(params);
3877 if (r.inPinnedWindowingMode()) {
3878 // If the activity is already in picture-in-picture, update the pinned stack now
3879 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3880 // be used the next time the activity enters PiP
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003881 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 if (!stack.isAnimatingBoundsToFullscreen()) {
3883 stack.setPictureInPictureAspectRatio(
3884 r.pictureInPictureArgs.getAspectRatio());
3885 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3886 }
3887 }
3888 logPictureInPictureArgs(params);
3889 }
3890 } finally {
3891 Binder.restoreCallingIdentity(origId);
3892 }
3893 }
3894
3895 @Override
3896 public int getMaxNumPictureInPictureActions(IBinder token) {
3897 // Currently, this is a static constant, but later, we may change this to be dependent on
3898 // the context of the activity
3899 return 3;
3900 }
3901
3902 private void logPictureInPictureArgs(PictureInPictureParams params) {
3903 if (params.hasSetActions()) {
3904 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3905 params.getActions().size());
3906 }
3907 if (params.hasSetAspectRatio()) {
3908 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3909 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3910 MetricsLogger.action(lm);
3911 }
3912 }
3913
3914 /**
3915 * Checks the state of the system and the activity associated with the given {@param token} to
3916 * verify that picture-in-picture is supported for that activity.
3917 *
3918 * @return the activity record for the given {@param token} if all the checks pass.
3919 */
3920 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3921 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 throw new IllegalStateException(caller
3924 + ": Device doesn't support picture-in-picture mode.");
3925 }
3926
3927 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3928 if (r == null) {
3929 throw new IllegalStateException(caller
3930 + ": Can't find activity for token=" + token);
3931 }
3932
3933 if (!r.supportsPictureInPicture()) {
3934 throw new IllegalStateException(caller
3935 + ": Current activity does not support picture-in-picture.");
3936 }
3937
3938 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003939 && !mWindowManager.isValidPictureInPictureAspectRatio(
3940 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 final float minAspectRatio = mContext.getResources().getFloat(
3942 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3943 final float maxAspectRatio = mContext.getResources().getFloat(
3944 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3945 throw new IllegalArgumentException(String.format(caller
3946 + ": Aspect ratio is too extreme (must be between %f and %f).",
3947 minAspectRatio, maxAspectRatio));
3948 }
3949
3950 // Truncate the number of actions if necessary
3951 params.truncateActions(getMaxNumPictureInPictureActions(token));
3952
3953 return r;
3954 }
3955
3956 @Override
3957 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003958 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 synchronized (mGlobalLock) {
3960 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3961 if (r == null) {
3962 throw new IllegalArgumentException("Activity does not exist; token="
3963 + activityToken);
3964 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003965 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 }
3967 }
3968
3969 @Override
3970 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3971 Rect tempDockedTaskInsetBounds,
3972 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003973 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 long ident = Binder.clearCallingIdentity();
3975 try {
3976 synchronized (mGlobalLock) {
3977 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3978 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3979 PRESERVE_WINDOWS);
3980 }
3981 } finally {
3982 Binder.restoreCallingIdentity(ident);
3983 }
3984 }
3985
3986 @Override
3987 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 final long ident = Binder.clearCallingIdentity();
3990 try {
3991 synchronized (mGlobalLock) {
3992 mStackSupervisor.setSplitScreenResizing(resizing);
3993 }
3994 } finally {
3995 Binder.restoreCallingIdentity(ident);
3996 }
3997 }
3998
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003999 /**
4000 * Check that we have the features required for VR-related API calls, and throw an exception if
4001 * not.
4002 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004003 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 if (!mContext.getPackageManager().hasSystemFeature(
4005 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4006 throw new UnsupportedOperationException("VR mode not supported on this device!");
4007 }
4008 }
4009
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 @Override
4011 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013
4014 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4015
4016 ActivityRecord r;
4017 synchronized (mGlobalLock) {
4018 r = ActivityRecord.isInStackLocked(token);
4019 }
4020
4021 if (r == null) {
4022 throw new IllegalArgumentException();
4023 }
4024
4025 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004026 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 VrManagerInternal.NO_ERROR) {
4028 return err;
4029 }
4030
4031 // Clear the binder calling uid since this path may call moveToTask().
4032 final long callingId = Binder.clearCallingIdentity();
4033 try {
4034 synchronized (mGlobalLock) {
4035 r.requestedVrComponent = (enabled) ? packageName : null;
4036
4037 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004038 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004039 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 }
4041 return 0;
4042 }
4043 } finally {
4044 Binder.restoreCallingIdentity(callingId);
4045 }
4046 }
4047
4048 @Override
4049 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4050 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4051 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004052 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4054 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4055 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004056 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 || activity.voiceSession != null) {
4058 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4059 return;
4060 }
4061 if (activity.pendingVoiceInteractionStart) {
4062 Slog.w(TAG, "Pending start of voice interaction already.");
4063 return;
4064 }
4065 activity.pendingVoiceInteractionStart = true;
4066 }
4067 LocalServices.getService(VoiceInteractionManagerInternal.class)
4068 .startLocalVoiceInteraction(callingActivity, options);
4069 }
4070
4071 @Override
4072 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4073 LocalServices.getService(VoiceInteractionManagerInternal.class)
4074 .stopLocalVoiceInteraction(callingActivity);
4075 }
4076
4077 @Override
4078 public boolean supportsLocalVoiceInteraction() {
4079 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4080 .supportsLocalVoiceInteraction();
4081 }
4082
4083 /** Notifies all listeners when the pinned stack animation starts. */
4084 @Override
4085 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004086 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 }
4088
4089 /** Notifies all listeners when the pinned stack animation ends. */
4090 @Override
4091 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004092 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093 }
4094
4095 @Override
4096 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004097 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004098 final long ident = Binder.clearCallingIdentity();
4099 try {
4100 synchronized (mGlobalLock) {
4101 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4102 }
4103 } finally {
4104 Binder.restoreCallingIdentity(ident);
4105 }
4106 }
4107
4108 @Override
4109 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004110 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111
4112 synchronized (mGlobalLock) {
4113 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004114 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 // Call might come when display is not yet added or has already been removed.
4116 if (DEBUG_CONFIGURATION) {
4117 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4118 + displayId);
4119 }
4120 return false;
4121 }
4122
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004123 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004125 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 }
4127
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004128 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004129 final Message msg = PooledLambda.obtainMessage(
4130 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4131 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 }
4133
4134 final long origId = Binder.clearCallingIdentity();
4135 try {
4136 if (values != null) {
4137 Settings.System.clearConfiguration(values);
4138 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004139 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4141 return mTmpUpdateConfigurationResult.changes != 0;
4142 } finally {
4143 Binder.restoreCallingIdentity(origId);
4144 }
4145 }
4146 }
4147
4148 @Override
4149 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004150 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151
4152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004153 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004155 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 }
4157
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004159 final Message msg = PooledLambda.obtainMessage(
4160 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4161 DEFAULT_DISPLAY);
4162 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 }
4164
4165 final long origId = Binder.clearCallingIdentity();
4166 try {
4167 if (values != null) {
4168 Settings.System.clearConfiguration(values);
4169 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004170 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004171 UserHandle.USER_NULL, false /* deferResume */,
4172 mTmpUpdateConfigurationResult);
4173 return mTmpUpdateConfigurationResult.changes != 0;
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177 }
4178 }
4179
4180 @Override
4181 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4182 CharSequence message) {
4183 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004184 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4186 }
4187 final long callingId = Binder.clearCallingIdentity();
4188 try {
4189 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004190 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004191 }
4192 } finally {
4193 Binder.restoreCallingIdentity(callingId);
4194 }
4195 }
4196
4197 @Override
4198 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004199 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 "cancelTaskWindowTransition()");
4201 final long ident = Binder.clearCallingIdentity();
4202 try {
4203 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004204 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 MATCH_TASK_IN_STACKS_ONLY);
4206 if (task == null) {
4207 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4208 return;
4209 }
4210 task.cancelWindowTransition();
4211 }
4212 } finally {
4213 Binder.restoreCallingIdentity(ident);
4214 }
4215 }
4216
4217 @Override
4218 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004219 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 final long ident = Binder.clearCallingIdentity();
4221 try {
4222 final TaskRecord task;
4223 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004224 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4226 if (task == null) {
4227 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4228 return null;
4229 }
4230 }
4231 // Don't call this while holding the lock as this operation might hit the disk.
4232 return task.getSnapshot(reducedResolution);
4233 } finally {
4234 Binder.restoreCallingIdentity(ident);
4235 }
4236 }
4237
4238 @Override
4239 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4240 synchronized (mGlobalLock) {
4241 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4242 if (r == null) {
4243 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4244 + token);
4245 return;
4246 }
4247 final long origId = Binder.clearCallingIdentity();
4248 try {
4249 r.setDisablePreviewScreenshots(disable);
4250 } finally {
4251 Binder.restoreCallingIdentity(origId);
4252 }
4253 }
4254 }
4255
4256 /** Return the user id of the last resumed activity. */
4257 @Override
4258 public @UserIdInt
4259 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004260 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4262 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004263 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004264 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004266 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004267 }
4268 }
4269
4270 @Override
4271 public void updateLockTaskFeatures(int userId, int flags) {
4272 final int callingUid = Binder.getCallingUid();
4273 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004274 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 "updateLockTaskFeatures()");
4276 }
4277 synchronized (mGlobalLock) {
4278 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4279 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004280 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 }
4282 }
4283
4284 @Override
4285 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4286 synchronized (mGlobalLock) {
4287 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4288 if (r == null) {
4289 return;
4290 }
4291 final long origId = Binder.clearCallingIdentity();
4292 try {
4293 r.setShowWhenLocked(showWhenLocked);
4294 } finally {
4295 Binder.restoreCallingIdentity(origId);
4296 }
4297 }
4298 }
4299
4300 @Override
4301 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4302 synchronized (mGlobalLock) {
4303 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4304 if (r == null) {
4305 return;
4306 }
4307 final long origId = Binder.clearCallingIdentity();
4308 try {
4309 r.setTurnScreenOn(turnScreenOn);
4310 } finally {
4311 Binder.restoreCallingIdentity(origId);
4312 }
4313 }
4314 }
4315
4316 @Override
4317 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004318 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 "registerRemoteAnimations");
4320 definition.setCallingPid(Binder.getCallingPid());
4321 synchronized (mGlobalLock) {
4322 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4323 if (r == null) {
4324 return;
4325 }
4326 final long origId = Binder.clearCallingIdentity();
4327 try {
4328 r.registerRemoteAnimations(definition);
4329 } finally {
4330 Binder.restoreCallingIdentity(origId);
4331 }
4332 }
4333 }
4334
4335 @Override
4336 public void registerRemoteAnimationForNextActivityStart(String packageName,
4337 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004338 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 "registerRemoteAnimationForNextActivityStart");
4340 adapter.setCallingPid(Binder.getCallingPid());
4341 synchronized (mGlobalLock) {
4342 final long origId = Binder.clearCallingIdentity();
4343 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004344 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 packageName, adapter);
4346 } finally {
4347 Binder.restoreCallingIdentity(origId);
4348 }
4349 }
4350 }
4351
4352 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4353 @Override
4354 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4355 synchronized (mGlobalLock) {
4356 final long origId = Binder.clearCallingIdentity();
4357 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004358 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 } finally {
4360 Binder.restoreCallingIdentity(origId);
4361 }
4362 }
4363 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004364
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004365 @Override
4366 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004368 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004369 final int pid = Binder.getCallingPid();
4370 final WindowProcessController wpc = mPidMap.get(pid);
4371 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 }
4373 }
4374
4375 @Override
4376 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 != PERMISSION_GRANTED) {
4379 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4380 + Binder.getCallingPid()
4381 + ", uid=" + Binder.getCallingUid()
4382 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4383 Slog.w(TAG, msg);
4384 throw new SecurityException(msg);
4385 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004387 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004388 final int pid = Binder.getCallingPid();
4389 final WindowProcessController proc = mPidMap.get(pid);
4390 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004391 }
4392 }
4393
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004394 @Override
4395 public void stopAppSwitches() {
4396 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4397 synchronized (mGlobalLock) {
4398 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4399 mDidAppSwitch = false;
4400 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4401 }
4402 }
4403
4404 @Override
4405 public void resumeAppSwitches() {
4406 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4407 synchronized (mGlobalLock) {
4408 // Note that we don't execute any pending app switches... we will
4409 // let those wait until either the timeout, or the next start
4410 // activity request.
4411 mAppSwitchesAllowedTime = 0;
4412 }
4413 }
4414
4415 void onStartActivitySetDidAppSwitch() {
4416 if (mDidAppSwitch) {
4417 // This is the second allowed switch since we stopped switches, so now just generally
4418 // allow switches. Use case:
4419 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4420 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4421 // anyone to switch again).
4422 mAppSwitchesAllowedTime = 0;
4423 } else {
4424 mDidAppSwitch = true;
4425 }
4426 }
4427
4428 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004429 boolean shouldDisableNonVrUiLocked() {
4430 return mVrController.shouldDisableNonVrUiLocked();
4431 }
4432
Wale Ogunwale53783742018-09-16 10:21:51 -07004433 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004434 // VR apps are expected to run in a main display. If an app is turning on VR for
4435 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4436 // fullscreen stack before enabling VR Mode.
4437 // TODO: The goal of this code is to keep the VR app on the main display. When the
4438 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4439 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4440 // option would be a better choice here.
4441 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4442 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4443 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004444 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004445 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004446 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004447 }
4448 mH.post(() -> {
4449 if (!mVrController.onVrModeChanged(r)) {
4450 return;
4451 }
4452 synchronized (mGlobalLock) {
4453 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4454 mWindowManager.disableNonVrUi(disableNonVrUi);
4455 if (disableNonVrUi) {
4456 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4457 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004458 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004459 }
4460 }
4461 });
4462 }
4463
Wale Ogunwale53783742018-09-16 10:21:51 -07004464 @Override
4465 public int getPackageScreenCompatMode(String packageName) {
4466 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4467 synchronized (mGlobalLock) {
4468 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4469 }
4470 }
4471
4472 @Override
4473 public void setPackageScreenCompatMode(String packageName, int mode) {
4474 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4475 "setPackageScreenCompatMode");
4476 synchronized (mGlobalLock) {
4477 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4478 }
4479 }
4480
4481 @Override
4482 public boolean getPackageAskScreenCompat(String packageName) {
4483 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4484 synchronized (mGlobalLock) {
4485 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4486 }
4487 }
4488
4489 @Override
4490 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4491 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4492 "setPackageAskScreenCompat");
4493 synchronized (mGlobalLock) {
4494 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4495 }
4496 }
4497
Wale Ogunwale64258362018-10-16 15:13:37 -07004498 public static String relaunchReasonToString(int relaunchReason) {
4499 switch (relaunchReason) {
4500 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4501 return "window_resize";
4502 case RELAUNCH_REASON_FREE_RESIZE:
4503 return "free_resize";
4504 default:
4505 return null;
4506 }
4507 }
4508
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004509 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004510 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004511 }
4512
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004513 /** Pokes the task persister. */
4514 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4515 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4516 }
4517
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004518 boolean isKeyguardLocked() {
4519 return mKeyguardController.isKeyguardLocked();
4520 }
4521
Garfield Tan01548632018-11-27 10:15:48 -08004522 /**
4523 * Clears launch params for the given package.
4524 * @param packageNames the names of the packages of which the launch params are to be cleared
4525 */
4526 @Override
4527 public void clearLaunchParamsForPackages(List<String> packageNames) {
4528 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4529 "clearLaunchParamsForPackages");
4530 synchronized (mGlobalLock) {
4531 for (int i = 0; i < packageNames.size(); ++i) {
4532 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4533 }
4534 }
4535 }
4536
Wale Ogunwale31913b52018-10-13 08:29:31 -07004537 void dumpLastANRLocked(PrintWriter pw) {
4538 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4539 if (mLastANRState == null) {
4540 pw.println(" <no ANR has occurred since boot>");
4541 } else {
4542 pw.println(mLastANRState);
4543 }
4544 }
4545
4546 void dumpLastANRTracesLocked(PrintWriter pw) {
4547 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4548
4549 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4550 if (ArrayUtils.isEmpty(files)) {
4551 pw.println(" <no ANR has occurred since boot>");
4552 return;
4553 }
4554 // Find the latest file.
4555 File latest = null;
4556 for (File f : files) {
4557 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4558 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004559 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004560 }
4561 pw.print("File: ");
4562 pw.print(latest.getName());
4563 pw.println();
4564 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4565 String line;
4566 while ((line = in.readLine()) != null) {
4567 pw.println(line);
4568 }
4569 } catch (IOException e) {
4570 pw.print("Unable to read: ");
4571 pw.print(e);
4572 pw.println();
4573 }
4574 }
4575
4576 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4577 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4578 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4579 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4580 }
4581
4582 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4583 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4584 pw.println(header);
4585
Wale Ogunwaled32da472018-11-16 07:19:28 -08004586 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004587 dumpPackage);
4588 boolean needSep = printedAnything;
4589
4590 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004591 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004592 " ResumedActivity: ");
4593 if (printed) {
4594 printedAnything = true;
4595 needSep = false;
4596 }
4597
4598 if (dumpPackage == null) {
4599 if (needSep) {
4600 pw.println();
4601 }
4602 printedAnything = true;
4603 mStackSupervisor.dump(pw, " ");
4604 }
4605
4606 if (!printedAnything) {
4607 pw.println(" (nothing)");
4608 }
4609 }
4610
4611 void dumpActivityContainersLocked(PrintWriter pw) {
4612 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004613 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004614 pw.println(" ");
4615 }
4616
4617 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4618 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4619 getActivityStartController().dump(pw, "", dumpPackage);
4620 }
4621
4622 /**
4623 * There are three things that cmd can be:
4624 * - a flattened component name that matches an existing activity
4625 * - the cmd arg isn't the flattened component name of an existing activity:
4626 * dump all activity whose component contains the cmd as a substring
4627 * - A hex number of the ActivityRecord object instance.
4628 *
4629 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4630 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4631 */
4632 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4633 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4634 ArrayList<ActivityRecord> activities;
4635
4636 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004637 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004638 dumpFocusedStackOnly);
4639 }
4640
4641 if (activities.size() <= 0) {
4642 return false;
4643 }
4644
4645 String[] newArgs = new String[args.length - opti];
4646 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4647
4648 TaskRecord lastTask = null;
4649 boolean needSep = false;
4650 for (int i = activities.size() - 1; i >= 0; i--) {
4651 ActivityRecord r = activities.get(i);
4652 if (needSep) {
4653 pw.println();
4654 }
4655 needSep = true;
4656 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004657 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004658 if (lastTask != task) {
4659 lastTask = task;
4660 pw.print("TASK "); pw.print(lastTask.affinity);
4661 pw.print(" id="); pw.print(lastTask.taskId);
4662 pw.print(" userId="); pw.println(lastTask.userId);
4663 if (dumpAll) {
4664 lastTask.dump(pw, " ");
4665 }
4666 }
4667 }
4668 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4669 }
4670 return true;
4671 }
4672
4673 /**
4674 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4675 * there is a thread associated with the activity.
4676 */
4677 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4678 final ActivityRecord r, String[] args, boolean dumpAll) {
4679 String innerPrefix = prefix + " ";
4680 synchronized (mGlobalLock) {
4681 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4682 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4683 pw.print(" pid=");
4684 if (r.hasProcess()) pw.println(r.app.getPid());
4685 else pw.println("(not running)");
4686 if (dumpAll) {
4687 r.dump(pw, innerPrefix);
4688 }
4689 }
4690 if (r.attachedToProcess()) {
4691 // flush anything that is already in the PrintWriter since the thread is going
4692 // to write to the file descriptor directly
4693 pw.flush();
4694 try {
4695 TransferPipe tp = new TransferPipe();
4696 try {
4697 r.app.getThread().dumpActivity(tp.getWriteFd(),
4698 r.appToken, innerPrefix, args);
4699 tp.go(fd);
4700 } finally {
4701 tp.kill();
4702 }
4703 } catch (IOException e) {
4704 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4705 } catch (RemoteException e) {
4706 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4707 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004708 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 }
4710
Wale Ogunwalef6733932018-06-27 05:14:34 -07004711 void writeSleepStateToProto(ProtoOutputStream proto) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004712 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004713 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4714 st.toString());
4715 }
4716
4717 if (mRunningVoice != null) {
4718 final long vrToken = proto.start(
4719 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4720 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4721 mRunningVoice.toString());
4722 mVoiceWakeLock.writeToProto(
4723 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4724 proto.end(vrToken);
4725 }
4726
4727 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4728 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4729 mShuttingDown);
4730 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004733 int getCurrentUserId() {
4734 return mAmInternal.getCurrentUserId();
4735 }
4736
4737 private void enforceNotIsolatedCaller(String caller) {
4738 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4739 throw new SecurityException("Isolated process not allowed to call " + caller);
4740 }
4741 }
4742
Wale Ogunwalef6733932018-06-27 05:14:34 -07004743 public Configuration getConfiguration() {
4744 Configuration ci;
4745 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004746 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004747 ci.userSetLocale = false;
4748 }
4749 return ci;
4750 }
4751
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004752 /**
4753 * Current global configuration information. Contains general settings for the entire system,
4754 * also corresponds to the merged configuration of the default display.
4755 */
4756 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004757 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004758 }
4759
4760 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4761 boolean initLocale) {
4762 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4763 }
4764
4765 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4766 boolean initLocale, boolean deferResume) {
4767 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4768 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4769 UserHandle.USER_NULL, deferResume);
4770 }
4771
Wale Ogunwale59507092018-10-29 09:00:30 -07004772 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004773 final long origId = Binder.clearCallingIdentity();
4774 try {
4775 synchronized (mGlobalLock) {
4776 updateConfigurationLocked(values, null, false, true, userId,
4777 false /* deferResume */);
4778 }
4779 } finally {
4780 Binder.restoreCallingIdentity(origId);
4781 }
4782 }
4783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4785 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4786 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4787 deferResume, null /* result */);
4788 }
4789
4790 /**
4791 * Do either or both things: (1) change the current configuration, and (2)
4792 * make sure the given activity is running with the (now) current
4793 * configuration. Returns true if the activity has been left running, or
4794 * false if <var>starting</var> is being destroyed to match the new
4795 * configuration.
4796 *
4797 * @param userId is only used when persistent parameter is set to true to persist configuration
4798 * for that particular user
4799 */
4800 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4801 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4802 ActivityTaskManagerService.UpdateConfigurationResult result) {
4803 int changes = 0;
4804 boolean kept = true;
4805
4806 if (mWindowManager != null) {
4807 mWindowManager.deferSurfaceLayout();
4808 }
4809 try {
4810 if (values != null) {
4811 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4812 deferResume);
4813 }
4814
4815 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4816 } finally {
4817 if (mWindowManager != null) {
4818 mWindowManager.continueSurfaceLayout();
4819 }
4820 }
4821
4822 if (result != null) {
4823 result.changes = changes;
4824 result.activityRelaunched = !kept;
4825 }
4826 return kept;
4827 }
4828
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004829 /** Update default (global) configuration and notify listeners about changes. */
4830 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4831 boolean persistent, int userId, boolean deferResume) {
4832 mTempConfig.setTo(getGlobalConfiguration());
4833 final int changes = mTempConfig.updateFrom(values);
4834 if (changes == 0) {
4835 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4836 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4837 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4838 // (even if there are no actual changes) to unfreeze the window.
4839 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4840 return 0;
4841 }
4842
4843 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4844 "Updating global configuration to: " + values);
4845
4846 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4847 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4848 values.colorMode,
4849 values.densityDpi,
4850 values.fontScale,
4851 values.hardKeyboardHidden,
4852 values.keyboard,
4853 values.keyboardHidden,
4854 values.mcc,
4855 values.mnc,
4856 values.navigation,
4857 values.navigationHidden,
4858 values.orientation,
4859 values.screenHeightDp,
4860 values.screenLayout,
4861 values.screenWidthDp,
4862 values.smallestScreenWidthDp,
4863 values.touchscreen,
4864 values.uiMode);
4865
4866
4867 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4868 final LocaleList locales = values.getLocales();
4869 int bestLocaleIndex = 0;
4870 if (locales.size() > 1) {
4871 if (mSupportedSystemLocales == null) {
4872 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4873 }
4874 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4875 }
4876 SystemProperties.set("persist.sys.locale",
4877 locales.get(bestLocaleIndex).toLanguageTag());
4878 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004879
4880 final Message m = PooledLambda.obtainMessage(
4881 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4882 locales.get(bestLocaleIndex));
4883 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004884 }
4885
Yunfan Chen75157d72018-07-27 14:47:21 +09004886 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004887
4888 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004889 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890
4891 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4892 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004893 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004894
4895 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004896 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897
4898 AttributeCache ac = AttributeCache.instance();
4899 if (ac != null) {
4900 ac.updateConfiguration(mTempConfig);
4901 }
4902
4903 // Make sure all resources in our process are updated right now, so that anyone who is going
4904 // to retrieve resource values after we return will be sure to get the new ones. This is
4905 // especially important during boot, where the first config change needs to guarantee all
4906 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004907 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004908
4909 // We need another copy of global config because we're scheduling some calls instead of
4910 // running them in place. We need to be sure that object we send will be handled unchanged.
4911 final Configuration configCopy = new Configuration(mTempConfig);
4912 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004913 final Message msg = PooledLambda.obtainMessage(
4914 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4915 this, userId, configCopy);
4916 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004917 }
4918
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004919 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004920 final int pid = mPidMap.keyAt(i);
4921 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004922 if (DEBUG_CONFIGURATION) {
4923 Slog.v(TAG_CONFIGURATION, "Update process config of "
4924 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004925 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004926 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004927 }
4928
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004929 final Message msg = PooledLambda.obtainMessage(
4930 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4931 mAmInternal, changes, initLocale);
4932 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004933
4934 // Override configuration of the default display duplicates global config, so we need to
4935 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004936 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004937 DEFAULT_DISPLAY);
4938
4939 return changes;
4940 }
4941
4942 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4943 boolean deferResume, int displayId) {
4944 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4945 displayId, null /* result */);
4946 }
4947
4948 /**
4949 * Updates override configuration specific for the selected display. If no config is provided,
4950 * new one will be computed in WM based on current display info.
4951 */
4952 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4953 ActivityRecord starting, boolean deferResume, int displayId,
4954 ActivityTaskManagerService.UpdateConfigurationResult result) {
4955 int changes = 0;
4956 boolean kept = true;
4957
4958 if (mWindowManager != null) {
4959 mWindowManager.deferSurfaceLayout();
4960 }
4961 try {
4962 if (values != null) {
4963 if (displayId == DEFAULT_DISPLAY) {
4964 // Override configuration of the default display duplicates global config, so
4965 // we're calling global config update instead for default display. It will also
4966 // apply the correct override config.
4967 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4968 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4969 } else {
4970 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4971 }
4972 }
4973
4974 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4975 } finally {
4976 if (mWindowManager != null) {
4977 mWindowManager.continueSurfaceLayout();
4978 }
4979 }
4980
4981 if (result != null) {
4982 result.changes = changes;
4983 result.activityRelaunched = !kept;
4984 }
4985 return kept;
4986 }
4987
4988 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4989 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004990 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004991 final int changes = mTempConfig.updateFrom(values);
4992 if (changes != 0) {
4993 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4994 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08004995 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004996
4997 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4998 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004999 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005000
Wale Ogunwale5c918702018-10-18 11:06:33 -07005001 // Post message to start process to avoid possible deadlock of calling into AMS with
5002 // the ATMS lock held.
5003 final Message msg = PooledLambda.obtainMessage(
5004 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5005 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5006 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005007 }
5008 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005009 return changes;
5010 }
5011
Wale Ogunwalef6733932018-06-27 05:14:34 -07005012 private void updateEventDispatchingLocked(boolean booted) {
5013 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5014 }
5015
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005016 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5017 final ContentResolver resolver = mContext.getContentResolver();
5018 Settings.System.putConfigurationForUser(resolver, config, userId);
5019 }
5020
5021 private void sendLocaleToMountDaemonMsg(Locale l) {
5022 try {
5023 IBinder service = ServiceManager.getService("mount");
5024 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5025 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5026 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5027 } catch (RemoteException e) {
5028 Log.e(TAG, "Error storing locale for decryption UI", e);
5029 }
5030 }
5031
Alison Cichowlas3e340502018-08-07 17:15:01 -04005032 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5033 mStartActivitySources.remove(permissionToken);
5034 mExpiredStartAsCallerTokens.add(permissionToken);
5035 }
5036
5037 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5038 mExpiredStartAsCallerTokens.remove(permissionToken);
5039 }
5040
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005041 boolean isActivityStartsLoggingEnabled() {
5042 return mAmInternal.isActivityStartsLoggingEnabled();
5043 }
5044
Michal Karpinski8596ded2018-11-14 14:43:48 +00005045 boolean isBackgroundActivityStartsEnabled() {
5046 return mAmInternal.isBackgroundActivityStartsEnabled();
5047 }
5048
Wale Ogunwalef6733932018-06-27 05:14:34 -07005049 void enableScreenAfterBoot(boolean booted) {
5050 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5051 SystemClock.uptimeMillis());
5052 mWindowManager.enableScreenAfterBoot();
5053
5054 synchronized (mGlobalLock) {
5055 updateEventDispatchingLocked(booted);
5056 }
5057 }
5058
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005059 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5060 if (r == null || !r.hasProcess()) {
5061 return KEY_DISPATCHING_TIMEOUT_MS;
5062 }
5063 return getInputDispatchingTimeoutLocked(r.app);
5064 }
5065
5066 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005067 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005068 }
5069
Wale Ogunwalef6733932018-06-27 05:14:34 -07005070 /**
5071 * Decide based on the configuration whether we should show the ANR,
5072 * crash, etc dialogs. The idea is that if there is no affordance to
5073 * press the on-screen buttons, or the user experience would be more
5074 * greatly impacted than the crash itself, we shouldn't show the dialog.
5075 *
5076 * A thought: SystemUI might also want to get told about this, the Power
5077 * dialog / global actions also might want different behaviors.
5078 */
5079 private void updateShouldShowDialogsLocked(Configuration config) {
5080 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5081 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5082 && config.navigation == Configuration.NAVIGATION_NONAV);
5083 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5084 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5085 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5086 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5087 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5088 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5089 HIDE_ERROR_DIALOGS, 0) != 0;
5090 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5091 }
5092
5093 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5094 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5095 FONT_SCALE, 1.0f, userId);
5096
5097 synchronized (this) {
5098 if (getGlobalConfiguration().fontScale == scaleFactor) {
5099 return;
5100 }
5101
5102 final Configuration configuration
5103 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5104 configuration.fontScale = scaleFactor;
5105 updatePersistentConfiguration(configuration, userId);
5106 }
5107 }
5108
5109 // Actually is sleeping or shutting down or whatever else in the future
5110 // is an inactive state.
5111 boolean isSleepingOrShuttingDownLocked() {
5112 return isSleepingLocked() || mShuttingDown;
5113 }
5114
5115 boolean isSleepingLocked() {
5116 return mSleeping;
5117 }
5118
Riddle Hsu16567132018-08-16 21:37:47 +08005119 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005120 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005121 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005122 if (task.isActivityTypeStandard()) {
5123 if (mCurAppTimeTracker != r.appTimeTracker) {
5124 // We are switching app tracking. Complete the current one.
5125 if (mCurAppTimeTracker != null) {
5126 mCurAppTimeTracker.stop();
5127 mH.obtainMessage(
5128 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005129 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005130 mCurAppTimeTracker = null;
5131 }
5132 if (r.appTimeTracker != null) {
5133 mCurAppTimeTracker = r.appTimeTracker;
5134 startTimeTrackingFocusedActivityLocked();
5135 }
5136 } else {
5137 startTimeTrackingFocusedActivityLocked();
5138 }
5139 } else {
5140 r.appTimeTracker = null;
5141 }
5142 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5143 // TODO: Probably not, because we don't want to resume voice on switching
5144 // back to this activity
5145 if (task.voiceInteractor != null) {
5146 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5147 } else {
5148 finishRunningVoiceLocked();
5149
5150 if (mLastResumedActivity != null) {
5151 final IVoiceInteractionSession session;
5152
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005153 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005154 if (lastResumedActivityTask != null
5155 && lastResumedActivityTask.voiceSession != null) {
5156 session = lastResumedActivityTask.voiceSession;
5157 } else {
5158 session = mLastResumedActivity.voiceSession;
5159 }
5160
5161 if (session != null) {
5162 // We had been in a voice interaction session, but now focused has
5163 // move to something different. Just finish the session, we can't
5164 // return to it and retain the proper state and synchronization with
5165 // the voice interaction service.
5166 finishVoiceTask(session);
5167 }
5168 }
5169 }
5170
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005171 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5172 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005173 }
5174 updateResumedAppTrace(r);
5175 mLastResumedActivity = r;
5176
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005177 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005178
5179 applyUpdateLockStateLocked(r);
5180 applyUpdateVrModeLocked(r);
5181
5182 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005183 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005184 r == null ? "NULL" : r.shortComponentName,
5185 reason);
5186 }
5187
5188 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5189 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005190 final ActivityTaskManagerInternal.SleepToken token =
5191 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005192 updateSleepIfNeededLocked();
5193 return token;
5194 }
5195 }
5196
5197 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005198 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005199 final boolean wasSleeping = mSleeping;
5200 boolean updateOomAdj = false;
5201
5202 if (!shouldSleep) {
5203 // If wasSleeping is true, we need to wake up activity manager state from when
5204 // we started sleeping. In either case, we need to apply the sleep tokens, which
5205 // will wake up stacks or put them to sleep as appropriate.
5206 if (wasSleeping) {
5207 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005208 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5209 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005210 startTimeTrackingFocusedActivityLocked();
5211 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5212 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5213 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005214 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005215 if (wasSleeping) {
5216 updateOomAdj = true;
5217 }
5218 } else if (!mSleeping && shouldSleep) {
5219 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005220 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5221 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005222 if (mCurAppTimeTracker != null) {
5223 mCurAppTimeTracker.stop();
5224 }
5225 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5226 mStackSupervisor.goingToSleepLocked();
5227 updateResumedAppTrace(null /* resumed */);
5228 updateOomAdj = true;
5229 }
5230 if (updateOomAdj) {
5231 mH.post(mAmInternal::updateOomAdj);
5232 }
5233 }
5234
5235 void updateOomAdj() {
5236 mH.post(mAmInternal::updateOomAdj);
5237 }
5238
Wale Ogunwale53783742018-09-16 10:21:51 -07005239 void updateCpuStats() {
5240 mH.post(mAmInternal::updateCpuStats);
5241 }
5242
5243 void updateUsageStats(ActivityRecord component, boolean resumed) {
5244 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005245 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5246 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005247 mH.sendMessage(m);
5248 }
5249
5250 void setBooting(boolean booting) {
5251 mAmInternal.setBooting(booting);
5252 }
5253
5254 boolean isBooting() {
5255 return mAmInternal.isBooting();
5256 }
5257
5258 void setBooted(boolean booted) {
5259 mAmInternal.setBooted(booted);
5260 }
5261
5262 boolean isBooted() {
5263 return mAmInternal.isBooted();
5264 }
5265
5266 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5267 mH.post(() -> {
5268 if (finishBooting) {
5269 mAmInternal.finishBooting();
5270 }
5271 if (enableScreen) {
5272 mInternal.enableScreenAfterBoot(isBooted());
5273 }
5274 });
5275 }
5276
5277 void setHeavyWeightProcess(ActivityRecord root) {
5278 mHeavyWeightProcess = root.app;
5279 final Message m = PooledLambda.obtainMessage(
5280 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005281 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005282 mH.sendMessage(m);
5283 }
5284
5285 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5286 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5287 return;
5288 }
5289
5290 mHeavyWeightProcess = null;
5291 final Message m = PooledLambda.obtainMessage(
5292 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5293 proc.mUserId);
5294 mH.sendMessage(m);
5295 }
5296
5297 private void cancelHeavyWeightProcessNotification(int userId) {
5298 final INotificationManager inm = NotificationManager.getService();
5299 if (inm == null) {
5300 return;
5301 }
5302 try {
5303 inm.cancelNotificationWithTag("android", null,
5304 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5305 } catch (RuntimeException e) {
5306 Slog.w(TAG, "Error canceling notification for service", e);
5307 } catch (RemoteException e) {
5308 }
5309
5310 }
5311
5312 private void postHeavyWeightProcessNotification(
5313 WindowProcessController proc, Intent intent, int userId) {
5314 if (proc == null) {
5315 return;
5316 }
5317
5318 final INotificationManager inm = NotificationManager.getService();
5319 if (inm == null) {
5320 return;
5321 }
5322
5323 try {
5324 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5325 String text = mContext.getString(R.string.heavy_weight_notification,
5326 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5327 Notification notification =
5328 new Notification.Builder(context,
5329 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5330 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5331 .setWhen(0)
5332 .setOngoing(true)
5333 .setTicker(text)
5334 .setColor(mContext.getColor(
5335 com.android.internal.R.color.system_notification_accent_color))
5336 .setContentTitle(text)
5337 .setContentText(
5338 mContext.getText(R.string.heavy_weight_notification_detail))
5339 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5340 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5341 new UserHandle(userId)))
5342 .build();
5343 try {
5344 inm.enqueueNotificationWithTag("android", "android", null,
5345 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5346 } catch (RuntimeException e) {
5347 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5348 } catch (RemoteException e) {
5349 }
5350 } catch (PackageManager.NameNotFoundException e) {
5351 Slog.w(TAG, "Unable to create context for heavy notification", e);
5352 }
5353
5354 }
5355
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005356 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5357 IBinder token, String resultWho, int requestCode, Intent[] intents,
5358 String[] resolvedTypes, int flags, Bundle bOptions) {
5359
5360 ActivityRecord activity = null;
5361 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5362 activity = ActivityRecord.isInStackLocked(token);
5363 if (activity == null) {
5364 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5365 return null;
5366 }
5367 if (activity.finishing) {
5368 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5369 return null;
5370 }
5371 }
5372
5373 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5374 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5375 bOptions);
5376 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5377 if (noCreate) {
5378 return rec;
5379 }
5380 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5381 if (activity.pendingResults == null) {
5382 activity.pendingResults = new HashSet<>();
5383 }
5384 activity.pendingResults.add(rec.ref);
5385 }
5386 return rec;
5387 }
5388
Andrii Kulian52d255c2018-07-13 11:32:19 -07005389 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005390 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005391 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5393 mCurAppTimeTracker.start(resumedActivity.packageName);
5394 }
5395 }
5396
5397 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5398 if (mTracedResumedActivity != null) {
5399 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5400 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5401 }
5402 if (resumed != null) {
5403 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5404 constructResumedTraceName(resumed.packageName), 0);
5405 }
5406 mTracedResumedActivity = resumed;
5407 }
5408
5409 private String constructResumedTraceName(String packageName) {
5410 return "focused app: " + packageName;
5411 }
5412
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005413 /** Applies latest configuration and/or visibility updates if needed. */
5414 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5415 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005416 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005417 // mainStack is null during startup.
5418 if (mainStack != null) {
5419 if (changes != 0 && starting == null) {
5420 // If the configuration changed, and the caller is not already
5421 // in the process of starting an activity, then find the top
5422 // activity to check if its configuration needs to change.
5423 starting = mainStack.topRunningActivityLocked();
5424 }
5425
5426 if (starting != null) {
5427 kept = starting.ensureActivityConfiguration(changes,
5428 false /* preserveWindow */);
5429 // And we need to make sure at this point that all other activities
5430 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005431 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005432 !PRESERVE_WINDOWS);
5433 }
5434 }
5435
5436 return kept;
5437 }
5438
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005439 void scheduleAppGcsLocked() {
5440 mH.post(() -> mAmInternal.scheduleAppGcs());
5441 }
5442
Wale Ogunwale53783742018-09-16 10:21:51 -07005443 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5444 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5445 }
5446
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005447 /**
5448 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5449 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5450 * on demand.
5451 */
5452 IPackageManager getPackageManager() {
5453 return AppGlobals.getPackageManager();
5454 }
5455
5456 PackageManagerInternal getPackageManagerInternalLocked() {
5457 if (mPmInternal == null) {
5458 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5459 }
5460 return mPmInternal;
5461 }
5462
Wale Ogunwale008163e2018-07-23 23:11:08 -07005463 AppWarnings getAppWarningsLocked() {
5464 return mAppWarnings;
5465 }
5466
Wale Ogunwale214f3482018-10-04 11:00:47 -07005467 Intent getHomeIntent() {
5468 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5469 intent.setComponent(mTopComponent);
5470 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5471 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5472 intent.addCategory(Intent.CATEGORY_HOME);
5473 }
5474 return intent;
5475 }
5476
Wale Ogunwale214f3482018-10-04 11:00:47 -07005477 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5478 if (info == null) return null;
5479 ApplicationInfo newInfo = new ApplicationInfo(info);
5480 newInfo.initForUser(userId);
5481 return newInfo;
5482 }
5483
Wale Ogunwale9c103022018-10-18 07:44:54 -07005484 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005485 if (uid == SYSTEM_UID) {
5486 // The system gets to run in any process. If there are multiple processes with the same
5487 // uid, just pick the first (this should never happen).
5488 final SparseArray<WindowProcessController> procs =
5489 mProcessNames.getMap().get(processName);
5490 if (procs == null) return null;
5491 final int procCount = procs.size();
5492 for (int i = 0; i < procCount; i++) {
5493 final int procUid = procs.keyAt(i);
5494 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5495 // Don't use an app process or different user process for system component.
5496 continue;
5497 }
5498 return procs.valueAt(i);
5499 }
5500 }
5501
5502 return mProcessNames.get(processName, uid);
5503 }
5504
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005505 WindowProcessController getProcessController(IApplicationThread thread) {
5506 if (thread == null) {
5507 return null;
5508 }
5509
5510 final IBinder threadBinder = thread.asBinder();
5511 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5512 for (int i = pmap.size()-1; i >= 0; i--) {
5513 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5514 for (int j = procs.size() - 1; j >= 0; j--) {
5515 final WindowProcessController proc = procs.valueAt(j);
5516 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5517 return proc;
5518 }
5519 }
5520 }
5521
5522 return null;
5523 }
5524
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005525 int getUidStateLocked(int uid) {
5526 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5527 }
5528
Wale Ogunwale9de19442018-10-18 19:05:03 -07005529 /**
5530 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5531 * the whitelist
5532 */
5533 String getPendingTempWhitelistTagForUidLocked(int uid) {
5534 return mPendingTempWhitelist.get(uid);
5535 }
5536
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005537 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5538 if (true || Build.IS_USER) {
5539 return;
5540 }
5541
5542 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5543 StrictMode.allowThreadDiskWrites();
5544 try {
5545 File tracesDir = new File("/data/anr");
5546 File tracesFile = null;
5547 try {
5548 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5549
5550 StringBuilder sb = new StringBuilder();
5551 Time tobj = new Time();
5552 tobj.set(System.currentTimeMillis());
5553 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5554 sb.append(": ");
5555 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5556 sb.append(" since ");
5557 sb.append(msg);
5558 FileOutputStream fos = new FileOutputStream(tracesFile);
5559 fos.write(sb.toString().getBytes());
5560 if (app == null) {
5561 fos.write("\n*** No application process!".getBytes());
5562 }
5563 fos.close();
5564 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5565 } catch (IOException e) {
5566 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5567 return;
5568 }
5569
5570 if (app != null && app.getPid() > 0) {
5571 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5572 firstPids.add(app.getPid());
5573 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5574 }
5575
5576 File lastTracesFile = null;
5577 File curTracesFile = null;
5578 for (int i=9; i>=0; i--) {
5579 String name = String.format(Locale.US, "slow%02d.txt", i);
5580 curTracesFile = new File(tracesDir, name);
5581 if (curTracesFile.exists()) {
5582 if (lastTracesFile != null) {
5583 curTracesFile.renameTo(lastTracesFile);
5584 } else {
5585 curTracesFile.delete();
5586 }
5587 }
5588 lastTracesFile = curTracesFile;
5589 }
5590 tracesFile.renameTo(curTracesFile);
5591 } finally {
5592 StrictMode.setThreadPolicy(oldPolicy);
5593 }
5594 }
5595
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005596 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005598
5599
Wale Ogunwale98875612018-10-12 07:53:02 -07005600 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5601 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005602
Riddle Hsud93a6c42018-11-29 21:50:06 +08005603 H(Looper looper) {
5604 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005605 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606
5607 @Override
5608 public void handleMessage(Message msg) {
5609 switch (msg.what) {
5610 case REPORT_TIME_TRACKER_MSG: {
5611 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5612 tracker.deliverResult(mContext);
5613 } break;
5614 }
5615 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005616 }
5617
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005618 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005619 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005620
5621 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005622 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005623 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005624
5625 @Override
5626 public void handleMessage(Message msg) {
5627 switch (msg.what) {
5628 case DISMISS_DIALOG_UI_MSG: {
5629 final Dialog d = (Dialog) msg.obj;
5630 d.dismiss();
5631 break;
5632 }
5633 }
5634 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005635 }
5636
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005637 final class LocalService extends ActivityTaskManagerInternal {
5638 @Override
5639 public SleepToken acquireSleepToken(String tag, int displayId) {
5640 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005641 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005642 }
5643
5644 @Override
5645 public ComponentName getHomeActivityForUser(int userId) {
5646 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005647 final ActivityRecord homeActivity =
5648 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005649 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005650 }
5651 }
5652
5653 @Override
5654 public void onLocalVoiceInteractionStarted(IBinder activity,
5655 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5656 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005657 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005658 }
5659 }
5660
5661 @Override
5662 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5663 synchronized (mGlobalLock) {
5664 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5665 reasons, timestamp);
5666 }
5667 }
5668
5669 @Override
5670 public void notifyAppTransitionFinished() {
5671 synchronized (mGlobalLock) {
5672 mStackSupervisor.notifyAppTransitionDone();
5673 }
5674 }
5675
5676 @Override
5677 public void notifyAppTransitionCancelled() {
5678 synchronized (mGlobalLock) {
5679 mStackSupervisor.notifyAppTransitionDone();
5680 }
5681 }
5682
5683 @Override
5684 public List<IBinder> getTopVisibleActivities() {
5685 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005686 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005687 }
5688 }
5689
5690 @Override
5691 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5692 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005693 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005694 }
5695 }
5696
5697 @Override
5698 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5699 Bundle bOptions) {
5700 Preconditions.checkNotNull(intents, "intents");
5701 final String[] resolvedTypes = new String[intents.length];
5702
5703 // UID of the package on user userId.
5704 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5705 // packageUid may not be initialized.
5706 int packageUid = 0;
5707 final long ident = Binder.clearCallingIdentity();
5708
5709 try {
5710 for (int i = 0; i < intents.length; i++) {
5711 resolvedTypes[i] =
5712 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5713 }
5714
5715 packageUid = AppGlobals.getPackageManager().getPackageUid(
5716 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5717 } catch (RemoteException e) {
5718 // Shouldn't happen.
5719 } finally {
5720 Binder.restoreCallingIdentity(ident);
5721 }
5722
5723 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005724 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005725 packageUid, packageName,
5726 intents, resolvedTypes, null /* resultTo */,
5727 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005728 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005729 }
5730 }
5731
5732 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005733 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5734 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5735 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5736 synchronized (mGlobalLock) {
5737 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5738 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5739 originatingPendingIntent);
5740 }
5741 }
5742
5743 @Override
5744 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5745 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5746 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5747 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5748 PendingIntentRecord originatingPendingIntent) {
5749 synchronized (mGlobalLock) {
5750 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5751 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5752 requestCode, startFlags, options, userId, inTask, reason,
5753 validateIncomingUser, originatingPendingIntent);
5754 }
5755 }
5756
5757 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005758 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5759 Intent intent, Bundle options, int userId) {
5760 return ActivityTaskManagerService.this.startActivityAsUser(
5761 caller, callerPacakge, intent,
5762 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5763 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5764 false /*validateIncomingUser*/);
5765 }
5766
5767 @Override
lumark588a3e82018-07-20 18:53:54 +08005768 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005769 synchronized (mGlobalLock) {
5770
5771 // We might change the visibilities here, so prepare an empty app transition which
5772 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005773 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005774 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005775 if (activityDisplay == null) {
5776 return;
5777 }
5778 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005779 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005780 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005781 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005783 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005784
5785 // If there was a transition set already we don't want to interfere with it as we
5786 // might be starting it too early.
5787 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005788 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005789 }
5790 }
5791 if (callback != null) {
5792 callback.run();
5793 }
5794 }
5795
5796 @Override
5797 public void notifyKeyguardTrustedChanged() {
5798 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005799 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005800 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005801 }
5802 }
5803 }
5804
5805 /**
5806 * Called after virtual display Id is updated by
5807 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5808 * {@param vrVr2dDisplayId}.
5809 */
5810 @Override
5811 public void setVr2dDisplayId(int vr2dDisplayId) {
5812 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5813 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005814 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005815 }
5816 }
5817
5818 @Override
5819 public void setFocusedActivity(IBinder token) {
5820 synchronized (mGlobalLock) {
5821 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5822 if (r == null) {
5823 throw new IllegalArgumentException(
5824 "setFocusedActivity: No activity record matching token=" + token);
5825 }
Louis Chang19443452018-10-09 12:10:21 +08005826 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005827 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005828 }
5829 }
5830 }
5831
5832 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005833 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005834 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005835 }
5836
5837 @Override
5838 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005839 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005840 }
5841
5842 @Override
5843 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005844 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005845 }
5846
5847 @Override
5848 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5849 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5850 }
5851
5852 @Override
5853 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005854 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005855 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005856
5857 @Override
5858 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5859 synchronized (mGlobalLock) {
5860 mActiveVoiceInteractionServiceComponent = component;
5861 }
5862 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005863
5864 @Override
5865 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5866 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5867 return;
5868 }
5869 synchronized (mGlobalLock) {
5870 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5871 if (types == null) {
5872 if (uid < 0) {
5873 return;
5874 }
5875 types = new ArrayMap<>();
5876 mAllowAppSwitchUids.put(userId, types);
5877 }
5878 if (uid < 0) {
5879 types.remove(type);
5880 } else {
5881 types.put(type, uid);
5882 }
5883 }
5884 }
5885
5886 @Override
5887 public void onUserStopped(int userId) {
5888 synchronized (mGlobalLock) {
5889 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5890 mAllowAppSwitchUids.remove(userId);
5891 }
5892 }
5893
5894 @Override
5895 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5896 synchronized (mGlobalLock) {
5897 return ActivityTaskManagerService.this.isGetTasksAllowed(
5898 caller, callingPid, callingUid);
5899 }
5900 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005901
5902 @Override
5903 public void onProcessAdded(WindowProcessController proc) {
5904 synchronized (mGlobalLock) {
5905 mProcessNames.put(proc.mName, proc.mUid, proc);
5906 }
5907 }
5908
5909 @Override
5910 public void onProcessRemoved(String name, int uid) {
5911 synchronized (mGlobalLock) {
5912 mProcessNames.remove(name, uid);
5913 }
5914 }
5915
5916 @Override
5917 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5918 synchronized (mGlobalLock) {
5919 if (proc == mHomeProcess) {
5920 mHomeProcess = null;
5921 }
5922 if (proc == mPreviousProcess) {
5923 mPreviousProcess = null;
5924 }
5925 }
5926 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005927
5928 @Override
5929 public int getTopProcessState() {
5930 synchronized (mGlobalLock) {
5931 return mTopProcessState;
5932 }
5933 }
5934
5935 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005936 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5937 synchronized (mGlobalLock) {
5938 return proc == mHeavyWeightProcess;
5939 }
5940 }
5941
5942 @Override
5943 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5944 synchronized (mGlobalLock) {
5945 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5946 }
5947 }
5948
5949 @Override
5950 public void finishHeavyWeightApp() {
5951 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005952 if (mHeavyWeightProcess != null) {
5953 mHeavyWeightProcess.finishActivities();
5954 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005955 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5956 mHeavyWeightProcess);
5957 }
5958 }
5959
5960 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005961 public boolean isSleeping() {
5962 synchronized (mGlobalLock) {
5963 return isSleepingLocked();
5964 }
5965 }
5966
5967 @Override
5968 public boolean isShuttingDown() {
5969 synchronized (mGlobalLock) {
5970 return mShuttingDown;
5971 }
5972 }
5973
5974 @Override
5975 public boolean shuttingDown(boolean booted, int timeout) {
5976 synchronized (mGlobalLock) {
5977 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005978 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005979 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005980 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005981 return mStackSupervisor.shutdownLocked(timeout);
5982 }
5983 }
5984
5985 @Override
5986 public void enableScreenAfterBoot(boolean booted) {
5987 synchronized (mGlobalLock) {
5988 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5989 SystemClock.uptimeMillis());
5990 mWindowManager.enableScreenAfterBoot();
5991 updateEventDispatchingLocked(booted);
5992 }
5993 }
5994
5995 @Override
5996 public boolean showStrictModeViolationDialog() {
5997 synchronized (mGlobalLock) {
5998 return mShowDialogs && !mSleeping && !mShuttingDown;
5999 }
6000 }
6001
6002 @Override
6003 public void showSystemReadyErrorDialogsIfNeeded() {
6004 synchronized (mGlobalLock) {
6005 try {
6006 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6007 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6008 + " data partition or your device will be unstable.");
6009 mUiHandler.post(() -> {
6010 if (mShowDialogs) {
6011 AlertDialog d = new BaseErrorDialog(mUiContext);
6012 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6013 d.setCancelable(false);
6014 d.setTitle(mUiContext.getText(R.string.android_system_label));
6015 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6016 d.setButton(DialogInterface.BUTTON_POSITIVE,
6017 mUiContext.getText(R.string.ok),
6018 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6019 d.show();
6020 }
6021 });
6022 }
6023 } catch (RemoteException e) {
6024 }
6025
6026 if (!Build.isBuildConsistent()) {
6027 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6028 mUiHandler.post(() -> {
6029 if (mShowDialogs) {
6030 AlertDialog d = new BaseErrorDialog(mUiContext);
6031 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6032 d.setCancelable(false);
6033 d.setTitle(mUiContext.getText(R.string.android_system_label));
6034 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6035 d.setButton(DialogInterface.BUTTON_POSITIVE,
6036 mUiContext.getText(R.string.ok),
6037 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6038 d.show();
6039 }
6040 });
6041 }
6042 }
6043 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006044
6045 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006046 public void onProcessMapped(int pid, WindowProcessController proc) {
6047 synchronized (mGlobalLock) {
6048 mPidMap.put(pid, proc);
6049 }
6050 }
6051
6052 @Override
6053 public void onProcessUnMapped(int pid) {
6054 synchronized (mGlobalLock) {
6055 mPidMap.remove(pid);
6056 }
6057 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006058
6059 @Override
6060 public void onPackageDataCleared(String name) {
6061 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006062 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006063 mAppWarnings.onPackageDataCleared(name);
6064 }
6065 }
6066
6067 @Override
6068 public void onPackageUninstalled(String name) {
6069 synchronized (mGlobalLock) {
6070 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006071 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006072 }
6073 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006074
6075 @Override
6076 public void onPackageAdded(String name, boolean replacing) {
6077 synchronized (mGlobalLock) {
6078 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6079 }
6080 }
6081
6082 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006083 public void onPackageReplaced(ApplicationInfo aInfo) {
6084 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006085 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006086 }
6087 }
6088
6089 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006090 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6091 synchronized (mGlobalLock) {
6092 return compatibilityInfoForPackageLocked(ai);
6093 }
6094 }
6095
Yunfan Chen75157d72018-07-27 14:47:21 +09006096 /**
6097 * Set the corresponding display information for the process global configuration. To be
6098 * called when we need to show IME on a different display.
6099 *
6100 * @param pid The process id associated with the IME window.
6101 * @param displayId The ID of the display showing the IME.
6102 */
6103 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006104 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006105 if (pid == MY_PID || pid < 0) {
6106 if (DEBUG_CONFIGURATION) {
6107 Slog.w(TAG,
6108 "Trying to update display configuration for system/invalid process.");
6109 }
6110 return;
6111 }
6112 mH.post(() -> {
6113 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006114 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006115 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006116 if (activityDisplay == null) {
6117 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006118 if (DEBUG_CONFIGURATION) {
6119 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006120 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006121 }
6122 return;
6123 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006124 final WindowProcessController process = mPidMap.get(pid);
6125 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006126 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006127 Slog.w(TAG, "Trying to update display configuration for invalid "
6128 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006129 }
6130 return;
6131 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006132 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006133 }
6134 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006135
Yunfan Chen75157d72018-07-27 14:47:21 +09006136 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006137
6138 @Override
6139 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6140 int requestCode, int resultCode, Intent data) {
6141 synchronized (mGlobalLock) {
6142 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006143 if (r != null && r.getActivityStack() != null) {
6144 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6145 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006146 }
6147 }
6148 }
6149
6150 @Override
6151 public void clearPendingResultForActivity(IBinder activityToken,
6152 WeakReference<PendingIntentRecord> pir) {
6153 synchronized (mGlobalLock) {
6154 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6155 if (r != null && r.pendingResults != null) {
6156 r.pendingResults.remove(pir);
6157 }
6158 }
6159 }
6160
6161 @Override
6162 public IIntentSender getIntentSender(int type, String packageName,
6163 int callingUid, int userId, IBinder token, String resultWho,
6164 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6165 Bundle bOptions) {
6166 synchronized (mGlobalLock) {
6167 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6168 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6169 }
6170 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006171
6172 @Override
6173 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6174 synchronized (mGlobalLock) {
6175 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6176 if (r == null) {
6177 return null;
6178 }
6179 if (r.mServiceConnectionsHolder == null) {
6180 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6181 ActivityTaskManagerService.this, r);
6182 }
6183
6184 return r.mServiceConnectionsHolder;
6185 }
6186 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006187
6188 @Override
6189 public Intent getHomeIntent() {
6190 synchronized (mGlobalLock) {
6191 return ActivityTaskManagerService.this.getHomeIntent();
6192 }
6193 }
6194
6195 @Override
6196 public boolean startHomeActivity(int userId, String reason) {
6197 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006198 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006199 }
6200 }
6201
6202 @Override
6203 public boolean startHomeOnAllDisplays(int userId, String reason) {
6204 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006205 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006206 }
6207 }
6208
6209 @Override
6210 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6211 synchronized (mGlobalLock) {
6212 if (mFactoryTest == FACTORY_TEST_OFF) {
6213 return false;
6214 }
6215 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6216 && wpc.mName.equals(mTopComponent.getPackageName())) {
6217 return true;
6218 }
6219 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6220 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6221 }
6222 }
6223
6224 @Override
6225 public void updateTopComponentForFactoryTest() {
6226 synchronized (mGlobalLock) {
6227 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6228 return;
6229 }
6230 final ResolveInfo ri = mContext.getPackageManager()
6231 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6232 final CharSequence errorMsg;
6233 if (ri != null) {
6234 final ActivityInfo ai = ri.activityInfo;
6235 final ApplicationInfo app = ai.applicationInfo;
6236 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6237 mTopAction = Intent.ACTION_FACTORY_TEST;
6238 mTopData = null;
6239 mTopComponent = new ComponentName(app.packageName, ai.name);
6240 errorMsg = null;
6241 } else {
6242 errorMsg = mContext.getResources().getText(
6243 com.android.internal.R.string.factorytest_not_system);
6244 }
6245 } else {
6246 errorMsg = mContext.getResources().getText(
6247 com.android.internal.R.string.factorytest_no_action);
6248 }
6249 if (errorMsg == null) {
6250 return;
6251 }
6252
6253 mTopAction = null;
6254 mTopData = null;
6255 mTopComponent = null;
6256 mUiHandler.post(() -> {
6257 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6258 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006259 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006260 });
6261 }
6262 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006263
6264 @Override
6265 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6266 Runnable finishInstrumentationCallback) {
6267 synchronized (mGlobalLock) {
6268 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006269 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006270
6271 wpc.clearRecentTasks();
6272 wpc.clearActivities();
6273
6274 if (wpc.isInstrumenting()) {
6275 finishInstrumentationCallback.run();
6276 }
6277
6278 mWindowManager.deferSurfaceLayout();
6279 try {
6280 if (!restarting && hasVisibleActivities
Wale Ogunwaled32da472018-11-16 07:19:28 -08006281 && !mRootActivityContainer.resumeFocusedStacksTopActivities()) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006282 // If there was nothing to resume, and we are not already restarting this
6283 // process, but there is a visible activity that is hosted by the process...
6284 // then make sure all visible activities are running, taking care of
6285 // restarting this process.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006286 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006287 }
6288 } finally {
6289 mWindowManager.continueSurfaceLayout();
6290 }
6291 }
6292 }
6293
6294 @Override
6295 public void closeSystemDialogs(String reason) {
6296 enforceNotIsolatedCaller("closeSystemDialogs");
6297
6298 final int pid = Binder.getCallingPid();
6299 final int uid = Binder.getCallingUid();
6300 final long origId = Binder.clearCallingIdentity();
6301 try {
6302 synchronized (mGlobalLock) {
6303 // Only allow this from foreground processes, so that background
6304 // applications can't abuse it to prevent system UI from being shown.
6305 if (uid >= FIRST_APPLICATION_UID) {
6306 final WindowProcessController proc = mPidMap.get(pid);
6307 if (!proc.isPerceptible()) {
6308 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6309 + " from background process " + proc);
6310 return;
6311 }
6312 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006313 mWindowManager.closeSystemDialogs(reason);
6314
Wale Ogunwaled32da472018-11-16 07:19:28 -08006315 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006316 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006317 // Call into AM outside the synchronized block.
6318 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006319 } finally {
6320 Binder.restoreCallingIdentity(origId);
6321 }
6322 }
6323
6324 @Override
6325 public void cleanupDisabledPackageComponents(
6326 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6327 synchronized (mGlobalLock) {
6328 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006329 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006330 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006331 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006332 mStackSupervisor.scheduleIdleLocked();
6333 }
6334
6335 // Clean-up disabled tasks
6336 getRecentTasks().cleanupDisabledPackageTasksLocked(
6337 packageName, disabledClasses, userId);
6338 }
6339 }
6340
6341 @Override
6342 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6343 int userId) {
6344 synchronized (mGlobalLock) {
6345
6346 boolean didSomething =
6347 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006348 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006349 null, doit, evenPersistent, userId);
6350 return didSomething;
6351 }
6352 }
6353
6354 @Override
6355 public void resumeTopActivities(boolean scheduleIdle) {
6356 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006357 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006358 if (scheduleIdle) {
6359 mStackSupervisor.scheduleIdleLocked();
6360 }
6361 }
6362 }
6363
6364 @Override
6365 public void preBindApplication(WindowProcessController wpc) {
6366 synchronized (mGlobalLock) {
6367 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6368 }
6369 }
6370
6371 @Override
6372 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6373 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006374 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006375 }
6376 }
6377
6378 @Override
6379 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6380 try {
6381 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6382 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6383 }
6384 } catch (RemoteException ex) {
6385 throw new SecurityException("Fail to check is caller a privileged app", ex);
6386 }
6387
6388 synchronized (mGlobalLock) {
6389 final long ident = Binder.clearCallingIdentity();
6390 try {
6391 if (mAmInternal.shouldConfirmCredentials(userId)) {
6392 if (mKeyguardController.isKeyguardLocked()) {
6393 // Showing launcher to avoid user entering credential twice.
6394 startHomeActivity(currentUserId, "notifyLockedProfile");
6395 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006396 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006397 }
6398 } finally {
6399 Binder.restoreCallingIdentity(ident);
6400 }
6401 }
6402 }
6403
6404 @Override
6405 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6406 mAmInternal.enforceCallingPermission(
6407 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6408
6409 synchronized (mGlobalLock) {
6410 final long ident = Binder.clearCallingIdentity();
6411 try {
6412 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6413 FLAG_ACTIVITY_TASK_ON_HOME);
6414 ActivityOptions activityOptions = options != null
6415 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006416 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006417 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006418 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006419 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006420 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006421 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6422 UserHandle.CURRENT);
6423 } finally {
6424 Binder.restoreCallingIdentity(ident);
6425 }
6426 }
6427 }
6428
6429 @Override
6430 public void writeActivitiesToProto(ProtoOutputStream proto) {
6431 synchronized (mGlobalLock) {
6432 // The output proto of "activity --proto activities"
6433 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006434 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006435 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6436 }
6437 }
6438
6439 @Override
6440 public void saveANRState(String reason) {
6441 synchronized (mGlobalLock) {
6442 final StringWriter sw = new StringWriter();
6443 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6444 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6445 if (reason != null) {
6446 pw.println(" Reason: " + reason);
6447 }
6448 pw.println();
6449 getActivityStartController().dump(pw, " ", null);
6450 pw.println();
6451 pw.println("-------------------------------------------------------------------------------");
6452 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6453 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6454 "" /* header */);
6455 pw.println();
6456 pw.close();
6457
6458 mLastANRState = sw.toString();
6459 }
6460 }
6461
6462 @Override
6463 public void clearSavedANRState() {
6464 synchronized (mGlobalLock) {
6465 mLastANRState = null;
6466 }
6467 }
6468
6469 @Override
6470 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6471 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6472 synchronized (mGlobalLock) {
6473 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6474 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6475 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6476 dumpLastANRLocked(pw);
6477 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6478 dumpLastANRTracesLocked(pw);
6479 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6480 dumpActivityStarterLocked(pw, dumpPackage);
6481 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6482 dumpActivityContainersLocked(pw);
6483 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6484 if (getRecentTasks() != null) {
6485 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6486 }
6487 }
6488 }
6489 }
6490
6491 @Override
6492 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6493 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6494 int wakefulness) {
6495 synchronized (mGlobalLock) {
6496 if (mHomeProcess != null && (dumpPackage == null
6497 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6498 if (needSep) {
6499 pw.println();
6500 needSep = false;
6501 }
6502 pw.println(" mHomeProcess: " + mHomeProcess);
6503 }
6504 if (mPreviousProcess != null && (dumpPackage == null
6505 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6506 if (needSep) {
6507 pw.println();
6508 needSep = false;
6509 }
6510 pw.println(" mPreviousProcess: " + mPreviousProcess);
6511 }
6512 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6513 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6514 StringBuilder sb = new StringBuilder(128);
6515 sb.append(" mPreviousProcessVisibleTime: ");
6516 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6517 pw.println(sb);
6518 }
6519 if (mHeavyWeightProcess != null && (dumpPackage == null
6520 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6521 if (needSep) {
6522 pw.println();
6523 needSep = false;
6524 }
6525 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6526 }
6527 if (dumpPackage == null) {
6528 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006529 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006530 }
6531 if (dumpAll) {
6532 if (dumpPackage == null) {
6533 pw.println(" mConfigWillChange: "
6534 + getTopDisplayFocusedStack().mConfigWillChange);
6535 }
6536 if (mCompatModePackages.getPackages().size() > 0) {
6537 boolean printed = false;
6538 for (Map.Entry<String, Integer> entry
6539 : mCompatModePackages.getPackages().entrySet()) {
6540 String pkg = entry.getKey();
6541 int mode = entry.getValue();
6542 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6543 continue;
6544 }
6545 if (!printed) {
6546 pw.println(" mScreenCompatPackages:");
6547 printed = true;
6548 }
6549 pw.println(" " + pkg + ": " + mode);
6550 }
6551 }
6552 }
6553
6554 if (dumpPackage == null) {
6555 pw.println(" mWakefulness="
6556 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006557 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006558 if (mRunningVoice != null) {
6559 pw.println(" mRunningVoice=" + mRunningVoice);
6560 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6561 }
6562 pw.println(" mSleeping=" + mSleeping);
6563 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6564 pw.println(" mVrController=" + mVrController);
6565 }
6566 if (mCurAppTimeTracker != null) {
6567 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6568 }
6569 if (mAllowAppSwitchUids.size() > 0) {
6570 boolean printed = false;
6571 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6572 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6573 for (int j = 0; j < types.size(); j++) {
6574 if (dumpPackage == null ||
6575 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6576 if (needSep) {
6577 pw.println();
6578 needSep = false;
6579 }
6580 if (!printed) {
6581 pw.println(" mAllowAppSwitchUids:");
6582 printed = true;
6583 }
6584 pw.print(" User ");
6585 pw.print(mAllowAppSwitchUids.keyAt(i));
6586 pw.print(": Type ");
6587 pw.print(types.keyAt(j));
6588 pw.print(" = ");
6589 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6590 pw.println();
6591 }
6592 }
6593 }
6594 }
6595 if (dumpPackage == null) {
6596 if (mController != null) {
6597 pw.println(" mController=" + mController
6598 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6599 }
6600 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6601 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6602 }
6603
6604 return needSep;
6605 }
6606 }
6607
6608 @Override
6609 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6610 synchronized (mGlobalLock) {
6611 if (dumpPackage == null) {
6612 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6613 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6614 writeSleepStateToProto(proto);
6615 if (mController != null) {
6616 final long token = proto.start(CONTROLLER);
6617 proto.write(CONTROLLER, mController.toString());
6618 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6619 proto.end(token);
6620 }
6621 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6622 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6623 }
6624
6625 if (mHomeProcess != null && (dumpPackage == null
6626 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006627 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006628 }
6629
6630 if (mPreviousProcess != null && (dumpPackage == null
6631 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006632 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006633 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6634 }
6635
6636 if (mHeavyWeightProcess != null && (dumpPackage == null
6637 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006638 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006639 }
6640
6641 for (Map.Entry<String, Integer> entry
6642 : mCompatModePackages.getPackages().entrySet()) {
6643 String pkg = entry.getKey();
6644 int mode = entry.getValue();
6645 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6646 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6647 proto.write(PACKAGE, pkg);
6648 proto.write(MODE, mode);
6649 proto.end(compatToken);
6650 }
6651 }
6652
6653 if (mCurAppTimeTracker != null) {
6654 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6655 }
6656
6657 }
6658 }
6659
6660 @Override
6661 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6662 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6663 boolean dumpFocusedStackOnly) {
6664 synchronized (mGlobalLock) {
6665 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6666 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6667 }
6668 }
6669
6670 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006671 public void dumpForOom(PrintWriter pw) {
6672 synchronized (mGlobalLock) {
6673 pw.println(" mHomeProcess: " + mHomeProcess);
6674 pw.println(" mPreviousProcess: " + mPreviousProcess);
6675 if (mHeavyWeightProcess != null) {
6676 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6677 }
6678 }
6679 }
6680
6681 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006682 public boolean canGcNow() {
6683 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006684 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006685 }
6686 }
6687
6688 @Override
6689 public WindowProcessController getTopApp() {
6690 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006691 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692 return top != null ? top.app : null;
6693 }
6694 }
6695
6696 @Override
6697 public void rankTaskLayersIfNeeded() {
6698 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006699 if (mRootActivityContainer != null) {
6700 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 }
6702 }
6703 }
6704
6705 @Override
6706 public void scheduleDestroyAllActivities(String reason) {
6707 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006708 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 }
6710 }
6711
6712 @Override
6713 public void removeUser(int userId) {
6714 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006715 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716 }
6717 }
6718
6719 @Override
6720 public boolean switchUser(int userId, UserState userState) {
6721 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006722 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 }
6724 }
6725
6726 @Override
6727 public void onHandleAppCrash(WindowProcessController wpc) {
6728 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006729 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 }
6731 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006732
6733 @Override
6734 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6735 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006736 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006737 }
6738 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006739
6740 @Override
6741 public void onUidActive(int uid, int procState) {
6742 synchronized (mGlobalLock) {
6743 mActiveUids.put(uid, procState);
6744 }
6745 }
6746
6747 @Override
6748 public void onUidInactive(int uid) {
6749 synchronized (mGlobalLock) {
6750 mActiveUids.remove(uid);
6751 }
6752 }
6753
6754 @Override
6755 public void onActiveUidsCleared() {
6756 synchronized (mGlobalLock) {
6757 mActiveUids.clear();
6758 }
6759 }
6760
6761 @Override
6762 public void onUidProcStateChanged(int uid, int procState) {
6763 synchronized (mGlobalLock) {
6764 if (mActiveUids.get(uid) != null) {
6765 mActiveUids.put(uid, procState);
6766 }
6767 }
6768 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006769
6770 @Override
6771 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6772 synchronized (mGlobalLock) {
6773 mPendingTempWhitelist.put(uid, tag);
6774 }
6775 }
6776
6777 @Override
6778 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6779 synchronized (mGlobalLock) {
6780 mPendingTempWhitelist.remove(uid);
6781 }
6782 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006783
6784 @Override
6785 public boolean handleAppCrashInActivityController(String processName, int pid,
6786 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6787 Runnable killCrashingAppCallback) {
6788 synchronized (mGlobalLock) {
6789 if (mController == null) {
6790 return false;
6791 }
6792
6793 try {
6794 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6795 stackTrace)) {
6796 killCrashingAppCallback.run();
6797 return true;
6798 }
6799 } catch (RemoteException e) {
6800 mController = null;
6801 Watchdog.getInstance().setActivityController(null);
6802 }
6803 return false;
6804 }
6805 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006806
6807 @Override
6808 public void removeRecentTasksByPackageName(String packageName, int userId) {
6809 synchronized (mGlobalLock) {
6810 mRecentTasks.removeTasksByPackageName(packageName, userId);
6811 }
6812 }
6813
6814 @Override
6815 public void cleanupRecentTasksForUser(int userId) {
6816 synchronized (mGlobalLock) {
6817 mRecentTasks.cleanupLocked(userId);
6818 }
6819 }
6820
6821 @Override
6822 public void loadRecentTasksForUser(int userId) {
6823 synchronized (mGlobalLock) {
6824 mRecentTasks.loadUserRecentsLocked(userId);
6825 }
6826 }
6827
6828 @Override
6829 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6830 synchronized (mGlobalLock) {
6831 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6832 }
6833 }
6834
6835 @Override
6836 public void flushRecentTasks() {
6837 mRecentTasks.flush();
6838 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006839
6840 @Override
6841 public WindowProcessController getHomeProcess() {
6842 synchronized (mGlobalLock) {
6843 return mHomeProcess;
6844 }
6845 }
6846
6847 @Override
6848 public WindowProcessController getPreviousProcess() {
6849 synchronized (mGlobalLock) {
6850 return mPreviousProcess;
6851 }
6852 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006853
6854 @Override
6855 public void clearLockedTasks(String reason) {
6856 synchronized (mGlobalLock) {
6857 getLockTaskController().clearLockedTasks(reason);
6858 }
6859 }
6860
6861 @Override
6862 public void updateUserConfiguration() {
6863 synchronized (mGlobalLock) {
6864 final Configuration configuration = new Configuration(getGlobalConfiguration());
6865 final int currentUserId = mAmInternal.getCurrentUserId();
6866 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6867 configuration, currentUserId, Settings.System.canWrite(mContext));
6868 updateConfigurationLocked(configuration, null /* starting */,
6869 false /* initLocale */, false /* persistent */, currentUserId,
6870 false /* deferResume */);
6871 }
6872 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006873
6874 @Override
6875 public boolean canShowErrorDialogs() {
6876 synchronized (mGlobalLock) {
6877 return mShowDialogs && !mSleeping && !mShuttingDown
6878 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6879 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6880 mAmInternal.getCurrentUserId())
6881 && !(UserManager.isDeviceInDemoMode(mContext)
6882 && mAmInternal.getCurrentUser().isDemo());
6883 }
6884 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006885
6886 @Override
6887 public void setProfileApp(String profileApp) {
6888 synchronized (mGlobalLock) {
6889 mProfileApp = profileApp;
6890 }
6891 }
6892
6893 @Override
6894 public void setProfileProc(WindowProcessController wpc) {
6895 synchronized (mGlobalLock) {
6896 mProfileProc = wpc;
6897 }
6898 }
6899
6900 @Override
6901 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6902 synchronized (mGlobalLock) {
6903 mProfilerInfo = profilerInfo;
6904 }
6905 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08006906
6907 @Override
6908 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
6909 synchronized (mGlobalLock) {
6910 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
6911 }
6912 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006913 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08006914}