blob: 2cd4921a66721562de429f74c95e009d54ec0cd0 [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;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700216import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
218import android.util.EventLog;
219import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700220import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700222import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700224import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700225import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700226import android.view.IRecentsAnimationRunner;
227import android.view.RemoteAnimationAdapter;
228import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700229import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
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;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700278import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700280import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700281import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400283import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700286import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Map;
288import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289
290/**
291 * System service for managing activities and their containers (task, stacks, displays,... ).
292 *
293 * {@hide}
294 */
295public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700296 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700298 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
299 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
300 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
301 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
302 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700303 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700308 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309
Wale Ogunwale98875612018-10-12 07:53:02 -0700310 /** Used to indicate that an app transition should be animated. */
311 static final boolean ANIMATE = true;
312
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700313 /** Hardware-reported OpenGLES version. */
314 final int GL_ES_VERSION;
315
Wale Ogunwale31913b52018-10-13 08:29:31 -0700316 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
317 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
318 public static final String DUMP_LASTANR_CMD = "lastanr" ;
319 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
320 public static final String DUMP_STARTER_CMD = "starter" ;
321 public static final String DUMP_CONTAINERS_CMD = "containers" ;
322 public static final String DUMP_RECENTS_CMD = "recents" ;
323 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
324
Wale Ogunwale64258362018-10-16 15:13:37 -0700325 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
326 public static final int RELAUNCH_REASON_NONE = 0;
327 /** This activity is being relaunched due to windowing mode change. */
328 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
329 /** This activity is being relaunched due to a free-resize operation. */
330 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
331
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700332 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700333
Wale Ogunwalef6733932018-06-27 05:14:34 -0700334 /**
335 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
336 * change at runtime. Use mContext for non-UI purposes.
337 */
338 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700339 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700340 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700342 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700343 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700344 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800345 @VisibleForTesting
346 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 PowerManagerInternal mPowerManagerInternal;
348 private UsageStatsManagerInternal mUsageStatsInternal;
349
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700350 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 IntentFirewall mIntentFirewall;
352
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700353 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800354 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700355 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800356 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700357 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700358 private UserManagerService mUserManager;
359 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700360 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700361 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
362 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700363 /** All processes currently running that might have a window organized by name. */
364 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700365 /** All processes we currently have running mapped by pid */
366 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700367 /** This is the process holding what we currently consider to be the "home" activity. */
368 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700369 /** The currently running heavy-weight process, if any. */
370 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700371 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700372 /**
373 * This is the process holding the activity the user last visited that is in a different process
374 * from the one they are currently in.
375 */
376 WindowProcessController mPreviousProcess;
377 /** The time at which the previous process was last visible. */
378 long mPreviousProcessVisibleTime;
379
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700380 /** List of intents that were used to start the most recent tasks. */
381 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700382 /** State of external calls telling us if the device is awake or asleep. */
383 private boolean mKeyguardShown = false;
384
385 // Wrapper around VoiceInteractionServiceManager
386 private AssistUtils mAssistUtils;
387
388 // VoiceInteraction session ID that changes for each new request except when
389 // being called for multi-window assist in a single session.
390 private int mViSessionId = 1000;
391
392 // How long to wait in getAssistContextExtras for the activity and foreground services
393 // to respond with the result.
394 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
395
396 // How long top wait when going through the modern assist (which doesn't need to block
397 // on getting this result before starting to launch its UI).
398 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
399
400 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
401 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
402
Alison Cichowlas3e340502018-08-07 17:15:01 -0400403 // Permission tokens are used to temporarily granted a trusted app the ability to call
404 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
405 // showing any appropriate error messages to the user.
406 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
407 10 * MINUTE_IN_MILLIS;
408
409 // How long before the service actually expires a token. This is slightly longer than
410 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
411 // expiration exception.
412 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
413 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
414
415 // How long the service will remember expired tokens, for the purpose of providing error
416 // messaging when a client uses an expired token.
417 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
418 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
419
420 // Activity tokens of system activities that are delegating their call to
421 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
422 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
423
424 // Permission tokens that have expired, but we remember for error reporting.
425 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
426
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700427 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
428
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700429 // Keeps track of the active voice interaction service component, notified from
430 // VoiceInteractionManagerService
431 ComponentName mActiveVoiceInteractionServiceComponent;
432
Wale Ogunwalee2172292018-10-25 10:11:10 -0700433 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700434 KeyguardController mKeyguardController;
435 private final ClientLifecycleManager mLifecycleManager;
436 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700437 /** The controller for all operations related to locktask. */
438 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700439 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700441 boolean mSuppressResizeConfigChanges;
442
443 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
444 new UpdateConfigurationResult();
445
446 static final class UpdateConfigurationResult {
447 // Configuration changes that were updated.
448 int changes;
449 // If the activity was relaunched to match the new configuration.
450 boolean activityRelaunched;
451
452 void reset() {
453 changes = 0;
454 activityRelaunched = false;
455 }
456 }
457
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700458 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700459 private int mConfigurationSeq;
460 // To cache the list of supported system locales
461 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700462
463 /**
464 * Temp object used when global and/or display override configuration is updated. It is also
465 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
466 * anyone...
467 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700468 private Configuration mTempConfig = new Configuration();
469
Wale Ogunwalef6733932018-06-27 05:14:34 -0700470 /** Temporary to avoid allocations. */
471 final StringBuilder mStringBuilder = new StringBuilder(256);
472
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700473 // Amount of time after a call to stopAppSwitches() during which we will
474 // prevent further untrusted switches from happening.
475 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
476
477 /**
478 * The time at which we will allow normal application switches again,
479 * after a call to {@link #stopAppSwitches()}.
480 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700481 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 /**
483 * This is set to true after the first switch after mAppSwitchesAllowedTime
484 * is set; any switches after that will clear the time.
485 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700486 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487
488 IActivityController mController = null;
489 boolean mControllerIsAMonkey = false;
490
Wale Ogunwale214f3482018-10-04 11:00:47 -0700491 final int mFactoryTest;
492
493 /** Used to control how we initialize the service. */
494 ComponentName mTopComponent;
495 String mTopAction = Intent.ACTION_MAIN;
496 String mTopData;
497
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800498 /** Profiling app information. */
499 String mProfileApp = null;
500 WindowProcessController mProfileProc = null;
501 ProfilerInfo mProfilerInfo = null;
502
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700504 * Dump of the activity state at the time of the last ANR. Cleared after
505 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
506 */
507 String mLastANRState;
508
509 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510 * Used to retain an update lock when the foreground activity is in
511 * immersive mode.
512 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700513 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700514
515 /**
516 * Packages that are being allowed to perform unrestricted app switches. Mapping is
517 * User -> Type -> uid.
518 */
519 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
520
521 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700522 private int mThumbnailWidth;
523 private int mThumbnailHeight;
524 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700525
526 /**
527 * Flag that indicates if multi-window is enabled.
528 *
529 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
530 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
531 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
532 * At least one of the forms of multi-window must be enabled in order for this flag to be
533 * initialized to 'true'.
534 *
535 * @see #mSupportsSplitScreenMultiWindow
536 * @see #mSupportsFreeformWindowManagement
537 * @see #mSupportsPictureInPicture
538 * @see #mSupportsMultiDisplay
539 */
540 boolean mSupportsMultiWindow;
541 boolean mSupportsSplitScreenMultiWindow;
542 boolean mSupportsFreeformWindowManagement;
543 boolean mSupportsPictureInPicture;
544 boolean mSupportsMultiDisplay;
545 boolean mForceResizableActivities;
546
547 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
548
549 // VR Vr2d Display Id.
550 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700551
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 /**
553 * Set while we are wanting to sleep, to prevent any
554 * activities from being started/resumed.
555 *
556 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
557 *
558 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
559 * while in the sleep state until there is a pending transition out of sleep, in which case
560 * mSleeping is set to false, and remains false while awake.
561 *
562 * Whether mSleeping can quickly toggled between true/false without the device actually
563 * display changing states is undefined.
564 */
565 private boolean mSleeping = false;
566
567 /**
568 * The process state used for processes that are running the top activities.
569 * This changes between TOP and TOP_SLEEPING to following mSleeping.
570 */
571 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
572
573 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
574 // automatically. Important for devices without direct input devices.
575 private boolean mShowDialogs = true;
576
577 /** Set if we are shutting down the system, similar to sleeping. */
578 boolean mShuttingDown = false;
579
580 /**
581 * We want to hold a wake lock while running a voice interaction session, since
582 * this may happen with the screen off and we need to keep the CPU running to
583 * be able to continue to interact with the user.
584 */
585 PowerManager.WakeLock mVoiceWakeLock;
586
587 /**
588 * Set while we are running a voice interaction. This overrides sleeping while it is active.
589 */
590 IVoiceInteractionSession mRunningVoice;
591
592 /**
593 * The last resumed activity. This is identical to the current resumed activity most
594 * of the time but could be different when we're pausing one activity before we resume
595 * another activity.
596 */
597 ActivityRecord mLastResumedActivity;
598
599 /**
600 * The activity that is currently being traced as the active resumed activity.
601 *
602 * @see #updateResumedAppTrace
603 */
604 private @Nullable ActivityRecord mTracedResumedActivity;
605
606 /** If non-null, we are tracking the time the user spends in the currently focused app. */
607 AppTimeTracker mCurAppTimeTracker;
608
Wale Ogunwale008163e2018-07-23 23:11:08 -0700609 private AppWarnings mAppWarnings;
610
Wale Ogunwale53783742018-09-16 10:21:51 -0700611 /**
612 * Packages that the user has asked to have run in screen size
613 * compatibility mode instead of filling the screen.
614 */
615 CompatModePackages mCompatModePackages;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 private FontScaleSettingObserver mFontScaleSettingObserver;
618
619 private final class FontScaleSettingObserver extends ContentObserver {
620 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
621 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
622
623 public FontScaleSettingObserver() {
624 super(mH);
625 final ContentResolver resolver = mContext.getContentResolver();
626 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
627 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
628 UserHandle.USER_ALL);
629 }
630
631 @Override
632 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
633 if (mFontScaleUri.equals(uri)) {
634 updateFontScaleIfNeeded(userId);
635 } else if (mHideErrorDialogsUri.equals(uri)) {
636 synchronized (mGlobalLock) {
637 updateShouldShowDialogsLocked(getGlobalConfiguration());
638 }
639 }
640 }
641 }
642
Charles Chen8d98dd22018-12-26 17:36:54 +0800643 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
644 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700645 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700646 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700647 mSystemThread = ActivityThread.currentActivityThread();
648 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700649 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800650 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700651 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700652 }
653
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700654 public void onSystemReady() {
655 synchronized (mGlobalLock) {
656 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
657 PackageManager.FEATURE_CANT_SAVE_STATE);
658 mAssistUtils = new AssistUtils(mContext);
659 mVrController.onSystemReady();
660 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700661 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700662 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700663 }
664
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700665 public void onInitPowerManagement() {
666 synchronized (mGlobalLock) {
667 mStackSupervisor.initPowerManagement();
668 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
669 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
670 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
671 mVoiceWakeLock.setReferenceCounted(false);
672 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 }
674
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700675 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700676 mFontScaleSettingObserver = new FontScaleSettingObserver();
677 }
678
Wale Ogunwale59507092018-10-29 09:00:30 -0700679 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700680 final boolean freeformWindowManagement =
681 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
682 || Settings.Global.getInt(
683 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
684
685 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
686 final boolean supportsPictureInPicture = supportsMultiWindow &&
687 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
688 final boolean supportsSplitScreenMultiWindow =
689 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
690 final boolean supportsMultiDisplay = mContext.getPackageManager()
691 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700692 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
693 final boolean forceResizable = Settings.Global.getInt(
694 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700695 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700696
697 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900698 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700699
700 final Configuration configuration = new Configuration();
701 Settings.System.getConfiguration(resolver, configuration);
702 if (forceRtl) {
703 // This will take care of setting the correct layout direction flags
704 configuration.setLayoutDirection(configuration.locale);
705 }
706
707 synchronized (mGlobalLock) {
708 mForceResizableActivities = forceResizable;
709 final boolean multiWindowFormEnabled = freeformWindowManagement
710 || supportsSplitScreenMultiWindow
711 || supportsPictureInPicture
712 || supportsMultiDisplay;
713 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
714 mSupportsMultiWindow = true;
715 mSupportsFreeformWindowManagement = freeformWindowManagement;
716 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
717 mSupportsPictureInPicture = supportsPictureInPicture;
718 mSupportsMultiDisplay = supportsMultiDisplay;
719 } else {
720 mSupportsMultiWindow = false;
721 mSupportsFreeformWindowManagement = false;
722 mSupportsSplitScreenMultiWindow = false;
723 mSupportsPictureInPicture = false;
724 mSupportsMultiDisplay = false;
725 }
726 mWindowManager.setForceResizableTasks(mForceResizableActivities);
727 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700728 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
729 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730 // This happens before any activities are started, so we can change global configuration
731 // in-place.
732 updateConfigurationLocked(configuration, null, true);
733 final Configuration globalConfig = getGlobalConfiguration();
734 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
735
736 // Load resources only after the current configuration has been set.
737 final Resources res = mContext.getResources();
738 mThumbnailWidth = res.getDimensionPixelSize(
739 com.android.internal.R.dimen.thumbnail_width);
740 mThumbnailHeight = res.getDimensionPixelSize(
741 com.android.internal.R.dimen.thumbnail_height);
742
743 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
744 mFullscreenThumbnailScale = (float) res
745 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
746 (float) globalConfig.screenWidthDp;
747 } else {
748 mFullscreenThumbnailScale = res.getFraction(
749 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
750 }
751 }
752 }
753
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800754 public WindowManagerGlobalLock getGlobalLock() {
755 return mGlobalLock;
756 }
757
Riddle Hsud93a6c42018-11-29 21:50:06 +0800758 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
759 Looper looper) {
760 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700762 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700763 final File systemDir = SystemServiceManager.ensureSystemDir();
764 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
765 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700766 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700767
768 mTempConfig.setToDefaults();
769 mTempConfig.setLocales(LocaleList.getDefault());
770 mConfigurationSeq = mTempConfig.seq = 1;
771 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800772 mRootActivityContainer = new RootActivityContainer(this);
773 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700775 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700777 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700778 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700779 mRecentTasks = createRecentTasks();
780 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700781 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700782 mKeyguardController = mStackSupervisor.getKeyguardController();
783 }
784
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700785 public void onActivityManagerInternalAdded() {
786 synchronized (mGlobalLock) {
787 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
788 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
789 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700790 }
791
Yunfan Chen75157d72018-07-27 14:47:21 +0900792 int increaseConfigurationSeqLocked() {
793 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
794 return mConfigurationSeq;
795 }
796
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700797 protected ActivityStackSupervisor createStackSupervisor() {
798 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
799 supervisor.initialize();
800 return supervisor;
801 }
802
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700803 public void setWindowManager(WindowManagerService wm) {
804 synchronized (mGlobalLock) {
805 mWindowManager = wm;
806 mLockTaskController.setWindowManager(wm);
807 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800808 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700809 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700810 }
811
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700812 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
813 synchronized (mGlobalLock) {
814 mUsageStatsInternal = usageStatsManager;
815 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700816 }
817
Wale Ogunwalef6733932018-06-27 05:14:34 -0700818 UserManagerService getUserManager() {
819 if (mUserManager == null) {
820 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
821 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
822 }
823 return mUserManager;
824 }
825
826 AppOpsService getAppOpsService() {
827 if (mAppOpsService == null) {
828 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
829 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
830 }
831 return mAppOpsService;
832 }
833
834 boolean hasUserRestriction(String restriction, int userId) {
835 return getUserManager().hasUserRestriction(restriction, userId);
836 }
837
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700838 protected RecentTasks createRecentTasks() {
839 return new RecentTasks(this, mStackSupervisor);
840 }
841
842 RecentTasks getRecentTasks() {
843 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700844 }
845
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700846 ClientLifecycleManager getLifecycleManager() {
847 return mLifecycleManager;
848 }
849
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700850 ActivityStartController getActivityStartController() {
851 return mActivityStartController;
852 }
853
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700854 TaskChangeNotificationController getTaskChangeNotificationController() {
855 return mTaskChangeNotificationController;
856 }
857
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700858 LockTaskController getLockTaskController() {
859 return mLockTaskController;
860 }
861
Yunfan Chen75157d72018-07-27 14:47:21 +0900862 /**
863 * Return the global configuration used by the process corresponding to the input pid. This is
864 * usually the global configuration with some overrides specific to that process.
865 */
866 Configuration getGlobalConfigurationForCallingPid() {
867 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800868 return getGlobalConfigurationForPid(pid);
869 }
870
871 /**
872 * Return the global configuration used by the process corresponding to the given pid.
873 */
874 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900875 if (pid == MY_PID || pid < 0) {
876 return getGlobalConfiguration();
877 }
878 synchronized (mGlobalLock) {
879 final WindowProcessController app = mPidMap.get(pid);
880 return app != null ? app.getConfiguration() : getGlobalConfiguration();
881 }
882 }
883
884 /**
885 * Return the device configuration info used by the process corresponding to the input pid.
886 * The value is consistent with the global configuration for the process.
887 */
888 @Override
889 public ConfigurationInfo getDeviceConfigurationInfo() {
890 ConfigurationInfo config = new ConfigurationInfo();
891 synchronized (mGlobalLock) {
892 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
893 config.reqTouchScreen = globalConfig.touchscreen;
894 config.reqKeyboardType = globalConfig.keyboard;
895 config.reqNavigation = globalConfig.navigation;
896 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
897 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
898 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
899 }
900 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
901 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
902 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
903 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700904 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900905 }
906 return config;
907 }
908
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700909 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700910 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700911 }
912
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700913 public static final class Lifecycle extends SystemService {
914 private final ActivityTaskManagerService mService;
915
916 public Lifecycle(Context context) {
917 super(context);
918 mService = new ActivityTaskManagerService(context);
919 }
920
921 @Override
922 public void onStart() {
923 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700924 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700925 }
926
Garfield Tan891146c2018-10-09 12:14:00 -0700927 @Override
928 public void onUnlockUser(int userId) {
929 synchronized (mService.getGlobalLock()) {
930 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
931 }
932 }
933
934 @Override
935 public void onCleanupUser(int userId) {
936 synchronized (mService.getGlobalLock()) {
937 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
938 }
939 }
940
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700941 public ActivityTaskManagerService getService() {
942 return mService;
943 }
944 }
945
946 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700947 public final int startActivity(IApplicationThread caller, String callingPackage,
948 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
949 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
950 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
951 resultWho, requestCode, startFlags, profilerInfo, bOptions,
952 UserHandle.getCallingUserId());
953 }
954
955 @Override
956 public final int startActivities(IApplicationThread caller, String callingPackage,
957 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
958 int userId) {
959 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700960 enforceNotIsolatedCaller(reason);
961 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700962 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700963 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100964 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +0000965 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700966 }
967
968 @Override
969 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
970 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
971 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
972 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
973 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
974 true /*validateIncomingUser*/);
975 }
976
977 int startActivityAsUser(IApplicationThread caller, String callingPackage,
978 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
979 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
980 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700981 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700982
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700983 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700984 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
985
986 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700987 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700988 .setCaller(caller)
989 .setCallingPackage(callingPackage)
990 .setResolvedType(resolvedType)
991 .setResultTo(resultTo)
992 .setResultWho(resultWho)
993 .setRequestCode(requestCode)
994 .setStartFlags(startFlags)
995 .setProfilerInfo(profilerInfo)
996 .setActivityOptions(bOptions)
997 .setMayWait(userId)
998 .execute();
999
1000 }
1001
1002 @Override
1003 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1004 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001005 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1006 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001007 // Refuse possible leaked file descriptors
1008 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1009 throw new IllegalArgumentException("File descriptors passed in Intent");
1010 }
1011
1012 if (!(target instanceof PendingIntentRecord)) {
1013 throw new IllegalArgumentException("Bad PendingIntent object");
1014 }
1015
1016 PendingIntentRecord pir = (PendingIntentRecord)target;
1017
1018 synchronized (mGlobalLock) {
1019 // If this is coming from the currently resumed activity, it is
1020 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001021 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 if (stack.mResumedActivity != null &&
1023 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001024 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001025 }
1026 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001027 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 }
1030
1031 @Override
1032 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1033 Bundle bOptions) {
1034 // Refuse possible leaked file descriptors
1035 if (intent != null && intent.hasFileDescriptors()) {
1036 throw new IllegalArgumentException("File descriptors passed in Intent");
1037 }
1038 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1039
1040 synchronized (mGlobalLock) {
1041 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1042 if (r == null) {
1043 SafeActivityOptions.abort(options);
1044 return false;
1045 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001046 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 // The caller is not running... d'oh!
1048 SafeActivityOptions.abort(options);
1049 return false;
1050 }
1051 intent = new Intent(intent);
1052 // The caller is not allowed to change the data.
1053 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1054 // And we are resetting to find the next component...
1055 intent.setComponent(null);
1056
1057 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1058
1059 ActivityInfo aInfo = null;
1060 try {
1061 List<ResolveInfo> resolves =
1062 AppGlobals.getPackageManager().queryIntentActivities(
1063 intent, r.resolvedType,
1064 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1065 UserHandle.getCallingUserId()).getList();
1066
1067 // Look for the original activity in the list...
1068 final int N = resolves != null ? resolves.size() : 0;
1069 for (int i=0; i<N; i++) {
1070 ResolveInfo rInfo = resolves.get(i);
1071 if (rInfo.activityInfo.packageName.equals(r.packageName)
1072 && rInfo.activityInfo.name.equals(r.info.name)) {
1073 // We found the current one... the next matching is
1074 // after it.
1075 i++;
1076 if (i<N) {
1077 aInfo = resolves.get(i).activityInfo;
1078 }
1079 if (debug) {
1080 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1081 + "/" + r.info.name);
1082 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1083 ? "null" : aInfo.packageName + "/" + aInfo.name));
1084 }
1085 break;
1086 }
1087 }
1088 } catch (RemoteException e) {
1089 }
1090
1091 if (aInfo == null) {
1092 // Nobody who is next!
1093 SafeActivityOptions.abort(options);
1094 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1095 return false;
1096 }
1097
1098 intent.setComponent(new ComponentName(
1099 aInfo.applicationInfo.packageName, aInfo.name));
1100 intent.setFlags(intent.getFlags()&~(
1101 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1102 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1103 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1104 FLAG_ACTIVITY_NEW_TASK));
1105
1106 // Okay now we need to start the new activity, replacing the currently running activity.
1107 // This is a little tricky because we want to start the new one as if the current one is
1108 // finished, but not finish the current one first so that there is no flicker.
1109 // And thus...
1110 final boolean wasFinishing = r.finishing;
1111 r.finishing = true;
1112
1113 // Propagate reply information over to the new activity.
1114 final ActivityRecord resultTo = r.resultTo;
1115 final String resultWho = r.resultWho;
1116 final int requestCode = r.requestCode;
1117 r.resultTo = null;
1118 if (resultTo != null) {
1119 resultTo.removeResultsLocked(r, resultWho, requestCode);
1120 }
1121
1122 final long origId = Binder.clearCallingIdentity();
1123 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001124 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001126 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001127 .setResolvedType(r.resolvedType)
1128 .setActivityInfo(aInfo)
1129 .setResultTo(resultTo != null ? resultTo.appToken : null)
1130 .setResultWho(resultWho)
1131 .setRequestCode(requestCode)
1132 .setCallingPid(-1)
1133 .setCallingUid(r.launchedFromUid)
1134 .setCallingPackage(r.launchedFromPackage)
1135 .setRealCallingPid(-1)
1136 .setRealCallingUid(r.launchedFromUid)
1137 .setActivityOptions(options)
1138 .execute();
1139 Binder.restoreCallingIdentity(origId);
1140
1141 r.finishing = wasFinishing;
1142 if (res != ActivityManager.START_SUCCESS) {
1143 return false;
1144 }
1145 return true;
1146 }
1147 }
1148
1149 @Override
1150 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1151 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1152 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1153 final WaitResult res = new WaitResult();
1154 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001155 enforceNotIsolatedCaller("startActivityAndWait");
1156 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1157 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001158 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001159 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001160 .setCaller(caller)
1161 .setCallingPackage(callingPackage)
1162 .setResolvedType(resolvedType)
1163 .setResultTo(resultTo)
1164 .setResultWho(resultWho)
1165 .setRequestCode(requestCode)
1166 .setStartFlags(startFlags)
1167 .setActivityOptions(bOptions)
1168 .setMayWait(userId)
1169 .setProfilerInfo(profilerInfo)
1170 .setWaitResult(res)
1171 .execute();
1172 }
1173 return res;
1174 }
1175
1176 @Override
1177 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1178 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1179 int startFlags, Configuration config, Bundle bOptions, int userId) {
1180 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001181 enforceNotIsolatedCaller("startActivityWithConfig");
1182 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1183 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001184 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001185 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001186 .setCaller(caller)
1187 .setCallingPackage(callingPackage)
1188 .setResolvedType(resolvedType)
1189 .setResultTo(resultTo)
1190 .setResultWho(resultWho)
1191 .setRequestCode(requestCode)
1192 .setStartFlags(startFlags)
1193 .setGlobalConfiguration(config)
1194 .setActivityOptions(bOptions)
1195 .setMayWait(userId)
1196 .execute();
1197 }
1198 }
1199
Alison Cichowlas3e340502018-08-07 17:15:01 -04001200
1201 @Override
1202 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1203 int callingUid = Binder.getCallingUid();
1204 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1205 throw new SecurityException("Only the system process can request a permission token, "
1206 + "received request from uid: " + callingUid);
1207 }
1208 IBinder permissionToken = new Binder();
1209 synchronized (mGlobalLock) {
1210 mStartActivitySources.put(permissionToken, delegatorToken);
1211 }
1212
1213 Message expireMsg = PooledLambda.obtainMessage(
1214 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1215 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1216
1217 Message forgetMsg = PooledLambda.obtainMessage(
1218 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1219 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1220
1221 return permissionToken;
1222 }
1223
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 @Override
1225 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1226 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001227 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1228 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001229 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001230 // permission grants) as any app that may launch one of your own activities. So we only
1231 // allow this in two cases:
1232 // 1) The caller is an activity that is part of the core framework, and then only when it
1233 // is running as the system.
1234 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1235 // can only be requested by a system activity, which may then delegate this call to
1236 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 final ActivityRecord sourceRecord;
1238 final int targetUid;
1239 final String targetPackage;
1240 final boolean isResolver;
1241 synchronized (mGlobalLock) {
1242 if (resultTo == null) {
1243 throw new SecurityException("Must be called from an activity");
1244 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001245 final IBinder sourceToken;
1246 if (permissionToken != null) {
1247 // To even attempt to use a permissionToken, an app must also have this signature
1248 // permission.
1249 mAmInternal.enforceCallingPermission(
1250 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1251 "startActivityAsCaller");
1252 // If called with a permissionToken, we want the sourceRecord from the delegator
1253 // activity that requested this token.
1254 sourceToken = mStartActivitySources.remove(permissionToken);
1255 if (sourceToken == null) {
1256 // Invalid permissionToken, check if it recently expired.
1257 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1258 throw new SecurityException("Called with expired permission token: "
1259 + permissionToken);
1260 } else {
1261 throw new SecurityException("Called with invalid permission token: "
1262 + permissionToken);
1263 }
1264 }
1265 } else {
1266 // This method was called directly by the source.
1267 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001268 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269
Wale Ogunwaled32da472018-11-16 07:19:28 -08001270 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001271 if (sourceRecord == null) {
1272 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001273 }
1274 if (sourceRecord.app == null) {
1275 throw new SecurityException("Called without a process attached to activity");
1276 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277
1278 // Whether called directly or from a delegate, the source activity must be from the
1279 // android package.
1280 if (!sourceRecord.info.packageName.equals("android")) {
1281 throw new SecurityException("Must be called from an activity that is "
1282 + "declared in the android package");
1283 }
1284
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001285 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 // This is still okay, as long as this activity is running under the
1287 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001288 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001290 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 + " must be system uid or original calling uid "
1292 + sourceRecord.launchedFromUid);
1293 }
1294 }
1295 if (ignoreTargetSecurity) {
1296 if (intent.getComponent() == null) {
1297 throw new SecurityException(
1298 "Component must be specified with ignoreTargetSecurity");
1299 }
1300 if (intent.getSelector() != null) {
1301 throw new SecurityException(
1302 "Selector not allowed with ignoreTargetSecurity");
1303 }
1304 }
1305 targetUid = sourceRecord.launchedFromUid;
1306 targetPackage = sourceRecord.launchedFromPackage;
1307 isResolver = sourceRecord.isResolverOrChildActivity();
1308 }
1309
1310 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001311 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001312 }
1313
1314 // TODO: Switch to user app stacks here.
1315 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001316 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 .setCallingUid(targetUid)
1318 .setCallingPackage(targetPackage)
1319 .setResolvedType(resolvedType)
1320 .setResultTo(resultTo)
1321 .setResultWho(resultWho)
1322 .setRequestCode(requestCode)
1323 .setStartFlags(startFlags)
1324 .setActivityOptions(bOptions)
1325 .setMayWait(userId)
1326 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1327 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1328 .execute();
1329 } catch (SecurityException e) {
1330 // XXX need to figure out how to propagate to original app.
1331 // A SecurityException here is generally actually a fault of the original
1332 // calling activity (such as a fairly granting permissions), so propagate it
1333 // back to them.
1334 /*
1335 StringBuilder msg = new StringBuilder();
1336 msg.append("While launching");
1337 msg.append(intent.toString());
1338 msg.append(": ");
1339 msg.append(e.getMessage());
1340 */
1341 throw e;
1342 }
1343 }
1344
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001345 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1346 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1347 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1348 }
1349
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 @Override
1351 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1352 Intent intent, String resolvedType, IVoiceInteractionSession session,
1353 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1354 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001355 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001356 if (session == null || interactor == null) {
1357 throw new NullPointerException("null session or interactor");
1358 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001359 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001361 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 .setCallingUid(callingUid)
1363 .setCallingPackage(callingPackage)
1364 .setResolvedType(resolvedType)
1365 .setVoiceSession(session)
1366 .setVoiceInteractor(interactor)
1367 .setStartFlags(startFlags)
1368 .setProfilerInfo(profilerInfo)
1369 .setActivityOptions(bOptions)
1370 .setMayWait(userId)
1371 .execute();
1372 }
1373
1374 @Override
1375 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1376 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001377 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1378 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001380 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 .setCallingUid(callingUid)
1382 .setCallingPackage(callingPackage)
1383 .setResolvedType(resolvedType)
1384 .setActivityOptions(bOptions)
1385 .setMayWait(userId)
1386 .execute();
1387 }
1388
1389 @Override
1390 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1391 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001393 final int callingPid = Binder.getCallingPid();
1394 final long origId = Binder.clearCallingIdentity();
1395 try {
1396 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001397 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1398 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399
1400 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001401 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1402 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1404 recentsUid, assistDataReceiver);
1405 }
1406 } finally {
1407 Binder.restoreCallingIdentity(origId);
1408 }
1409 }
1410
1411 @Override
1412 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 "startActivityFromRecents()");
1415
1416 final int callingPid = Binder.getCallingPid();
1417 final int callingUid = Binder.getCallingUid();
1418 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1419 final long origId = Binder.clearCallingIdentity();
1420 try {
1421 synchronized (mGlobalLock) {
1422 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1423 safeOptions);
1424 }
1425 } finally {
1426 Binder.restoreCallingIdentity(origId);
1427 }
1428 }
1429
1430 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001431 * Public API to check if the client is allowed to start an activity on specified display.
1432 *
1433 * If the target display is private or virtual, some restrictions will apply.
1434 *
1435 * @param displayId Target display id.
1436 * @param intent Intent used to launch the activity.
1437 * @param resolvedType The MIME type of the intent.
1438 * @param userId The id of the user for whom the call is made.
1439 * @return {@code true} if a call to start an activity on the target display should succeed and
1440 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1441 */
1442 @Override
1443 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1444 String resolvedType, int userId) {
1445 final int callingUid = Binder.getCallingUid();
1446 final int callingPid = Binder.getCallingPid();
1447 final long origId = Binder.clearCallingIdentity();
1448
1449 try {
1450 // Collect information about the target of the Intent.
1451 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1452 0 /* startFlags */, null /* profilerInfo */, userId,
1453 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1454 UserHandle.USER_NULL));
1455 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1456
1457 synchronized (mGlobalLock) {
1458 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1459 aInfo);
1460 }
1461 } finally {
1462 Binder.restoreCallingIdentity(origId);
1463 }
1464 }
1465
1466 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 * This is the internal entry point for handling Activity.finish().
1468 *
1469 * @param token The Binder token referencing the Activity we want to finish.
1470 * @param resultCode Result code, if any, from this Activity.
1471 * @param resultData Result data (Intent), if any, from this Activity.
1472 * @param finishTask Whether to finish the task associated with this Activity.
1473 *
1474 * @return Returns true if the activity successfully finished, or false if it is still running.
1475 */
1476 @Override
1477 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1478 int finishTask) {
1479 // Refuse possible leaked file descriptors
1480 if (resultData != null && resultData.hasFileDescriptors()) {
1481 throw new IllegalArgumentException("File descriptors passed in Intent");
1482 }
1483
1484 synchronized (mGlobalLock) {
1485 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1486 if (r == null) {
1487 return true;
1488 }
1489 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001490 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001491 ActivityRecord rootR = tr.getRootActivity();
1492 if (rootR == null) {
1493 Slog.w(TAG, "Finishing task with all activities already finished");
1494 }
1495 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1496 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001497 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001498 return false;
1499 }
1500
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001501 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1502 // We should consolidate.
1503 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001505 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506 if (next != null) {
1507 // ask watcher if this is allowed
1508 boolean resumeOK = true;
1509 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 Watchdog.getInstance().setActivityController(null);
1514 }
1515
1516 if (!resumeOK) {
1517 Slog.i(TAG, "Not finishing activity because controller resumed");
1518 return false;
1519 }
1520 }
1521 }
1522 final long origId = Binder.clearCallingIdentity();
1523 try {
1524 boolean res;
1525 final boolean finishWithRootActivity =
1526 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1527 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1528 || (finishWithRootActivity && r == rootR)) {
1529 // If requested, remove the task that is associated to this activity only if it
1530 // was the root activity in the task. The result code and data is ignored
1531 // because we don't support returning them across task boundaries. Also, to
1532 // keep backwards compatibility we remove the task from recents when finishing
1533 // task with root activity.
1534 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1535 finishWithRootActivity, "finish-activity");
1536 if (!res) {
1537 Slog.i(TAG, "Removing task failed to finish activity");
1538 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001539 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001540 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541 } else {
1542 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1543 resultData, "app-request", true);
1544 if (!res) {
1545 Slog.i(TAG, "Failed to finish by app-request");
1546 }
1547 }
1548 return res;
1549 } finally {
1550 Binder.restoreCallingIdentity(origId);
1551 }
1552 }
1553 }
1554
1555 @Override
1556 public boolean finishActivityAffinity(IBinder token) {
1557 synchronized (mGlobalLock) {
1558 final long origId = Binder.clearCallingIdentity();
1559 try {
1560 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1561 if (r == null) {
1562 return false;
1563 }
1564
1565 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1566 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001567 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001568 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 return false;
1570 }
1571 return task.getStack().finishActivityAffinityLocked(r);
1572 } finally {
1573 Binder.restoreCallingIdentity(origId);
1574 }
1575 }
1576 }
1577
1578 @Override
1579 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1580 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001581 try {
1582 WindowProcessController proc = null;
1583 synchronized (mGlobalLock) {
1584 ActivityStack stack = ActivityRecord.getStackLocked(token);
1585 if (stack == null) {
1586 return;
1587 }
1588 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1589 false /* fromTimeout */, false /* processPausingActivities */, config);
1590 if (r != null) {
1591 proc = r.app;
1592 }
1593 if (stopProfiling && proc != null) {
1594 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 }
1596 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001597 } finally {
1598 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001600 }
1601
1602 @Override
1603 public final void activityResumed(IBinder token) {
1604 final long origId = Binder.clearCallingIdentity();
1605 synchronized (mGlobalLock) {
1606 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001607 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001608 }
1609 Binder.restoreCallingIdentity(origId);
1610 }
1611
1612 @Override
1613 public final void activityPaused(IBinder token) {
1614 final long origId = Binder.clearCallingIdentity();
1615 synchronized (mGlobalLock) {
1616 ActivityStack stack = ActivityRecord.getStackLocked(token);
1617 if (stack != null) {
1618 stack.activityPausedLocked(token, false);
1619 }
1620 }
1621 Binder.restoreCallingIdentity(origId);
1622 }
1623
1624 @Override
1625 public final void activityStopped(IBinder token, Bundle icicle,
1626 PersistableBundle persistentState, CharSequence description) {
1627 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1628
1629 // Refuse possible leaked file descriptors
1630 if (icicle != null && icicle.hasFileDescriptors()) {
1631 throw new IllegalArgumentException("File descriptors passed in Bundle");
1632 }
1633
1634 final long origId = Binder.clearCallingIdentity();
1635
1636 synchronized (mGlobalLock) {
1637 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1638 if (r != null) {
1639 r.activityStoppedLocked(icicle, persistentState, description);
1640 }
1641 }
1642
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001643 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647
1648 @Override
1649 public final void activityDestroyed(IBinder token) {
1650 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1651 synchronized (mGlobalLock) {
1652 ActivityStack stack = ActivityRecord.getStackLocked(token);
1653 if (stack != null) {
1654 stack.activityDestroyedLocked(token, "activityDestroyed");
1655 }
1656 }
1657 }
1658
1659 @Override
1660 public final void activityRelaunched(IBinder token) {
1661 final long origId = Binder.clearCallingIdentity();
1662 synchronized (mGlobalLock) {
1663 mStackSupervisor.activityRelaunchedLocked(token);
1664 }
1665 Binder.restoreCallingIdentity(origId);
1666 }
1667
1668 public final void activitySlept(IBinder token) {
1669 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1670
1671 final long origId = Binder.clearCallingIdentity();
1672
1673 synchronized (mGlobalLock) {
1674 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1675 if (r != null) {
1676 mStackSupervisor.activitySleptLocked(r);
1677 }
1678 }
1679
1680 Binder.restoreCallingIdentity(origId);
1681 }
1682
1683 @Override
1684 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1685 synchronized (mGlobalLock) {
1686 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1687 if (r == null) {
1688 return;
1689 }
1690 final long origId = Binder.clearCallingIdentity();
1691 try {
1692 r.setRequestedOrientation(requestedOrientation);
1693 } finally {
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696 }
1697 }
1698
1699 @Override
1700 public int getRequestedOrientation(IBinder token) {
1701 synchronized (mGlobalLock) {
1702 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1703 if (r == null) {
1704 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1705 }
1706 return r.getRequestedOrientation();
1707 }
1708 }
1709
1710 @Override
1711 public void setImmersive(IBinder token, boolean immersive) {
1712 synchronized (mGlobalLock) {
1713 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1714 if (r == null) {
1715 throw new IllegalArgumentException();
1716 }
1717 r.immersive = immersive;
1718
1719 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001720 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001722 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 }
1724 }
1725 }
1726
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001727 void applyUpdateLockStateLocked(ActivityRecord r) {
1728 // Modifications to the UpdateLock state are done on our handler, outside
1729 // the activity manager's locks. The new state is determined based on the
1730 // state *now* of the relevant activity record. The object is passed to
1731 // the handler solely for logging detail, not to be consulted/modified.
1732 final boolean nextState = r != null && r.immersive;
1733 mH.post(() -> {
1734 if (mUpdateLock.isHeld() != nextState) {
1735 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1736 "Applying new update lock state '" + nextState + "' for " + r);
1737 if (nextState) {
1738 mUpdateLock.acquire();
1739 } else {
1740 mUpdateLock.release();
1741 }
1742 }
1743 });
1744 }
1745
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001746 @Override
1747 public boolean isImmersive(IBinder token) {
1748 synchronized (mGlobalLock) {
1749 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1750 if (r == null) {
1751 throw new IllegalArgumentException();
1752 }
1753 return r.immersive;
1754 }
1755 }
1756
1757 @Override
1758 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001759 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001761 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001762 return (r != null) ? r.immersive : false;
1763 }
1764 }
1765
1766 @Override
1767 public void overridePendingTransition(IBinder token, String packageName,
1768 int enterAnim, int exitAnim) {
1769 synchronized (mGlobalLock) {
1770 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1771 if (self == null) {
1772 return;
1773 }
1774
1775 final long origId = Binder.clearCallingIdentity();
1776
1777 if (self.isState(
1778 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001779 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001780 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781 }
1782
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785 }
1786
1787 @Override
1788 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001789 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001790 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001791 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001792 if (r == null) {
1793 return ActivityManager.COMPAT_MODE_UNKNOWN;
1794 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001795 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001796 }
1797 }
1798
1799 @Override
1800 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001801 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001803 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001805 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001806 if (r == null) {
1807 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1808 return;
1809 }
1810 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001811 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 }
1813 }
1814
1815 @Override
1816 public int getLaunchedFromUid(IBinder activityToken) {
1817 ActivityRecord srec;
1818 synchronized (mGlobalLock) {
1819 srec = ActivityRecord.forTokenLocked(activityToken);
1820 }
1821 if (srec == null) {
1822 return -1;
1823 }
1824 return srec.launchedFromUid;
1825 }
1826
1827 @Override
1828 public String getLaunchedFromPackage(IBinder activityToken) {
1829 ActivityRecord srec;
1830 synchronized (mGlobalLock) {
1831 srec = ActivityRecord.forTokenLocked(activityToken);
1832 }
1833 if (srec == null) {
1834 return null;
1835 }
1836 return srec.launchedFromPackage;
1837 }
1838
1839 @Override
1840 public boolean convertFromTranslucent(IBinder token) {
1841 final long origId = Binder.clearCallingIdentity();
1842 try {
1843 synchronized (mGlobalLock) {
1844 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1845 if (r == null) {
1846 return false;
1847 }
1848 final boolean translucentChanged = r.changeWindowTranslucency(true);
1849 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001850 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001852 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 return translucentChanged;
1854 }
1855 } finally {
1856 Binder.restoreCallingIdentity(origId);
1857 }
1858 }
1859
1860 @Override
1861 public boolean convertToTranslucent(IBinder token, Bundle options) {
1862 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1863 final long origId = Binder.clearCallingIdentity();
1864 try {
1865 synchronized (mGlobalLock) {
1866 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1867 if (r == null) {
1868 return false;
1869 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001870 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 int index = task.mActivities.lastIndexOf(r);
1872 if (index > 0) {
1873 ActivityRecord under = task.mActivities.get(index - 1);
1874 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1875 }
1876 final boolean translucentChanged = r.changeWindowTranslucency(false);
1877 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001878 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001880 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001881 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001882 return translucentChanged;
1883 }
1884 } finally {
1885 Binder.restoreCallingIdentity(origId);
1886 }
1887 }
1888
1889 @Override
1890 public void notifyActivityDrawn(IBinder token) {
1891 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1892 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001893 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001895 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001896 }
1897 }
1898 }
1899
1900 @Override
1901 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1902 synchronized (mGlobalLock) {
1903 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1904 if (r == null) {
1905 return;
1906 }
1907 r.reportFullyDrawnLocked(restoredFromBundle);
1908 }
1909 }
1910
1911 @Override
1912 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1913 synchronized (mGlobalLock) {
1914 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1915 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1916 return stack.mDisplayId;
1917 }
1918 return DEFAULT_DISPLAY;
1919 }
1920 }
1921
1922 @Override
1923 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001924 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 long ident = Binder.clearCallingIdentity();
1926 try {
1927 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001928 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001930 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001931 }
1932 return null;
1933 }
1934 } finally {
1935 Binder.restoreCallingIdentity(ident);
1936 }
1937 }
1938
1939 @Override
1940 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001941 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1943 final long callingId = Binder.clearCallingIdentity();
1944 try {
1945 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001946 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 if (stack == null) {
1948 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1949 return;
1950 }
1951 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001952 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001953 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 }
1955 }
1956 } finally {
1957 Binder.restoreCallingIdentity(callingId);
1958 }
1959 }
1960
1961 @Override
1962 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001963 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1965 final long callingId = Binder.clearCallingIdentity();
1966 try {
1967 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001968 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001969 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 if (task == null) {
1971 return;
1972 }
1973 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001974 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001975 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 }
1977 }
1978 } finally {
1979 Binder.restoreCallingIdentity(callingId);
1980 }
1981 }
1982
1983 @Override
1984 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001985 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 synchronized (mGlobalLock) {
1987 final long ident = Binder.clearCallingIdentity();
1988 try {
1989 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1990 "remove-task");
1991 } finally {
1992 Binder.restoreCallingIdentity(ident);
1993 }
1994 }
1995 }
1996
1997 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001998 public void removeAllVisibleRecentTasks() {
1999 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2000 synchronized (mGlobalLock) {
2001 final long ident = Binder.clearCallingIdentity();
2002 try {
2003 getRecentTasks().removeAllVisibleTasks();
2004 } finally {
2005 Binder.restoreCallingIdentity(ident);
2006 }
2007 }
2008 }
2009
2010 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2012 synchronized (mGlobalLock) {
2013 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2014 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002015 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 }
2018 return false;
2019 }
2020
2021 @Override
2022 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2023 Intent resultData) {
2024
2025 synchronized (mGlobalLock) {
2026 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2027 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002028 return r.getActivityStack().navigateUpToLocked(
2029 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 }
2031 return false;
2032 }
2033 }
2034
2035 /**
2036 * Attempts to move a task backwards in z-order (the order of activities within the task is
2037 * unchanged).
2038 *
2039 * There are several possible results of this call:
2040 * - if the task is locked, then we will show the lock toast
2041 * - if there is a task behind the provided task, then that task is made visible and resumed as
2042 * this task is moved to the back
2043 * - otherwise, if there are no other tasks in the stack:
2044 * - if this task is in the pinned stack, then we remove the stack completely, which will
2045 * have the effect of moving the task to the top or bottom of the fullscreen stack
2046 * (depending on whether it is visible)
2047 * - otherwise, we simply return home and hide this task
2048 *
2049 * @param token A reference to the activity we wish to move
2050 * @param nonRoot If false then this only works if the activity is the root
2051 * of a task; if true it will work for any activity in a task.
2052 * @return Returns true if the move completed, false if not.
2053 */
2054 @Override
2055 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002056 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 synchronized (mGlobalLock) {
2058 final long origId = Binder.clearCallingIdentity();
2059 try {
2060 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002061 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (task != null) {
2063 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(origId);
2067 }
2068 }
2069 return false;
2070 }
2071
2072 @Override
2073 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002074 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 long ident = Binder.clearCallingIdentity();
2076 Rect rect = new Rect();
2077 try {
2078 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002079 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2081 if (task == null) {
2082 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2083 return rect;
2084 }
2085 if (task.getStack() != null) {
2086 // Return the bounds from window manager since it will be adjusted for various
2087 // things like the presense of a docked stack for tasks that aren't resizeable.
2088 task.getWindowContainerBounds(rect);
2089 } else {
2090 // Task isn't in window manager yet since it isn't associated with a stack.
2091 // Return the persist value from activity manager
2092 if (!task.matchParentBounds()) {
2093 rect.set(task.getBounds());
2094 } else if (task.mLastNonFullscreenBounds != null) {
2095 rect.set(task.mLastNonFullscreenBounds);
2096 }
2097 }
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(ident);
2101 }
2102 return rect;
2103 }
2104
2105 @Override
2106 public ActivityManager.TaskDescription getTaskDescription(int id) {
2107 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002108 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002110 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2112 if (tr != null) {
2113 return tr.lastTaskDescription;
2114 }
2115 }
2116 return null;
2117 }
2118
2119 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002120 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2121 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2122 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2123 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2124 return;
2125 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002126 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002127 synchronized (mGlobalLock) {
2128 final long ident = Binder.clearCallingIdentity();
2129 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002130 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002131 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002132 if (task == null) {
2133 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2134 return;
2135 }
2136
2137 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2138 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2139
2140 if (!task.isActivityTypeStandardOrUndefined()) {
2141 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2142 + " non-standard task " + taskId + " to windowing mode="
2143 + windowingMode);
2144 }
2145
2146 final ActivityStack stack = task.getStack();
2147 if (toTop) {
2148 stack.moveToFront("setTaskWindowingMode", task);
2149 }
2150 stack.setWindowingMode(windowingMode);
2151 } finally {
2152 Binder.restoreCallingIdentity(ident);
2153 }
2154 }
2155 }
2156
2157 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002159 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002160 ActivityRecord r = getCallingRecordLocked(token);
2161 return r != null ? r.info.packageName : null;
2162 }
2163 }
2164
2165 @Override
2166 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002167 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 ActivityRecord r = getCallingRecordLocked(token);
2169 return r != null ? r.intent.getComponent() : null;
2170 }
2171 }
2172
2173 private ActivityRecord getCallingRecordLocked(IBinder token) {
2174 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2175 if (r == null) {
2176 return null;
2177 }
2178 return r.resultTo;
2179 }
2180
2181 @Override
2182 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184
2185 synchronized (mGlobalLock) {
2186 final long origId = Binder.clearCallingIdentity();
2187 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002188 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 } finally {
2190 Binder.restoreCallingIdentity(origId);
2191 }
2192 }
2193 }
2194
2195 /**
2196 * TODO: Add mController hook
2197 */
2198 @Override
2199 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201
2202 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2203 synchronized (mGlobalLock) {
2204 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2205 false /* fromRecents */);
2206 }
2207 }
2208
2209 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2210 boolean fromRecents) {
2211
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 Binder.getCallingUid(), -1, -1, "Task to front")) {
2214 SafeActivityOptions.abort(options);
2215 return;
2216 }
2217 final long origId = Binder.clearCallingIdentity();
2218 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002219 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220 if (task == null) {
2221 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002222 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 return;
2224 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002225 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002227 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 return;
2229 }
2230 ActivityOptions realOptions = options != null
2231 ? options.getOptions(mStackSupervisor)
2232 : null;
2233 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2234 false /* forceNonResizable */);
2235
2236 final ActivityRecord topActivity = task.getTopActivity();
2237 if (topActivity != null) {
2238
2239 // We are reshowing a task, use a starting window to hide the initial draw delay
2240 // so the transition can start earlier.
2241 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2242 true /* taskSwitch */, fromRecents);
2243 }
2244 } finally {
2245 Binder.restoreCallingIdentity(origId);
2246 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 }
2248
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002249 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2250 int callingPid, int callingUid, String name) {
2251 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2252 return true;
2253 }
2254
2255 if (getRecentTasks().isCallerRecents(sourceUid)) {
2256 return true;
2257 }
2258
2259 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2260 if (perm == PackageManager.PERMISSION_GRANTED) {
2261 return true;
2262 }
2263 if (checkAllowAppSwitchUid(sourceUid)) {
2264 return true;
2265 }
2266
2267 // If the actual IPC caller is different from the logical source, then
2268 // also see if they are allowed to control app switches.
2269 if (callingUid != -1 && callingUid != sourceUid) {
2270 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2271 if (perm == PackageManager.PERMISSION_GRANTED) {
2272 return true;
2273 }
2274 if (checkAllowAppSwitchUid(callingUid)) {
2275 return true;
2276 }
2277 }
2278
2279 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2280 return false;
2281 }
2282
2283 private boolean checkAllowAppSwitchUid(int uid) {
2284 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2285 if (types != null) {
2286 for (int i = types.size() - 1; i >= 0; i--) {
2287 if (types.valueAt(i).intValue() == uid) {
2288 return true;
2289 }
2290 }
2291 }
2292 return false;
2293 }
2294
2295 @Override
2296 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2297 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2298 "setActivityController()");
2299 synchronized (mGlobalLock) {
2300 mController = controller;
2301 mControllerIsAMonkey = imAMonkey;
2302 Watchdog.getInstance().setActivityController(controller);
2303 }
2304 }
2305
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002306 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 synchronized (mGlobalLock) {
2308 return mController != null && mControllerIsAMonkey;
2309 }
2310 }
2311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 @Override
2313 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2314 synchronized (mGlobalLock) {
2315 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2316 }
2317 }
2318
2319 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002320 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2321 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2322 }
2323
2324 @Override
2325 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2326 @WindowConfiguration.ActivityType int ignoreActivityType,
2327 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2328 final int callingUid = Binder.getCallingUid();
2329 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2330
2331 synchronized (mGlobalLock) {
2332 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2333
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002334 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002336 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002337 ignoreWindowingMode, callingUid, allowed);
2338 }
2339
2340 return list;
2341 }
2342
2343 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002344 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2345 synchronized (mGlobalLock) {
2346 final long origId = Binder.clearCallingIdentity();
2347 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2348 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002349 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 }
2351 Binder.restoreCallingIdentity(origId);
2352 }
2353 }
2354
2355 @Override
2356 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358 ActivityStack stack = ActivityRecord.getStackLocked(token);
2359 if (stack != null) {
2360 return stack.willActivityBeVisibleLocked(token);
2361 }
2362 return false;
2363 }
2364 }
2365
2366 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002368 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002369 synchronized (mGlobalLock) {
2370 final long ident = Binder.clearCallingIdentity();
2371 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002372 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002373 if (task == null) {
2374 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2375 return;
2376 }
2377
2378 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2379 + " to stackId=" + stackId + " toTop=" + toTop);
2380
Wale Ogunwaled32da472018-11-16 07:19:28 -08002381 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002382 if (stack == null) {
2383 throw new IllegalStateException(
2384 "moveTaskToStack: No stack for stackId=" + stackId);
2385 }
2386 if (!stack.isActivityTypeStandardOrUndefined()) {
2387 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2388 + taskId + " to stack " + stackId);
2389 }
2390 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002391 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002392 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2393 }
2394 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2395 "moveTaskToStack");
2396 } finally {
2397 Binder.restoreCallingIdentity(ident);
2398 }
2399 }
2400 }
2401
2402 @Override
2403 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2404 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002405 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002406
2407 final long ident = Binder.clearCallingIdentity();
2408 try {
2409 synchronized (mGlobalLock) {
2410 if (animate) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002411 final PinnedActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002412 if (stack == null) {
2413 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2414 return;
2415 }
2416 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2417 throw new IllegalArgumentException("Stack: " + stackId
2418 + " doesn't support animated resize.");
2419 }
2420 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2421 animationDuration, false /* fromFullscreen */);
2422 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002423 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002424 if (stack == null) {
2425 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2426 return;
2427 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002428 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002429 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2430 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2431 }
2432 }
2433 } finally {
2434 Binder.restoreCallingIdentity(ident);
2435 }
2436 }
2437
2438 /**
2439 * Moves the specified task to the primary-split-screen stack.
2440 *
2441 * @param taskId Id of task to move.
2442 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2443 * exist already. See
2444 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2445 * and
2446 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2447 * @param toTop If the task and stack should be moved to the top.
2448 * @param animate Whether we should play an animation for the moving the task.
2449 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2450 * stack. Pass {@code null} to use default bounds.
2451 * @param showRecents If the recents activity should be shown on the other side of the task
2452 * going into split-screen mode.
2453 */
2454 @Override
2455 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2456 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002458 "setTaskWindowingModeSplitScreenPrimary()");
2459 synchronized (mGlobalLock) {
2460 final long ident = Binder.clearCallingIdentity();
2461 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002462 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002463 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002464 if (task == null) {
2465 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2466 return false;
2467 }
2468 if (DEBUG_STACK) Slog.d(TAG_STACK,
2469 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2470 + " to createMode=" + createMode + " toTop=" + toTop);
2471 if (!task.isActivityTypeStandardOrUndefined()) {
2472 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2473 + " non-standard task " + taskId + " to split-screen windowing mode");
2474 }
2475
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002476 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002477 final int windowingMode = task.getWindowingMode();
2478 final ActivityStack stack = task.getStack();
2479 if (toTop) {
2480 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2481 }
2482 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002483 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2484 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002485 return windowingMode != task.getWindowingMode();
2486 } finally {
2487 Binder.restoreCallingIdentity(ident);
2488 }
2489 }
2490 }
2491
2492 /**
2493 * Removes stacks in the input windowing modes from the system if they are of activity type
2494 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2495 */
2496 @Override
2497 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002498 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002499 "removeStacksInWindowingModes()");
2500
2501 synchronized (mGlobalLock) {
2502 final long ident = Binder.clearCallingIdentity();
2503 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002504 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002505 } finally {
2506 Binder.restoreCallingIdentity(ident);
2507 }
2508 }
2509 }
2510
2511 @Override
2512 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002514 "removeStacksWithActivityTypes()");
2515
2516 synchronized (mGlobalLock) {
2517 final long ident = Binder.clearCallingIdentity();
2518 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002519 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002520 } finally {
2521 Binder.restoreCallingIdentity(ident);
2522 }
2523 }
2524 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002525
2526 @Override
2527 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2528 int userId) {
2529 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002530 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2531 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002532 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002533 final boolean detailed = checkGetTasksPermission(
2534 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2535 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002536 == PackageManager.PERMISSION_GRANTED;
2537
2538 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002539 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 callingUid);
2541 }
2542 }
2543
2544 @Override
2545 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002546 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002547 long ident = Binder.clearCallingIdentity();
2548 try {
2549 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002550 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002551 }
2552 } finally {
2553 Binder.restoreCallingIdentity(ident);
2554 }
2555 }
2556
2557 @Override
2558 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002559 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560 long ident = Binder.clearCallingIdentity();
2561 try {
2562 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002564 }
2565 } finally {
2566 Binder.restoreCallingIdentity(ident);
2567 }
2568 }
2569
2570 @Override
2571 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002573 final long callingUid = Binder.getCallingUid();
2574 final long origId = Binder.clearCallingIdentity();
2575 try {
2576 synchronized (mGlobalLock) {
2577 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002578 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002579 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2580 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2581 }
2582 } finally {
2583 Binder.restoreCallingIdentity(origId);
2584 }
2585 }
2586
2587 @Override
2588 public void startLockTaskModeByToken(IBinder token) {
2589 synchronized (mGlobalLock) {
2590 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2591 if (r == null) {
2592 return;
2593 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002594 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002595 }
2596 }
2597
2598 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002599 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002600 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002601 // This makes inner call to look as if it was initiated by system.
2602 long ident = Binder.clearCallingIdentity();
2603 try {
2604 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002605 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002606 MATCH_TASK_IN_STACKS_ONLY);
2607 if (task == null) {
2608 return;
2609 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002610
2611 // When starting lock task mode the stack must be in front and focused
2612 task.getStack().moveToFront("startSystemLockTaskMode");
2613 startLockTaskModeLocked(task, true /* isSystemCaller */);
2614 }
2615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
2618 }
2619
2620 @Override
2621 public void stopLockTaskModeByToken(IBinder token) {
2622 synchronized (mGlobalLock) {
2623 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2624 if (r == null) {
2625 return;
2626 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002627 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002628 }
2629 }
2630
2631 /**
2632 * This API should be called by SystemUI only when user perform certain action to dismiss
2633 * lock task mode. We should only dismiss pinned lock task mode in this case.
2634 */
2635 @Override
2636 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002637 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002638 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2639 }
2640
2641 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2642 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2643 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2644 return;
2645 }
2646
Wale Ogunwaled32da472018-11-16 07:19:28 -08002647 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002648 if (stack == null || task != stack.topTask()) {
2649 throw new IllegalArgumentException("Invalid task, not in foreground");
2650 }
2651
2652 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2653 // system or a specific app.
2654 // * System-initiated requests will only start the pinned mode (screen pinning)
2655 // * App-initiated requests
2656 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2657 // - will start the pinned mode, otherwise
2658 final int callingUid = Binder.getCallingUid();
2659 long ident = Binder.clearCallingIdentity();
2660 try {
2661 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002662 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002664 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 } finally {
2666 Binder.restoreCallingIdentity(ident);
2667 }
2668 }
2669
2670 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2671 final int callingUid = Binder.getCallingUid();
2672 long ident = Binder.clearCallingIdentity();
2673 try {
2674 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002675 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002676 }
2677 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2678 // task and jumping straight into a call in the case of emergency call back.
2679 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2680 if (tm != null) {
2681 tm.showInCallScreen(false);
2682 }
2683 } finally {
2684 Binder.restoreCallingIdentity(ident);
2685 }
2686 }
2687
2688 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002689 public void updateLockTaskPackages(int userId, String[] packages) {
2690 final int callingUid = Binder.getCallingUid();
2691 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2692 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2693 "updateLockTaskPackages()");
2694 }
2695 synchronized (this) {
2696 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2697 + Arrays.toString(packages));
2698 getLockTaskController().updateLockTaskPackages(userId, packages);
2699 }
2700 }
2701
2702 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002703 public boolean isInLockTaskMode() {
2704 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2705 }
2706
2707 @Override
2708 public int getLockTaskModeState() {
2709 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002710 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002711 }
2712 }
2713
2714 @Override
2715 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2716 synchronized (mGlobalLock) {
2717 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2718 if (r != null) {
2719 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002720 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002722 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002723 }
2724 }
2725 }
2726
2727 @Override
2728 public Bundle getActivityOptions(IBinder token) {
2729 final long origId = Binder.clearCallingIdentity();
2730 try {
2731 synchronized (mGlobalLock) {
2732 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2733 if (r != null) {
2734 final ActivityOptions activityOptions = r.takeOptionsLocked();
2735 return activityOptions == null ? null : activityOptions.toBundle();
2736 }
2737 return null;
2738 }
2739 } finally {
2740 Binder.restoreCallingIdentity(origId);
2741 }
2742 }
2743
2744 @Override
2745 public List<IBinder> getAppTasks(String callingPackage) {
2746 int callingUid = Binder.getCallingUid();
2747 long ident = Binder.clearCallingIdentity();
2748 try {
2749 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002750 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 }
2752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756
2757 @Override
2758 public void finishVoiceTask(IVoiceInteractionSession session) {
2759 synchronized (mGlobalLock) {
2760 final long origId = Binder.clearCallingIdentity();
2761 try {
2762 // TODO: VI Consider treating local voice interactions and voice tasks
2763 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002764 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 } finally {
2766 Binder.restoreCallingIdentity(origId);
2767 }
2768 }
2769
2770 }
2771
2772 @Override
2773 public boolean isTopOfTask(IBinder token) {
2774 synchronized (mGlobalLock) {
2775 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002776 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 }
2778 }
2779
2780 @Override
2781 public void notifyLaunchTaskBehindComplete(IBinder token) {
2782 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2783 }
2784
2785 @Override
2786 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002787 mH.post(() -> {
2788 synchronized (mGlobalLock) {
2789 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002790 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002791 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002792 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002793 } catch (RemoteException e) {
2794 }
2795 }
2796 }
2797
2798 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 }
2800
2801 /** Called from an app when assist data is ready. */
2802 @Override
2803 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2804 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 synchronized (pae) {
2807 pae.result = extras;
2808 pae.structure = structure;
2809 pae.content = content;
2810 if (referrer != null) {
2811 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2812 }
2813 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002814 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002815 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2816 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 structure.setHomeActivity(pae.isHome);
2818 }
2819 pae.haveResult = true;
2820 pae.notifyAll();
2821 if (pae.intent == null && pae.receiver == null) {
2822 // Caller is just waiting for the result.
2823 return;
2824 }
2825 }
2826 // We are now ready to launch the assist activity.
2827 IAssistDataReceiver sendReceiver = null;
2828 Bundle sendBundle = null;
2829 synchronized (mGlobalLock) {
2830 buildAssistBundleLocked(pae, extras);
2831 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002832 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 if (!exists) {
2834 // Timed out.
2835 return;
2836 }
2837
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002838 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 // Caller wants result sent back to them.
2840 sendBundle = new Bundle();
2841 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2842 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2843 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2844 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2845 }
2846 }
2847 if (sendReceiver != null) {
2848 try {
2849 sendReceiver.onHandleAssistData(sendBundle);
2850 } catch (RemoteException e) {
2851 }
2852 return;
2853 }
2854
2855 final long ident = Binder.clearCallingIdentity();
2856 try {
2857 if (TextUtils.equals(pae.intent.getAction(),
2858 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2859 pae.intent.putExtras(pae.extras);
2860 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2861 } else {
2862 pae.intent.replaceExtras(pae.extras);
2863 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2864 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2865 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002866 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867
2868 try {
2869 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2870 } catch (ActivityNotFoundException e) {
2871 Slog.w(TAG, "No activity to handle assist action.", e);
2872 }
2873 }
2874 } finally {
2875 Binder.restoreCallingIdentity(ident);
2876 }
2877 }
2878
2879 @Override
2880 public int addAppTask(IBinder activityToken, Intent intent,
2881 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2882 final int callingUid = Binder.getCallingUid();
2883 final long callingIdent = Binder.clearCallingIdentity();
2884
2885 try {
2886 synchronized (mGlobalLock) {
2887 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2888 if (r == null) {
2889 throw new IllegalArgumentException("Activity does not exist; token="
2890 + activityToken);
2891 }
2892 ComponentName comp = intent.getComponent();
2893 if (comp == null) {
2894 throw new IllegalArgumentException("Intent " + intent
2895 + " must specify explicit component");
2896 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002897 if (thumbnail.getWidth() != mThumbnailWidth
2898 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899 throw new IllegalArgumentException("Bad thumbnail size: got "
2900 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002901 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 if (intent.getSelector() != null) {
2904 intent.setSelector(null);
2905 }
2906 if (intent.getSourceBounds() != null) {
2907 intent.setSourceBounds(null);
2908 }
2909 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2910 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2911 // The caller has added this as an auto-remove task... that makes no
2912 // sense, so turn off auto-remove.
2913 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2914 }
2915 }
2916 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2917 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2918 if (ainfo.applicationInfo.uid != callingUid) {
2919 throw new SecurityException(
2920 "Can't add task for another application: target uid="
2921 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2922 }
2923
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002926 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002928 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 // The app has too many tasks already and we can't add any more
2930 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2931 return INVALID_TASK_ID;
2932 }
2933 task.lastTaskDescription.copyFrom(description);
2934
2935 // TODO: Send the thumbnail to WM to store it.
2936
2937 return task.taskId;
2938 }
2939 } finally {
2940 Binder.restoreCallingIdentity(callingIdent);
2941 }
2942 }
2943
2944 @Override
2945 public Point getAppTaskThumbnailSize() {
2946 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002947 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 }
2949 }
2950
2951 @Override
2952 public void setTaskResizeable(int taskId, int resizeableMode) {
2953 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002954 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2956 if (task == null) {
2957 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2958 return;
2959 }
2960 task.setResizeMode(resizeableMode);
2961 }
2962 }
2963
2964 @Override
2965 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002966 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002967 long ident = Binder.clearCallingIdentity();
2968 try {
2969 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002970 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002971 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 if (task == null) {
2973 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2974 return;
2975 }
2976 // Place the task in the right stack if it isn't there already based on
2977 // the requested bounds.
2978 // The stack transition logic is:
2979 // - a null bounds on a freeform task moves that task to fullscreen
2980 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2981 // that task to freeform
2982 // - otherwise the task is not moved
2983 ActivityStack stack = task.getStack();
2984 if (!task.getWindowConfiguration().canResizeTask()) {
2985 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2986 }
2987 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2988 stack = stack.getDisplay().getOrCreateStack(
2989 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2990 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2991 stack = stack.getDisplay().getOrCreateStack(
2992 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2993 }
2994
2995 // Reparent the task to the right stack if necessary
2996 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2997 if (stack != task.getStack()) {
2998 // Defer resume until the task is resized below
2999 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3000 DEFER_RESUME, "resizeTask");
3001 preserveWindow = false;
3002 }
3003
3004 // After reparenting (which only resizes the task to the stack bounds), resize the
3005 // task to the actual bounds provided
3006 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3007 }
3008 } finally {
3009 Binder.restoreCallingIdentity(ident);
3010 }
3011 }
3012
3013 @Override
3014 public boolean releaseActivityInstance(IBinder token) {
3015 synchronized (mGlobalLock) {
3016 final long origId = Binder.clearCallingIdentity();
3017 try {
3018 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3019 if (r == null) {
3020 return false;
3021 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003022 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 } finally {
3024 Binder.restoreCallingIdentity(origId);
3025 }
3026 }
3027 }
3028
3029 @Override
3030 public void releaseSomeActivities(IApplicationThread appInt) {
3031 synchronized (mGlobalLock) {
3032 final long origId = Binder.clearCallingIdentity();
3033 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003034 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003035 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 } finally {
3037 Binder.restoreCallingIdentity(origId);
3038 }
3039 }
3040 }
3041
3042 @Override
3043 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003044 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003045 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 != PackageManager.PERMISSION_GRANTED) {
3047 throw new SecurityException("Requires permission "
3048 + android.Manifest.permission.DEVICE_POWER);
3049 }
3050
3051 synchronized (mGlobalLock) {
3052 long ident = Binder.clearCallingIdentity();
3053 if (mKeyguardShown != keyguardShowing) {
3054 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003055 final Message msg = PooledLambda.obtainMessage(
3056 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3057 keyguardShowing);
3058 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 }
3060 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003061 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003062 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003063 } finally {
3064 Binder.restoreCallingIdentity(ident);
3065 }
3066 }
3067
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003068 mH.post(() -> {
3069 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3070 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3071 }
3072 });
3073 }
3074
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003075 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003076 mH.post(() -> {
3077 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3078 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3079 }
3080 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 }
3082
3083 @Override
3084 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003085 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3086 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087
3088 final File passedIconFile = new File(filePath);
3089 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3090 passedIconFile.getName());
3091 if (!legitIconFile.getPath().equals(filePath)
3092 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3093 throw new IllegalArgumentException("Bad file path: " + filePath
3094 + " passed for userId " + userId);
3095 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003096 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 }
3098
3099 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003100 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003101 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3102 final ActivityOptions activityOptions = safeOptions != null
3103 ? safeOptions.getOptions(mStackSupervisor)
3104 : null;
3105 if (activityOptions == null
3106 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3107 || activityOptions.getCustomInPlaceResId() == 0) {
3108 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3109 "with valid animation");
3110 }
lumark588a3e82018-07-20 18:53:54 +08003111 // Get top display of front most application.
3112 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3113 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003114 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3115 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3116 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003117 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003118 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003119 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003120 }
3121
3122 @Override
3123 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003124 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 synchronized (mGlobalLock) {
3126 final long ident = Binder.clearCallingIdentity();
3127 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003128 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003129 if (stack == null) {
3130 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3131 return;
3132 }
3133 if (!stack.isActivityTypeStandardOrUndefined()) {
3134 throw new IllegalArgumentException(
3135 "Removing non-standard stack is not allowed.");
3136 }
3137 mStackSupervisor.removeStack(stack);
3138 } finally {
3139 Binder.restoreCallingIdentity(ident);
3140 }
3141 }
3142 }
3143
3144 @Override
3145 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003146 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147
3148 synchronized (mGlobalLock) {
3149 final long ident = Binder.clearCallingIdentity();
3150 try {
3151 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3152 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003153 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 } finally {
3155 Binder.restoreCallingIdentity(ident);
3156 }
3157 }
3158 }
3159
3160 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 public void exitFreeformMode(IBinder token) {
3162 synchronized (mGlobalLock) {
3163 long ident = Binder.clearCallingIdentity();
3164 try {
3165 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3166 if (r == null) {
3167 throw new IllegalArgumentException(
3168 "exitFreeformMode: No activity record matching token=" + token);
3169 }
3170
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003171 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003172 if (stack == null || !stack.inFreeformWindowingMode()) {
3173 throw new IllegalStateException(
3174 "exitFreeformMode: You can only go fullscreen from freeform.");
3175 }
3176
3177 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3178 } finally {
3179 Binder.restoreCallingIdentity(ident);
3180 }
3181 }
3182 }
3183
3184 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3185 @Override
3186 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003187 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003189 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003190 }
3191
3192 /** Unregister a task stack listener so that it stops receiving callbacks. */
3193 @Override
3194 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003195 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003197 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 }
3199
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 @Override
3201 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3202 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3203 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3204 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3205 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3206 }
3207
3208 @Override
3209 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3210 IBinder activityToken, int flags) {
3211 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3212 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3213 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3214 }
3215
3216 @Override
3217 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3218 Bundle args) {
3219 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3220 true /* focused */, true /* newSessionId */, userHandle, args,
3221 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3222 }
3223
3224 @Override
3225 public Bundle getAssistContextExtras(int requestType) {
3226 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3227 null, null, true /* focused */, true /* newSessionId */,
3228 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3229 if (pae == null) {
3230 return null;
3231 }
3232 synchronized (pae) {
3233 while (!pae.haveResult) {
3234 try {
3235 pae.wait();
3236 } catch (InterruptedException e) {
3237 }
3238 }
3239 }
3240 synchronized (mGlobalLock) {
3241 buildAssistBundleLocked(pae, pae.result);
3242 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003243 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 }
3245 return pae.extras;
3246 }
3247
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003248 /**
3249 * Binder IPC calls go through the public entry point.
3250 * This can be called with or without the global lock held.
3251 */
3252 private static int checkCallingPermission(String permission) {
3253 return checkPermission(
3254 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3255 }
3256
3257 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003258 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003259 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3260 mAmInternal.enforceCallingPermission(permission, func);
3261 }
3262 }
3263
3264 @VisibleForTesting
3265 int checkGetTasksPermission(String permission, int pid, int uid) {
3266 return checkPermission(permission, pid, uid);
3267 }
3268
3269 static int checkPermission(String permission, int pid, int uid) {
3270 if (permission == null) {
3271 return PackageManager.PERMISSION_DENIED;
3272 }
3273 return checkComponentPermission(permission, pid, uid, -1, true);
3274 }
3275
Wale Ogunwale214f3482018-10-04 11:00:47 -07003276 public static int checkComponentPermission(String permission, int pid, int uid,
3277 int owningUid, boolean exported) {
3278 return ActivityManagerService.checkComponentPermission(
3279 permission, pid, uid, owningUid, exported);
3280 }
3281
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003282 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3283 if (getRecentTasks().isCallerRecents(callingUid)) {
3284 // Always allow the recents component to get tasks
3285 return true;
3286 }
3287
3288 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3289 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3290 if (!allowed) {
3291 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3292 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3293 // Temporary compatibility: some existing apps on the system image may
3294 // still be requesting the old permission and not switched to the new
3295 // one; if so, we'll still allow them full access. This means we need
3296 // to see if they are holding the old permission and are a system app.
3297 try {
3298 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3299 allowed = true;
3300 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3301 + " is using old GET_TASKS but privileged; allowing");
3302 }
3303 } catch (RemoteException e) {
3304 }
3305 }
3306 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3307 + " does not hold REAL_GET_TASKS; limiting output");
3308 }
3309 return allowed;
3310 }
3311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3313 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3314 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3315 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003316 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 "enqueueAssistContext()");
3318
3319 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003320 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 if (activity == null) {
3322 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3323 return null;
3324 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003325 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003326 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3327 return null;
3328 }
3329 if (focused) {
3330 if (activityToken != null) {
3331 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3332 if (activity != caller) {
3333 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3334 + " is not current top " + activity);
3335 return null;
3336 }
3337 }
3338 } else {
3339 activity = ActivityRecord.forTokenLocked(activityToken);
3340 if (activity == null) {
3341 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3342 + " couldn't be found");
3343 return null;
3344 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003345 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3347 return null;
3348 }
3349 }
3350
3351 PendingAssistExtras pae;
3352 Bundle extras = new Bundle();
3353 if (args != null) {
3354 extras.putAll(args);
3355 }
3356 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003357 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358
3359 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3360 userHandle);
3361 pae.isHome = activity.isActivityTypeHome();
3362
3363 // Increment the sessionId if necessary
3364 if (newSessionId) {
3365 mViSessionId++;
3366 }
3367 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003368 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3369 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003371 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 } catch (RemoteException e) {
3373 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3374 return null;
3375 }
3376 return pae;
3377 }
3378 }
3379
3380 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3381 if (result != null) {
3382 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3383 }
3384 if (pae.hint != null) {
3385 pae.extras.putBoolean(pae.hint, true);
3386 }
3387 }
3388
3389 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3390 IAssistDataReceiver receiver;
3391 synchronized (mGlobalLock) {
3392 mPendingAssistExtras.remove(pae);
3393 receiver = pae.receiver;
3394 }
3395 if (receiver != null) {
3396 // Caller wants result sent back to them.
3397 Bundle sendBundle = new Bundle();
3398 // At least return the receiver extras
3399 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3400 try {
3401 pae.receiver.onHandleAssistData(sendBundle);
3402 } catch (RemoteException e) {
3403 }
3404 }
3405 }
3406
3407 public class PendingAssistExtras extends Binder implements Runnable {
3408 public final ActivityRecord activity;
3409 public boolean isHome;
3410 public final Bundle extras;
3411 public final Intent intent;
3412 public final String hint;
3413 public final IAssistDataReceiver receiver;
3414 public final int userHandle;
3415 public boolean haveResult = false;
3416 public Bundle result = null;
3417 public AssistStructure structure = null;
3418 public AssistContent content = null;
3419 public Bundle receiverExtras;
3420
3421 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3422 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3423 int _userHandle) {
3424 activity = _activity;
3425 extras = _extras;
3426 intent = _intent;
3427 hint = _hint;
3428 receiver = _receiver;
3429 receiverExtras = _receiverExtras;
3430 userHandle = _userHandle;
3431 }
3432
3433 @Override
3434 public void run() {
3435 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3436 synchronized (this) {
3437 haveResult = true;
3438 notifyAll();
3439 }
3440 pendingAssistExtrasTimedOut(this);
3441 }
3442 }
3443
3444 @Override
3445 public boolean isAssistDataAllowedOnCurrentActivity() {
3446 int userId;
3447 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003448 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3450 return false;
3451 }
3452
3453 final ActivityRecord activity = focusedStack.getTopActivity();
3454 if (activity == null) {
3455 return false;
3456 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003457 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 }
3459 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3460 }
3461
3462 @Override
3463 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3464 long ident = Binder.clearCallingIdentity();
3465 try {
3466 synchronized (mGlobalLock) {
3467 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003468 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 if (top != caller) {
3470 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3471 + " is not current top " + top);
3472 return false;
3473 }
3474 if (!top.nowVisible) {
3475 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3476 + " is not visible");
3477 return false;
3478 }
3479 }
3480 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3481 token);
3482 } finally {
3483 Binder.restoreCallingIdentity(ident);
3484 }
3485 }
3486
3487 @Override
3488 public boolean isRootVoiceInteraction(IBinder token) {
3489 synchronized (mGlobalLock) {
3490 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3491 if (r == null) {
3492 return false;
3493 }
3494 return r.rootVoiceInteraction;
3495 }
3496 }
3497
Wale Ogunwalef6733932018-06-27 05:14:34 -07003498 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3499 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3500 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3501 if (activityToCallback == null) return;
3502 activityToCallback.setVoiceSessionLocked(voiceSession);
3503
3504 // Inform the activity
3505 try {
3506 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3507 voiceInteractor);
3508 long token = Binder.clearCallingIdentity();
3509 try {
3510 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3511 } finally {
3512 Binder.restoreCallingIdentity(token);
3513 }
3514 // TODO: VI Should we cache the activity so that it's easier to find later
3515 // rather than scan through all the stacks and activities?
3516 } catch (RemoteException re) {
3517 activityToCallback.clearVoiceSessionLocked();
3518 // TODO: VI Should this terminate the voice session?
3519 }
3520 }
3521
3522 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3523 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3524 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3525 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3526 boolean wasRunningVoice = mRunningVoice != null;
3527 mRunningVoice = session;
3528 if (!wasRunningVoice) {
3529 mVoiceWakeLock.acquire();
3530 updateSleepIfNeededLocked();
3531 }
3532 }
3533 }
3534
3535 void finishRunningVoiceLocked() {
3536 if (mRunningVoice != null) {
3537 mRunningVoice = null;
3538 mVoiceWakeLock.release();
3539 updateSleepIfNeededLocked();
3540 }
3541 }
3542
3543 @Override
3544 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3545 synchronized (mGlobalLock) {
3546 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3547 if (keepAwake) {
3548 mVoiceWakeLock.acquire();
3549 } else {
3550 mVoiceWakeLock.release();
3551 }
3552 }
3553 }
3554 }
3555
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003556 @Override
3557 public ComponentName getActivityClassForToken(IBinder token) {
3558 synchronized (mGlobalLock) {
3559 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3560 if (r == null) {
3561 return null;
3562 }
3563 return r.intent.getComponent();
3564 }
3565 }
3566
3567 @Override
3568 public String getPackageForToken(IBinder token) {
3569 synchronized (mGlobalLock) {
3570 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3571 if (r == null) {
3572 return null;
3573 }
3574 return r.packageName;
3575 }
3576 }
3577
3578 @Override
3579 public void showLockTaskEscapeMessage(IBinder token) {
3580 synchronized (mGlobalLock) {
3581 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3582 if (r == null) {
3583 return;
3584 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003585 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003586 }
3587 }
3588
3589 @Override
3590 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003591 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592 final long token = Binder.clearCallingIdentity();
3593 try {
3594 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003595 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003596 }
3597 } finally {
3598 Binder.restoreCallingIdentity(token);
3599 }
3600 }
3601
3602 /**
3603 * Try to place task to provided position. The final position might be different depending on
3604 * current user and stacks state. The task will be moved to target stack if it's currently in
3605 * different stack.
3606 */
3607 @Override
3608 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003609 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610 synchronized (mGlobalLock) {
3611 long ident = Binder.clearCallingIdentity();
3612 try {
3613 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3614 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003615 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003616 if (task == null) {
3617 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3618 + taskId);
3619 }
3620
Wale Ogunwaled32da472018-11-16 07:19:28 -08003621 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622
3623 if (stack == null) {
3624 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3625 + stackId);
3626 }
3627 if (!stack.isActivityTypeStandardOrUndefined()) {
3628 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3629 + " the position of task " + taskId + " in/to non-standard stack");
3630 }
3631
3632 // TODO: Have the callers of this API call a separate reparent method if that is
3633 // what they intended to do vs. having this method also do reparenting.
3634 if (task.getStack() == stack) {
3635 // Change position in current stack.
3636 stack.positionChildAt(task, position);
3637 } else {
3638 // Reparent to new stack.
3639 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3640 !DEFER_RESUME, "positionTaskInStack");
3641 }
3642 } finally {
3643 Binder.restoreCallingIdentity(ident);
3644 }
3645 }
3646 }
3647
3648 @Override
3649 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3650 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3651 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3652 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3653 synchronized (mGlobalLock) {
3654 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3655 if (record == null) {
3656 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3657 + "found for: " + token);
3658 }
3659 record.setSizeConfigurations(horizontalSizeConfiguration,
3660 verticalSizeConfigurations, smallestSizeConfigurations);
3661 }
3662 }
3663
3664 /**
3665 * Dismisses split-screen multi-window mode.
3666 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3667 */
3668 @Override
3669 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003670 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3672 final long ident = Binder.clearCallingIdentity();
3673 try {
3674 synchronized (mGlobalLock) {
3675 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003676 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677 if (stack == null) {
3678 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3679 return;
3680 }
3681
3682 if (toTop) {
3683 // Caller wants the current split-screen primary stack to be the top stack after
3684 // it goes fullscreen, so move it to the front.
3685 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003686 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003687 // In this case the current split-screen primary stack shouldn't be the top
3688 // stack after it goes fullscreen, but it current has focus, so we move the
3689 // focus to the top-most split-screen secondary stack next to it.
3690 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3691 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3692 if (otherStack != null) {
3693 otherStack.moveToFront("dismissSplitScreenMode_other");
3694 }
3695 }
3696
Evan Rosky10475742018-09-05 19:02:48 -07003697 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003698 }
3699 } finally {
3700 Binder.restoreCallingIdentity(ident);
3701 }
3702 }
3703
3704 /**
3705 * Dismisses Pip
3706 * @param animate True if the dismissal should be animated.
3707 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3708 * default animation duration should be used.
3709 */
3710 @Override
3711 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003712 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003713 final long ident = Binder.clearCallingIdentity();
3714 try {
3715 synchronized (mGlobalLock) {
3716 final PinnedActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003717 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718 if (stack == null) {
3719 Slog.w(TAG, "dismissPip: pinned stack not found.");
3720 return;
3721 }
3722 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3723 throw new IllegalArgumentException("Stack: " + stack
3724 + " doesn't support animated resize.");
3725 }
3726 if (animate) {
3727 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3728 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3729 } else {
3730 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3731 }
3732 }
3733 } finally {
3734 Binder.restoreCallingIdentity(ident);
3735 }
3736 }
3737
3738 @Override
3739 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003740 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003741 synchronized (mGlobalLock) {
3742 mSuppressResizeConfigChanges = suppress;
3743 }
3744 }
3745
3746 /**
3747 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3748 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3749 * activity and clearing the task at the same time.
3750 */
3751 @Override
3752 // TODO: API should just be about changing windowing modes...
3753 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003754 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 "moveTasksToFullscreenStack()");
3756 synchronized (mGlobalLock) {
3757 final long origId = Binder.clearCallingIdentity();
3758 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003759 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003760 if (stack != null){
3761 if (!stack.isActivityTypeStandardOrUndefined()) {
3762 throw new IllegalArgumentException(
3763 "You can't move tasks from non-standard stacks.");
3764 }
3765 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3766 }
3767 } finally {
3768 Binder.restoreCallingIdentity(origId);
3769 }
3770 }
3771 }
3772
3773 /**
3774 * Moves the top activity in the input stackId to the pinned stack.
3775 *
3776 * @param stackId Id of stack to move the top activity to pinned stack.
3777 * @param bounds Bounds to use for pinned stack.
3778 *
3779 * @return True if the top activity of the input stack was successfully moved to the pinned
3780 * stack.
3781 */
3782 @Override
3783 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003784 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 "moveTopActivityToPinnedStack()");
3786 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003787 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003788 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3789 + "Device doesn't support picture-in-picture mode");
3790 }
3791
3792 long ident = Binder.clearCallingIdentity();
3793 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003794 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 } finally {
3796 Binder.restoreCallingIdentity(ident);
3797 }
3798 }
3799 }
3800
3801 @Override
3802 public boolean isInMultiWindowMode(IBinder token) {
3803 final long origId = Binder.clearCallingIdentity();
3804 try {
3805 synchronized (mGlobalLock) {
3806 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3807 if (r == null) {
3808 return false;
3809 }
3810 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3811 return r.inMultiWindowMode();
3812 }
3813 } finally {
3814 Binder.restoreCallingIdentity(origId);
3815 }
3816 }
3817
3818 @Override
3819 public boolean isInPictureInPictureMode(IBinder token) {
3820 final long origId = Binder.clearCallingIdentity();
3821 try {
3822 synchronized (mGlobalLock) {
3823 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3824 }
3825 } finally {
3826 Binder.restoreCallingIdentity(origId);
3827 }
3828 }
3829
3830 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003831 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3832 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 return false;
3834 }
3835
3836 // If we are animating to fullscreen then we have already dispatched the PIP mode
3837 // changed, so we should reflect that check here as well.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003838 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 final PinnedStackWindowController windowController = stack.getWindowContainerController();
Evan Rosky1ac84462018-11-13 11:25:30 -08003840 return !windowController.mContainer.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 }
3842
3843 @Override
3844 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3845 final long origId = Binder.clearCallingIdentity();
3846 try {
3847 synchronized (mGlobalLock) {
3848 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3849 "enterPictureInPictureMode", token, params);
3850
3851 // If the activity is already in picture in picture mode, then just return early
3852 if (isInPictureInPictureMode(r)) {
3853 return true;
3854 }
3855
3856 // Activity supports picture-in-picture, now check that we can enter PiP at this
3857 // point, if it is
3858 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3859 false /* beforeStopping */)) {
3860 return false;
3861 }
3862
3863 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003864 synchronized (mGlobalLock) {
3865 // Only update the saved args from the args that are set
3866 r.pictureInPictureArgs.copyOnlySet(params);
3867 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3868 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3869 // Adjust the source bounds by the insets for the transition down
3870 final Rect sourceBounds = new Rect(
3871 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003872 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003873 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003874 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003875 stack.setPictureInPictureAspectRatio(aspectRatio);
3876 stack.setPictureInPictureActions(actions);
3877 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3878 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3879 logPictureInPictureArgs(params);
3880 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003881 };
3882
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003883 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003884 // If the keyguard is showing or occluded, then try and dismiss it before
3885 // entering picture-in-picture (this will prompt the user to authenticate if the
3886 // device is currently locked).
3887 dismissKeyguard(token, new KeyguardDismissCallback() {
3888 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003889 public void onDismissSucceeded() {
3890 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 }
3892 }, null /* message */);
3893 } else {
3894 // Enter picture in picture immediately otherwise
3895 enterPipRunnable.run();
3896 }
3897 return true;
3898 }
3899 } finally {
3900 Binder.restoreCallingIdentity(origId);
3901 }
3902 }
3903
3904 @Override
3905 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3906 final long origId = Binder.clearCallingIdentity();
3907 try {
3908 synchronized (mGlobalLock) {
3909 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3910 "setPictureInPictureParams", token, params);
3911
3912 // Only update the saved args from the args that are set
3913 r.pictureInPictureArgs.copyOnlySet(params);
3914 if (r.inPinnedWindowingMode()) {
3915 // If the activity is already in picture-in-picture, update the pinned stack now
3916 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3917 // be used the next time the activity enters PiP
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003918 final PinnedActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 if (!stack.isAnimatingBoundsToFullscreen()) {
3920 stack.setPictureInPictureAspectRatio(
3921 r.pictureInPictureArgs.getAspectRatio());
3922 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3923 }
3924 }
3925 logPictureInPictureArgs(params);
3926 }
3927 } finally {
3928 Binder.restoreCallingIdentity(origId);
3929 }
3930 }
3931
3932 @Override
3933 public int getMaxNumPictureInPictureActions(IBinder token) {
3934 // Currently, this is a static constant, but later, we may change this to be dependent on
3935 // the context of the activity
3936 return 3;
3937 }
3938
3939 private void logPictureInPictureArgs(PictureInPictureParams params) {
3940 if (params.hasSetActions()) {
3941 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3942 params.getActions().size());
3943 }
3944 if (params.hasSetAspectRatio()) {
3945 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3946 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3947 MetricsLogger.action(lm);
3948 }
3949 }
3950
3951 /**
3952 * Checks the state of the system and the activity associated with the given {@param token} to
3953 * verify that picture-in-picture is supported for that activity.
3954 *
3955 * @return the activity record for the given {@param token} if all the checks pass.
3956 */
3957 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3958 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003959 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 throw new IllegalStateException(caller
3961 + ": Device doesn't support picture-in-picture mode.");
3962 }
3963
3964 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3965 if (r == null) {
3966 throw new IllegalStateException(caller
3967 + ": Can't find activity for token=" + token);
3968 }
3969
3970 if (!r.supportsPictureInPicture()) {
3971 throw new IllegalStateException(caller
3972 + ": Current activity does not support picture-in-picture.");
3973 }
3974
3975 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003976 && !mWindowManager.isValidPictureInPictureAspectRatio(
3977 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 final float minAspectRatio = mContext.getResources().getFloat(
3979 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3980 final float maxAspectRatio = mContext.getResources().getFloat(
3981 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3982 throw new IllegalArgumentException(String.format(caller
3983 + ": Aspect ratio is too extreme (must be between %f and %f).",
3984 minAspectRatio, maxAspectRatio));
3985 }
3986
3987 // Truncate the number of actions if necessary
3988 params.truncateActions(getMaxNumPictureInPictureActions(token));
3989
3990 return r;
3991 }
3992
3993 @Override
3994 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 synchronized (mGlobalLock) {
3997 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3998 if (r == null) {
3999 throw new IllegalArgumentException("Activity does not exist; token="
4000 + activityToken);
4001 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004002 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 }
4004 }
4005
4006 @Override
4007 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4008 Rect tempDockedTaskInsetBounds,
4009 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004010 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004011 long ident = Binder.clearCallingIdentity();
4012 try {
4013 synchronized (mGlobalLock) {
4014 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4015 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4016 PRESERVE_WINDOWS);
4017 }
4018 } finally {
4019 Binder.restoreCallingIdentity(ident);
4020 }
4021 }
4022
4023 @Override
4024 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004025 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004026 final long ident = Binder.clearCallingIdentity();
4027 try {
4028 synchronized (mGlobalLock) {
4029 mStackSupervisor.setSplitScreenResizing(resizing);
4030 }
4031 } finally {
4032 Binder.restoreCallingIdentity(ident);
4033 }
4034 }
4035
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004036 /**
4037 * Check that we have the features required for VR-related API calls, and throw an exception if
4038 * not.
4039 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004040 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 if (!mContext.getPackageManager().hasSystemFeature(
4042 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4043 throw new UnsupportedOperationException("VR mode not supported on this device!");
4044 }
4045 }
4046
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 @Override
4048 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004049 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050
4051 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4052
4053 ActivityRecord r;
4054 synchronized (mGlobalLock) {
4055 r = ActivityRecord.isInStackLocked(token);
4056 }
4057
4058 if (r == null) {
4059 throw new IllegalArgumentException();
4060 }
4061
4062 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004063 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064 VrManagerInternal.NO_ERROR) {
4065 return err;
4066 }
4067
4068 // Clear the binder calling uid since this path may call moveToTask().
4069 final long callingId = Binder.clearCallingIdentity();
4070 try {
4071 synchronized (mGlobalLock) {
4072 r.requestedVrComponent = (enabled) ? packageName : null;
4073
4074 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004075 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004076 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004077 }
4078 return 0;
4079 }
4080 } finally {
4081 Binder.restoreCallingIdentity(callingId);
4082 }
4083 }
4084
4085 @Override
4086 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4087 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4088 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004089 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4091 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4092 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004093 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 || activity.voiceSession != null) {
4095 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4096 return;
4097 }
4098 if (activity.pendingVoiceInteractionStart) {
4099 Slog.w(TAG, "Pending start of voice interaction already.");
4100 return;
4101 }
4102 activity.pendingVoiceInteractionStart = true;
4103 }
4104 LocalServices.getService(VoiceInteractionManagerInternal.class)
4105 .startLocalVoiceInteraction(callingActivity, options);
4106 }
4107
4108 @Override
4109 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4110 LocalServices.getService(VoiceInteractionManagerInternal.class)
4111 .stopLocalVoiceInteraction(callingActivity);
4112 }
4113
4114 @Override
4115 public boolean supportsLocalVoiceInteraction() {
4116 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4117 .supportsLocalVoiceInteraction();
4118 }
4119
4120 /** Notifies all listeners when the pinned stack animation starts. */
4121 @Override
4122 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004123 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 }
4125
4126 /** Notifies all listeners when the pinned stack animation ends. */
4127 @Override
4128 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004129 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 }
4131
4132 @Override
4133 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004134 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004135 final long ident = Binder.clearCallingIdentity();
4136 try {
4137 synchronized (mGlobalLock) {
4138 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4139 }
4140 } finally {
4141 Binder.restoreCallingIdentity(ident);
4142 }
4143 }
4144
4145 @Override
4146 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148
4149 synchronized (mGlobalLock) {
4150 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004151 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 // Call might come when display is not yet added or has already been removed.
4153 if (DEBUG_CONFIGURATION) {
4154 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4155 + displayId);
4156 }
4157 return false;
4158 }
4159
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004160 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004162 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 }
4164
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004165 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004166 final Message msg = PooledLambda.obtainMessage(
4167 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4168 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004169 }
4170
4171 final long origId = Binder.clearCallingIdentity();
4172 try {
4173 if (values != null) {
4174 Settings.System.clearConfiguration(values);
4175 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004176 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4178 return mTmpUpdateConfigurationResult.changes != 0;
4179 } finally {
4180 Binder.restoreCallingIdentity(origId);
4181 }
4182 }
4183 }
4184
4185 @Override
4186 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004187 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188
4189 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004190 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004191 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 }
4194
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004195 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004196 final Message msg = PooledLambda.obtainMessage(
4197 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4198 DEFAULT_DISPLAY);
4199 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 }
4201
4202 final long origId = Binder.clearCallingIdentity();
4203 try {
4204 if (values != null) {
4205 Settings.System.clearConfiguration(values);
4206 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004207 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004208 UserHandle.USER_NULL, false /* deferResume */,
4209 mTmpUpdateConfigurationResult);
4210 return mTmpUpdateConfigurationResult.changes != 0;
4211 } finally {
4212 Binder.restoreCallingIdentity(origId);
4213 }
4214 }
4215 }
4216
4217 @Override
4218 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4219 CharSequence message) {
4220 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004221 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4223 }
4224 final long callingId = Binder.clearCallingIdentity();
4225 try {
4226 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004227 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 }
4229 } finally {
4230 Binder.restoreCallingIdentity(callingId);
4231 }
4232 }
4233
4234 @Override
4235 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 "cancelTaskWindowTransition()");
4238 final long ident = Binder.clearCallingIdentity();
4239 try {
4240 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004241 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 MATCH_TASK_IN_STACKS_ONLY);
4243 if (task == null) {
4244 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4245 return;
4246 }
4247 task.cancelWindowTransition();
4248 }
4249 } finally {
4250 Binder.restoreCallingIdentity(ident);
4251 }
4252 }
4253
4254 @Override
4255 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 final long ident = Binder.clearCallingIdentity();
4258 try {
4259 final TaskRecord task;
4260 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004261 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4263 if (task == null) {
4264 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4265 return null;
4266 }
4267 }
4268 // Don't call this while holding the lock as this operation might hit the disk.
4269 return task.getSnapshot(reducedResolution);
4270 } finally {
4271 Binder.restoreCallingIdentity(ident);
4272 }
4273 }
4274
4275 @Override
4276 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4277 synchronized (mGlobalLock) {
4278 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4279 if (r == null) {
4280 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4281 + token);
4282 return;
4283 }
4284 final long origId = Binder.clearCallingIdentity();
4285 try {
4286 r.setDisablePreviewScreenshots(disable);
4287 } finally {
4288 Binder.restoreCallingIdentity(origId);
4289 }
4290 }
4291 }
4292
4293 /** Return the user id of the last resumed activity. */
4294 @Override
4295 public @UserIdInt
4296 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4299 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004300 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004301 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004303 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 }
4305 }
4306
4307 @Override
4308 public void updateLockTaskFeatures(int userId, int flags) {
4309 final int callingUid = Binder.getCallingUid();
4310 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 "updateLockTaskFeatures()");
4313 }
4314 synchronized (mGlobalLock) {
4315 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4316 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004317 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004318 }
4319 }
4320
4321 @Override
4322 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4323 synchronized (mGlobalLock) {
4324 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4325 if (r == null) {
4326 return;
4327 }
4328 final long origId = Binder.clearCallingIdentity();
4329 try {
4330 r.setShowWhenLocked(showWhenLocked);
4331 } finally {
4332 Binder.restoreCallingIdentity(origId);
4333 }
4334 }
4335 }
4336
4337 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004338 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4339 synchronized (mGlobalLock) {
4340 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4341 if (r == null) {
4342 return;
4343 }
4344 final long origId = Binder.clearCallingIdentity();
4345 try {
4346 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4347 } finally {
4348 Binder.restoreCallingIdentity(origId);
4349 }
4350 }
4351 }
4352
4353 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4355 synchronized (mGlobalLock) {
4356 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4357 if (r == null) {
4358 return;
4359 }
4360 final long origId = Binder.clearCallingIdentity();
4361 try {
4362 r.setTurnScreenOn(turnScreenOn);
4363 } finally {
4364 Binder.restoreCallingIdentity(origId);
4365 }
4366 }
4367 }
4368
4369 @Override
4370 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004371 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004372 "registerRemoteAnimations");
4373 definition.setCallingPid(Binder.getCallingPid());
4374 synchronized (mGlobalLock) {
4375 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4376 if (r == null) {
4377 return;
4378 }
4379 final long origId = Binder.clearCallingIdentity();
4380 try {
4381 r.registerRemoteAnimations(definition);
4382 } finally {
4383 Binder.restoreCallingIdentity(origId);
4384 }
4385 }
4386 }
4387
4388 @Override
4389 public void registerRemoteAnimationForNextActivityStart(String packageName,
4390 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 "registerRemoteAnimationForNextActivityStart");
4393 adapter.setCallingPid(Binder.getCallingPid());
4394 synchronized (mGlobalLock) {
4395 final long origId = Binder.clearCallingIdentity();
4396 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004397 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 packageName, adapter);
4399 } finally {
4400 Binder.restoreCallingIdentity(origId);
4401 }
4402 }
4403 }
4404
4405 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4406 @Override
4407 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4408 synchronized (mGlobalLock) {
4409 final long origId = Binder.clearCallingIdentity();
4410 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004411 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 } finally {
4413 Binder.restoreCallingIdentity(origId);
4414 }
4415 }
4416 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004417
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004418 @Override
4419 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004420 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004422 final int pid = Binder.getCallingPid();
4423 final WindowProcessController wpc = mPidMap.get(pid);
4424 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004425 }
4426 }
4427
4428 @Override
4429 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004431 != PERMISSION_GRANTED) {
4432 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4433 + Binder.getCallingPid()
4434 + ", uid=" + Binder.getCallingUid()
4435 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4436 Slog.w(TAG, msg);
4437 throw new SecurityException(msg);
4438 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004439 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004440 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004441 final int pid = Binder.getCallingPid();
4442 final WindowProcessController proc = mPidMap.get(pid);
4443 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004444 }
4445 }
4446
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 @Override
4448 public void stopAppSwitches() {
4449 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4450 synchronized (mGlobalLock) {
4451 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4452 mDidAppSwitch = false;
4453 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4454 }
4455 }
4456
4457 @Override
4458 public void resumeAppSwitches() {
4459 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4460 synchronized (mGlobalLock) {
4461 // Note that we don't execute any pending app switches... we will
4462 // let those wait until either the timeout, or the next start
4463 // activity request.
4464 mAppSwitchesAllowedTime = 0;
4465 }
4466 }
4467
4468 void onStartActivitySetDidAppSwitch() {
4469 if (mDidAppSwitch) {
4470 // This is the second allowed switch since we stopped switches, so now just generally
4471 // allow switches. Use case:
4472 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4473 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4474 // anyone to switch again).
4475 mAppSwitchesAllowedTime = 0;
4476 } else {
4477 mDidAppSwitch = true;
4478 }
4479 }
4480
4481 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004482 boolean shouldDisableNonVrUiLocked() {
4483 return mVrController.shouldDisableNonVrUiLocked();
4484 }
4485
Wale Ogunwale53783742018-09-16 10:21:51 -07004486 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004487 // VR apps are expected to run in a main display. If an app is turning on VR for
4488 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4489 // fullscreen stack before enabling VR Mode.
4490 // TODO: The goal of this code is to keep the VR app on the main display. When the
4491 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4492 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4493 // option would be a better choice here.
4494 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4495 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4496 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004497 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004498 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004499 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004500 }
4501 mH.post(() -> {
4502 if (!mVrController.onVrModeChanged(r)) {
4503 return;
4504 }
4505 synchronized (mGlobalLock) {
4506 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4507 mWindowManager.disableNonVrUi(disableNonVrUi);
4508 if (disableNonVrUi) {
4509 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4510 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004511 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004512 }
4513 }
4514 });
4515 }
4516
Wale Ogunwale53783742018-09-16 10:21:51 -07004517 @Override
4518 public int getPackageScreenCompatMode(String packageName) {
4519 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4520 synchronized (mGlobalLock) {
4521 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4522 }
4523 }
4524
4525 @Override
4526 public void setPackageScreenCompatMode(String packageName, int mode) {
4527 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4528 "setPackageScreenCompatMode");
4529 synchronized (mGlobalLock) {
4530 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4531 }
4532 }
4533
4534 @Override
4535 public boolean getPackageAskScreenCompat(String packageName) {
4536 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4537 synchronized (mGlobalLock) {
4538 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4539 }
4540 }
4541
4542 @Override
4543 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4544 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4545 "setPackageAskScreenCompat");
4546 synchronized (mGlobalLock) {
4547 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4548 }
4549 }
4550
Wale Ogunwale64258362018-10-16 15:13:37 -07004551 public static String relaunchReasonToString(int relaunchReason) {
4552 switch (relaunchReason) {
4553 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4554 return "window_resize";
4555 case RELAUNCH_REASON_FREE_RESIZE:
4556 return "free_resize";
4557 default:
4558 return null;
4559 }
4560 }
4561
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004562 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004563 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004564 }
4565
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004566 /** Pokes the task persister. */
4567 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4568 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4569 }
4570
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004571 boolean isKeyguardLocked() {
4572 return mKeyguardController.isKeyguardLocked();
4573 }
4574
Garfield Tan01548632018-11-27 10:15:48 -08004575 /**
4576 * Clears launch params for the given package.
4577 * @param packageNames the names of the packages of which the launch params are to be cleared
4578 */
4579 @Override
4580 public void clearLaunchParamsForPackages(List<String> packageNames) {
4581 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4582 "clearLaunchParamsForPackages");
4583 synchronized (mGlobalLock) {
4584 for (int i = 0; i < packageNames.size(); ++i) {
4585 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4586 }
4587 }
4588 }
4589
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004590 /**
4591 * Makes the display with the given id a single task instance display. I.e the display can only
4592 * contain one task.
4593 */
4594 @Override
4595 public void setDisplayToSingleTaskInstance(int displayId) {
4596 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4597 "setDisplayToSingleTaskInstance");
4598 final long origId = Binder.clearCallingIdentity();
4599 try {
4600 final ActivityDisplay display =
4601 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4602 if (display != null) {
4603 display.setDisplayToSingleTaskInstance();
4604 }
4605 } finally {
4606 Binder.restoreCallingIdentity(origId);
4607 }
4608 }
4609
Wale Ogunwale31913b52018-10-13 08:29:31 -07004610 void dumpLastANRLocked(PrintWriter pw) {
4611 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4612 if (mLastANRState == null) {
4613 pw.println(" <no ANR has occurred since boot>");
4614 } else {
4615 pw.println(mLastANRState);
4616 }
4617 }
4618
4619 void dumpLastANRTracesLocked(PrintWriter pw) {
4620 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4621
4622 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4623 if (ArrayUtils.isEmpty(files)) {
4624 pw.println(" <no ANR has occurred since boot>");
4625 return;
4626 }
4627 // Find the latest file.
4628 File latest = null;
4629 for (File f : files) {
4630 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4631 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004632 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004633 }
4634 pw.print("File: ");
4635 pw.print(latest.getName());
4636 pw.println();
4637 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4638 String line;
4639 while ((line = in.readLine()) != null) {
4640 pw.println(line);
4641 }
4642 } catch (IOException e) {
4643 pw.print("Unable to read: ");
4644 pw.print(e);
4645 pw.println();
4646 }
4647 }
4648
4649 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4650 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4651 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4652 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4653 }
4654
4655 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4656 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4657 pw.println(header);
4658
Wale Ogunwaled32da472018-11-16 07:19:28 -08004659 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004660 dumpPackage);
4661 boolean needSep = printedAnything;
4662
4663 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004664 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004665 " ResumedActivity: ");
4666 if (printed) {
4667 printedAnything = true;
4668 needSep = false;
4669 }
4670
4671 if (dumpPackage == null) {
4672 if (needSep) {
4673 pw.println();
4674 }
4675 printedAnything = true;
4676 mStackSupervisor.dump(pw, " ");
4677 }
4678
4679 if (!printedAnything) {
4680 pw.println(" (nothing)");
4681 }
4682 }
4683
4684 void dumpActivityContainersLocked(PrintWriter pw) {
4685 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004686 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004687 pw.println(" ");
4688 }
4689
4690 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4691 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4692 getActivityStartController().dump(pw, "", dumpPackage);
4693 }
4694
4695 /**
4696 * There are three things that cmd can be:
4697 * - a flattened component name that matches an existing activity
4698 * - the cmd arg isn't the flattened component name of an existing activity:
4699 * dump all activity whose component contains the cmd as a substring
4700 * - A hex number of the ActivityRecord object instance.
4701 *
4702 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4703 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4704 */
4705 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4706 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4707 ArrayList<ActivityRecord> activities;
4708
4709 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004710 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004711 dumpFocusedStackOnly);
4712 }
4713
4714 if (activities.size() <= 0) {
4715 return false;
4716 }
4717
4718 String[] newArgs = new String[args.length - opti];
4719 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4720
4721 TaskRecord lastTask = null;
4722 boolean needSep = false;
4723 for (int i = activities.size() - 1; i >= 0; i--) {
4724 ActivityRecord r = activities.get(i);
4725 if (needSep) {
4726 pw.println();
4727 }
4728 needSep = true;
4729 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004730 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004731 if (lastTask != task) {
4732 lastTask = task;
4733 pw.print("TASK "); pw.print(lastTask.affinity);
4734 pw.print(" id="); pw.print(lastTask.taskId);
4735 pw.print(" userId="); pw.println(lastTask.userId);
4736 if (dumpAll) {
4737 lastTask.dump(pw, " ");
4738 }
4739 }
4740 }
4741 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4742 }
4743 return true;
4744 }
4745
4746 /**
4747 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4748 * there is a thread associated with the activity.
4749 */
4750 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4751 final ActivityRecord r, String[] args, boolean dumpAll) {
4752 String innerPrefix = prefix + " ";
4753 synchronized (mGlobalLock) {
4754 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4755 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4756 pw.print(" pid=");
4757 if (r.hasProcess()) pw.println(r.app.getPid());
4758 else pw.println("(not running)");
4759 if (dumpAll) {
4760 r.dump(pw, innerPrefix);
4761 }
4762 }
4763 if (r.attachedToProcess()) {
4764 // flush anything that is already in the PrintWriter since the thread is going
4765 // to write to the file descriptor directly
4766 pw.flush();
4767 try {
4768 TransferPipe tp = new TransferPipe();
4769 try {
4770 r.app.getThread().dumpActivity(tp.getWriteFd(),
4771 r.appToken, innerPrefix, args);
4772 tp.go(fd);
4773 } finally {
4774 tp.kill();
4775 }
4776 } catch (IOException e) {
4777 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4778 } catch (RemoteException e) {
4779 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4780 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004781 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 }
4783
sanryhuang498e77e2018-12-06 14:57:01 +08004784 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4785 boolean testPssMode) {
4786 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4787 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4788 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004789 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004790 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4791 st.toString());
4792 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004793 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4794 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4795 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004796 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4797 testPssMode);
4798 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 }
4800
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004801 int getCurrentUserId() {
4802 return mAmInternal.getCurrentUserId();
4803 }
4804
4805 private void enforceNotIsolatedCaller(String caller) {
4806 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4807 throw new SecurityException("Isolated process not allowed to call " + caller);
4808 }
4809 }
4810
Wale Ogunwalef6733932018-06-27 05:14:34 -07004811 public Configuration getConfiguration() {
4812 Configuration ci;
4813 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004814 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004815 ci.userSetLocale = false;
4816 }
4817 return ci;
4818 }
4819
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004820 /**
4821 * Current global configuration information. Contains general settings for the entire system,
4822 * also corresponds to the merged configuration of the default display.
4823 */
4824 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004825 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004826 }
4827
4828 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4829 boolean initLocale) {
4830 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4831 }
4832
4833 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4834 boolean initLocale, boolean deferResume) {
4835 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4836 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4837 UserHandle.USER_NULL, deferResume);
4838 }
4839
Wale Ogunwale59507092018-10-29 09:00:30 -07004840 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004841 final long origId = Binder.clearCallingIdentity();
4842 try {
4843 synchronized (mGlobalLock) {
4844 updateConfigurationLocked(values, null, false, true, userId,
4845 false /* deferResume */);
4846 }
4847 } finally {
4848 Binder.restoreCallingIdentity(origId);
4849 }
4850 }
4851
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004852 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4853 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4854 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4855 deferResume, null /* result */);
4856 }
4857
4858 /**
4859 * Do either or both things: (1) change the current configuration, and (2)
4860 * make sure the given activity is running with the (now) current
4861 * configuration. Returns true if the activity has been left running, or
4862 * false if <var>starting</var> is being destroyed to match the new
4863 * configuration.
4864 *
4865 * @param userId is only used when persistent parameter is set to true to persist configuration
4866 * for that particular user
4867 */
4868 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4869 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4870 ActivityTaskManagerService.UpdateConfigurationResult result) {
4871 int changes = 0;
4872 boolean kept = true;
4873
4874 if (mWindowManager != null) {
4875 mWindowManager.deferSurfaceLayout();
4876 }
4877 try {
4878 if (values != null) {
4879 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4880 deferResume);
4881 }
4882
4883 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4884 } finally {
4885 if (mWindowManager != null) {
4886 mWindowManager.continueSurfaceLayout();
4887 }
4888 }
4889
4890 if (result != null) {
4891 result.changes = changes;
4892 result.activityRelaunched = !kept;
4893 }
4894 return kept;
4895 }
4896
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897 /** Update default (global) configuration and notify listeners about changes. */
4898 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4899 boolean persistent, int userId, boolean deferResume) {
4900 mTempConfig.setTo(getGlobalConfiguration());
4901 final int changes = mTempConfig.updateFrom(values);
4902 if (changes == 0) {
4903 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4904 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4905 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4906 // (even if there are no actual changes) to unfreeze the window.
4907 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4908 return 0;
4909 }
4910
4911 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4912 "Updating global configuration to: " + values);
4913
4914 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4915 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4916 values.colorMode,
4917 values.densityDpi,
4918 values.fontScale,
4919 values.hardKeyboardHidden,
4920 values.keyboard,
4921 values.keyboardHidden,
4922 values.mcc,
4923 values.mnc,
4924 values.navigation,
4925 values.navigationHidden,
4926 values.orientation,
4927 values.screenHeightDp,
4928 values.screenLayout,
4929 values.screenWidthDp,
4930 values.smallestScreenWidthDp,
4931 values.touchscreen,
4932 values.uiMode);
4933
4934
4935 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4936 final LocaleList locales = values.getLocales();
4937 int bestLocaleIndex = 0;
4938 if (locales.size() > 1) {
4939 if (mSupportedSystemLocales == null) {
4940 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4941 }
4942 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4943 }
4944 SystemProperties.set("persist.sys.locale",
4945 locales.get(bestLocaleIndex).toLanguageTag());
4946 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004947
4948 final Message m = PooledLambda.obtainMessage(
4949 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4950 locales.get(bestLocaleIndex));
4951 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004952 }
4953
Yunfan Chen75157d72018-07-27 14:47:21 +09004954 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004955
4956 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004957 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004958
4959 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4960 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004961 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004962
4963 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004964 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004965
4966 AttributeCache ac = AttributeCache.instance();
4967 if (ac != null) {
4968 ac.updateConfiguration(mTempConfig);
4969 }
4970
4971 // Make sure all resources in our process are updated right now, so that anyone who is going
4972 // to retrieve resource values after we return will be sure to get the new ones. This is
4973 // especially important during boot, where the first config change needs to guarantee all
4974 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004975 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004976
4977 // We need another copy of global config because we're scheduling some calls instead of
4978 // running them in place. We need to be sure that object we send will be handled unchanged.
4979 final Configuration configCopy = new Configuration(mTempConfig);
4980 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004981 final Message msg = PooledLambda.obtainMessage(
4982 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4983 this, userId, configCopy);
4984 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004985 }
4986
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004987 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004988 final int pid = mPidMap.keyAt(i);
4989 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004990 if (DEBUG_CONFIGURATION) {
4991 Slog.v(TAG_CONFIGURATION, "Update process config of "
4992 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004993 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004994 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004995 }
4996
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004997 final Message msg = PooledLambda.obtainMessage(
4998 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4999 mAmInternal, changes, initLocale);
5000 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005001
5002 // Override configuration of the default display duplicates global config, so we need to
5003 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005004 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005005 DEFAULT_DISPLAY);
5006
5007 return changes;
5008 }
5009
5010 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5011 boolean deferResume, int displayId) {
5012 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5013 displayId, null /* result */);
5014 }
5015
5016 /**
5017 * Updates override configuration specific for the selected display. If no config is provided,
5018 * new one will be computed in WM based on current display info.
5019 */
5020 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5021 ActivityRecord starting, boolean deferResume, int displayId,
5022 ActivityTaskManagerService.UpdateConfigurationResult result) {
5023 int changes = 0;
5024 boolean kept = true;
5025
5026 if (mWindowManager != null) {
5027 mWindowManager.deferSurfaceLayout();
5028 }
5029 try {
5030 if (values != null) {
5031 if (displayId == DEFAULT_DISPLAY) {
5032 // Override configuration of the default display duplicates global config, so
5033 // we're calling global config update instead for default display. It will also
5034 // apply the correct override config.
5035 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5036 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5037 } else {
5038 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5039 }
5040 }
5041
5042 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5043 } finally {
5044 if (mWindowManager != null) {
5045 mWindowManager.continueSurfaceLayout();
5046 }
5047 }
5048
5049 if (result != null) {
5050 result.changes = changes;
5051 result.activityRelaunched = !kept;
5052 }
5053 return kept;
5054 }
5055
5056 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5057 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005058 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059 final int changes = mTempConfig.updateFrom(values);
5060 if (changes != 0) {
5061 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5062 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005063 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005064
5065 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5066 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005067 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068
Wale Ogunwale5c918702018-10-18 11:06:33 -07005069 // Post message to start process to avoid possible deadlock of calling into AMS with
5070 // the ATMS lock held.
5071 final Message msg = PooledLambda.obtainMessage(
5072 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5073 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5074 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005075 }
5076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005077 return changes;
5078 }
5079
Wale Ogunwalef6733932018-06-27 05:14:34 -07005080 private void updateEventDispatchingLocked(boolean booted) {
5081 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5082 }
5083
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005084 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5085 final ContentResolver resolver = mContext.getContentResolver();
5086 Settings.System.putConfigurationForUser(resolver, config, userId);
5087 }
5088
5089 private void sendLocaleToMountDaemonMsg(Locale l) {
5090 try {
5091 IBinder service = ServiceManager.getService("mount");
5092 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5093 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5094 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5095 } catch (RemoteException e) {
5096 Log.e(TAG, "Error storing locale for decryption UI", e);
5097 }
5098 }
5099
Alison Cichowlas3e340502018-08-07 17:15:01 -04005100 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5101 mStartActivitySources.remove(permissionToken);
5102 mExpiredStartAsCallerTokens.add(permissionToken);
5103 }
5104
5105 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5106 mExpiredStartAsCallerTokens.remove(permissionToken);
5107 }
5108
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005109 boolean isActivityStartsLoggingEnabled() {
5110 return mAmInternal.isActivityStartsLoggingEnabled();
5111 }
5112
Michal Karpinski8596ded2018-11-14 14:43:48 +00005113 boolean isBackgroundActivityStartsEnabled() {
5114 return mAmInternal.isBackgroundActivityStartsEnabled();
5115 }
5116
Wale Ogunwalef6733932018-06-27 05:14:34 -07005117 void enableScreenAfterBoot(boolean booted) {
5118 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5119 SystemClock.uptimeMillis());
5120 mWindowManager.enableScreenAfterBoot();
5121
5122 synchronized (mGlobalLock) {
5123 updateEventDispatchingLocked(booted);
5124 }
5125 }
5126
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005127 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5128 if (r == null || !r.hasProcess()) {
5129 return KEY_DISPATCHING_TIMEOUT_MS;
5130 }
5131 return getInputDispatchingTimeoutLocked(r.app);
5132 }
5133
5134 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005135 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005136 }
5137
Wale Ogunwalef6733932018-06-27 05:14:34 -07005138 /**
5139 * Decide based on the configuration whether we should show the ANR,
5140 * crash, etc dialogs. The idea is that if there is no affordance to
5141 * press the on-screen buttons, or the user experience would be more
5142 * greatly impacted than the crash itself, we shouldn't show the dialog.
5143 *
5144 * A thought: SystemUI might also want to get told about this, the Power
5145 * dialog / global actions also might want different behaviors.
5146 */
5147 private void updateShouldShowDialogsLocked(Configuration config) {
5148 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5149 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5150 && config.navigation == Configuration.NAVIGATION_NONAV);
5151 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5152 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5153 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5154 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5155 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5156 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5157 HIDE_ERROR_DIALOGS, 0) != 0;
5158 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5159 }
5160
5161 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5162 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5163 FONT_SCALE, 1.0f, userId);
5164
5165 synchronized (this) {
5166 if (getGlobalConfiguration().fontScale == scaleFactor) {
5167 return;
5168 }
5169
5170 final Configuration configuration
5171 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5172 configuration.fontScale = scaleFactor;
5173 updatePersistentConfiguration(configuration, userId);
5174 }
5175 }
5176
5177 // Actually is sleeping or shutting down or whatever else in the future
5178 // is an inactive state.
5179 boolean isSleepingOrShuttingDownLocked() {
5180 return isSleepingLocked() || mShuttingDown;
5181 }
5182
5183 boolean isSleepingLocked() {
5184 return mSleeping;
5185 }
5186
Riddle Hsu16567132018-08-16 21:37:47 +08005187 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005188 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005189 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005190 if (task.isActivityTypeStandard()) {
5191 if (mCurAppTimeTracker != r.appTimeTracker) {
5192 // We are switching app tracking. Complete the current one.
5193 if (mCurAppTimeTracker != null) {
5194 mCurAppTimeTracker.stop();
5195 mH.obtainMessage(
5196 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005197 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005198 mCurAppTimeTracker = null;
5199 }
5200 if (r.appTimeTracker != null) {
5201 mCurAppTimeTracker = r.appTimeTracker;
5202 startTimeTrackingFocusedActivityLocked();
5203 }
5204 } else {
5205 startTimeTrackingFocusedActivityLocked();
5206 }
5207 } else {
5208 r.appTimeTracker = null;
5209 }
5210 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5211 // TODO: Probably not, because we don't want to resume voice on switching
5212 // back to this activity
5213 if (task.voiceInteractor != null) {
5214 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5215 } else {
5216 finishRunningVoiceLocked();
5217
5218 if (mLastResumedActivity != null) {
5219 final IVoiceInteractionSession session;
5220
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005221 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005222 if (lastResumedActivityTask != null
5223 && lastResumedActivityTask.voiceSession != null) {
5224 session = lastResumedActivityTask.voiceSession;
5225 } else {
5226 session = mLastResumedActivity.voiceSession;
5227 }
5228
5229 if (session != null) {
5230 // We had been in a voice interaction session, but now focused has
5231 // move to something different. Just finish the session, we can't
5232 // return to it and retain the proper state and synchronization with
5233 // the voice interaction service.
5234 finishVoiceTask(session);
5235 }
5236 }
5237 }
5238
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005239 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5240 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005241 }
5242 updateResumedAppTrace(r);
5243 mLastResumedActivity = r;
5244
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005245 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005246
5247 applyUpdateLockStateLocked(r);
5248 applyUpdateVrModeLocked(r);
5249
5250 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005251 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005252 r == null ? "NULL" : r.shortComponentName,
5253 reason);
5254 }
5255
5256 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5257 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005258 final ActivityTaskManagerInternal.SleepToken token =
5259 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005260 updateSleepIfNeededLocked();
5261 return token;
5262 }
5263 }
5264
5265 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005266 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005267 final boolean wasSleeping = mSleeping;
5268 boolean updateOomAdj = false;
5269
5270 if (!shouldSleep) {
5271 // If wasSleeping is true, we need to wake up activity manager state from when
5272 // we started sleeping. In either case, we need to apply the sleep tokens, which
5273 // will wake up stacks or put them to sleep as appropriate.
5274 if (wasSleeping) {
5275 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005276 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5277 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 startTimeTrackingFocusedActivityLocked();
5279 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5280 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5281 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005282 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005283 if (wasSleeping) {
5284 updateOomAdj = true;
5285 }
5286 } else if (!mSleeping && shouldSleep) {
5287 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005288 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5289 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005290 if (mCurAppTimeTracker != null) {
5291 mCurAppTimeTracker.stop();
5292 }
5293 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5294 mStackSupervisor.goingToSleepLocked();
5295 updateResumedAppTrace(null /* resumed */);
5296 updateOomAdj = true;
5297 }
5298 if (updateOomAdj) {
5299 mH.post(mAmInternal::updateOomAdj);
5300 }
5301 }
5302
5303 void updateOomAdj() {
5304 mH.post(mAmInternal::updateOomAdj);
5305 }
5306
Wale Ogunwale53783742018-09-16 10:21:51 -07005307 void updateCpuStats() {
5308 mH.post(mAmInternal::updateCpuStats);
5309 }
5310
Hui Yu03d12402018-12-06 18:00:37 -08005311 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5312 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005313 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5314 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005315 mH.sendMessage(m);
5316 }
5317
Hui Yu03d12402018-12-06 18:00:37 -08005318 void updateActivityUsageStats(ActivityRecord activity, int event) {
5319 final Message m = PooledLambda.obtainMessage(
5320 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5321 activity.mActivityComponent, activity.mUserId, event, activity.appToken);
5322 mH.sendMessage(m);
5323 }
5324
Wale Ogunwale53783742018-09-16 10:21:51 -07005325 void setBooting(boolean booting) {
5326 mAmInternal.setBooting(booting);
5327 }
5328
5329 boolean isBooting() {
5330 return mAmInternal.isBooting();
5331 }
5332
5333 void setBooted(boolean booted) {
5334 mAmInternal.setBooted(booted);
5335 }
5336
5337 boolean isBooted() {
5338 return mAmInternal.isBooted();
5339 }
5340
5341 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5342 mH.post(() -> {
5343 if (finishBooting) {
5344 mAmInternal.finishBooting();
5345 }
5346 if (enableScreen) {
5347 mInternal.enableScreenAfterBoot(isBooted());
5348 }
5349 });
5350 }
5351
5352 void setHeavyWeightProcess(ActivityRecord root) {
5353 mHeavyWeightProcess = root.app;
5354 final Message m = PooledLambda.obtainMessage(
5355 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005356 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005357 mH.sendMessage(m);
5358 }
5359
5360 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5361 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5362 return;
5363 }
5364
5365 mHeavyWeightProcess = null;
5366 final Message m = PooledLambda.obtainMessage(
5367 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5368 proc.mUserId);
5369 mH.sendMessage(m);
5370 }
5371
5372 private void cancelHeavyWeightProcessNotification(int userId) {
5373 final INotificationManager inm = NotificationManager.getService();
5374 if (inm == null) {
5375 return;
5376 }
5377 try {
5378 inm.cancelNotificationWithTag("android", null,
5379 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5380 } catch (RuntimeException e) {
5381 Slog.w(TAG, "Error canceling notification for service", e);
5382 } catch (RemoteException e) {
5383 }
5384
5385 }
5386
5387 private void postHeavyWeightProcessNotification(
5388 WindowProcessController proc, Intent intent, int userId) {
5389 if (proc == null) {
5390 return;
5391 }
5392
5393 final INotificationManager inm = NotificationManager.getService();
5394 if (inm == null) {
5395 return;
5396 }
5397
5398 try {
5399 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5400 String text = mContext.getString(R.string.heavy_weight_notification,
5401 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5402 Notification notification =
5403 new Notification.Builder(context,
5404 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5405 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5406 .setWhen(0)
5407 .setOngoing(true)
5408 .setTicker(text)
5409 .setColor(mContext.getColor(
5410 com.android.internal.R.color.system_notification_accent_color))
5411 .setContentTitle(text)
5412 .setContentText(
5413 mContext.getText(R.string.heavy_weight_notification_detail))
5414 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5415 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5416 new UserHandle(userId)))
5417 .build();
5418 try {
5419 inm.enqueueNotificationWithTag("android", "android", null,
5420 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5421 } catch (RuntimeException e) {
5422 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5423 } catch (RemoteException e) {
5424 }
5425 } catch (PackageManager.NameNotFoundException e) {
5426 Slog.w(TAG, "Unable to create context for heavy notification", e);
5427 }
5428
5429 }
5430
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005431 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5432 IBinder token, String resultWho, int requestCode, Intent[] intents,
5433 String[] resolvedTypes, int flags, Bundle bOptions) {
5434
5435 ActivityRecord activity = null;
5436 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5437 activity = ActivityRecord.isInStackLocked(token);
5438 if (activity == null) {
5439 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5440 return null;
5441 }
5442 if (activity.finishing) {
5443 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5444 return null;
5445 }
5446 }
5447
5448 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5449 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5450 bOptions);
5451 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5452 if (noCreate) {
5453 return rec;
5454 }
5455 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5456 if (activity.pendingResults == null) {
5457 activity.pendingResults = new HashSet<>();
5458 }
5459 activity.pendingResults.add(rec.ref);
5460 }
5461 return rec;
5462 }
5463
Andrii Kulian52d255c2018-07-13 11:32:19 -07005464 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005466 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005467 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5468 mCurAppTimeTracker.start(resumedActivity.packageName);
5469 }
5470 }
5471
5472 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5473 if (mTracedResumedActivity != null) {
5474 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5475 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5476 }
5477 if (resumed != null) {
5478 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5479 constructResumedTraceName(resumed.packageName), 0);
5480 }
5481 mTracedResumedActivity = resumed;
5482 }
5483
5484 private String constructResumedTraceName(String packageName) {
5485 return "focused app: " + packageName;
5486 }
5487
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005488 /** Applies latest configuration and/or visibility updates if needed. */
5489 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5490 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005491 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005492 // mainStack is null during startup.
5493 if (mainStack != null) {
5494 if (changes != 0 && starting == null) {
5495 // If the configuration changed, and the caller is not already
5496 // in the process of starting an activity, then find the top
5497 // activity to check if its configuration needs to change.
5498 starting = mainStack.topRunningActivityLocked();
5499 }
5500
5501 if (starting != null) {
5502 kept = starting.ensureActivityConfiguration(changes,
5503 false /* preserveWindow */);
5504 // And we need to make sure at this point that all other activities
5505 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005506 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005507 !PRESERVE_WINDOWS);
5508 }
5509 }
5510
5511 return kept;
5512 }
5513
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005514 void scheduleAppGcsLocked() {
5515 mH.post(() -> mAmInternal.scheduleAppGcs());
5516 }
5517
Wale Ogunwale53783742018-09-16 10:21:51 -07005518 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5519 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5520 }
5521
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005522 /**
5523 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5524 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5525 * on demand.
5526 */
5527 IPackageManager getPackageManager() {
5528 return AppGlobals.getPackageManager();
5529 }
5530
5531 PackageManagerInternal getPackageManagerInternalLocked() {
5532 if (mPmInternal == null) {
5533 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5534 }
5535 return mPmInternal;
5536 }
5537
Wale Ogunwale008163e2018-07-23 23:11:08 -07005538 AppWarnings getAppWarningsLocked() {
5539 return mAppWarnings;
5540 }
5541
Wale Ogunwale214f3482018-10-04 11:00:47 -07005542 Intent getHomeIntent() {
5543 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5544 intent.setComponent(mTopComponent);
5545 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5546 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5547 intent.addCategory(Intent.CATEGORY_HOME);
5548 }
5549 return intent;
5550 }
5551
Chilun2ef71f72018-11-16 17:57:15 +08005552 /**
5553 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5554 * activities.
5555 *
5556 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5557 * component defined in config_secondaryHomeComponent.
5558 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5559 */
5560 Intent getSecondaryHomeIntent(String preferredPackage) {
5561 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5562 if (preferredPackage == null) {
5563 // Using the component stored in config if no package name.
5564 final String secondaryHomeComponent = mContext.getResources().getString(
5565 com.android.internal.R.string.config_secondaryHomeComponent);
5566 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5567 } else {
5568 intent.setPackage(preferredPackage);
5569 }
5570 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5571 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5572 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5573 }
5574 return intent;
5575 }
5576
Wale Ogunwale214f3482018-10-04 11:00:47 -07005577 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5578 if (info == null) return null;
5579 ApplicationInfo newInfo = new ApplicationInfo(info);
5580 newInfo.initForUser(userId);
5581 return newInfo;
5582 }
5583
Wale Ogunwale9c103022018-10-18 07:44:54 -07005584 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005585 if (uid == SYSTEM_UID) {
5586 // The system gets to run in any process. If there are multiple processes with the same
5587 // uid, just pick the first (this should never happen).
5588 final SparseArray<WindowProcessController> procs =
5589 mProcessNames.getMap().get(processName);
5590 if (procs == null) return null;
5591 final int procCount = procs.size();
5592 for (int i = 0; i < procCount; i++) {
5593 final int procUid = procs.keyAt(i);
5594 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5595 // Don't use an app process or different user process for system component.
5596 continue;
5597 }
5598 return procs.valueAt(i);
5599 }
5600 }
5601
5602 return mProcessNames.get(processName, uid);
5603 }
5604
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005605 WindowProcessController getProcessController(IApplicationThread thread) {
5606 if (thread == null) {
5607 return null;
5608 }
5609
5610 final IBinder threadBinder = thread.asBinder();
5611 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5612 for (int i = pmap.size()-1; i >= 0; i--) {
5613 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5614 for (int j = procs.size() - 1; j >= 0; j--) {
5615 final WindowProcessController proc = procs.valueAt(j);
5616 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5617 return proc;
5618 }
5619 }
5620 }
5621
5622 return null;
5623 }
5624
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005625 int getUidStateLocked(int uid) {
5626 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5627 }
5628
Wale Ogunwale9de19442018-10-18 19:05:03 -07005629 /**
5630 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5631 * the whitelist
5632 */
5633 String getPendingTempWhitelistTagForUidLocked(int uid) {
5634 return mPendingTempWhitelist.get(uid);
5635 }
5636
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005637 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5638 if (true || Build.IS_USER) {
5639 return;
5640 }
5641
5642 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5643 StrictMode.allowThreadDiskWrites();
5644 try {
5645 File tracesDir = new File("/data/anr");
5646 File tracesFile = null;
5647 try {
5648 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5649
5650 StringBuilder sb = new StringBuilder();
5651 Time tobj = new Time();
5652 tobj.set(System.currentTimeMillis());
5653 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5654 sb.append(": ");
5655 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5656 sb.append(" since ");
5657 sb.append(msg);
5658 FileOutputStream fos = new FileOutputStream(tracesFile);
5659 fos.write(sb.toString().getBytes());
5660 if (app == null) {
5661 fos.write("\n*** No application process!".getBytes());
5662 }
5663 fos.close();
5664 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5665 } catch (IOException e) {
5666 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5667 return;
5668 }
5669
5670 if (app != null && app.getPid() > 0) {
5671 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5672 firstPids.add(app.getPid());
5673 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5674 }
5675
5676 File lastTracesFile = null;
5677 File curTracesFile = null;
5678 for (int i=9; i>=0; i--) {
5679 String name = String.format(Locale.US, "slow%02d.txt", i);
5680 curTracesFile = new File(tracesDir, name);
5681 if (curTracesFile.exists()) {
5682 if (lastTracesFile != null) {
5683 curTracesFile.renameTo(lastTracesFile);
5684 } else {
5685 curTracesFile.delete();
5686 }
5687 }
5688 lastTracesFile = curTracesFile;
5689 }
5690 tracesFile.renameTo(curTracesFile);
5691 } finally {
5692 StrictMode.setThreadPolicy(oldPolicy);
5693 }
5694 }
5695
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005696 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005697 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005698
5699
Wale Ogunwale98875612018-10-12 07:53:02 -07005700 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5701 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005702
Riddle Hsud93a6c42018-11-29 21:50:06 +08005703 H(Looper looper) {
5704 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005705 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005706
5707 @Override
5708 public void handleMessage(Message msg) {
5709 switch (msg.what) {
5710 case REPORT_TIME_TRACKER_MSG: {
5711 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5712 tracker.deliverResult(mContext);
5713 } break;
5714 }
5715 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005716 }
5717
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005718 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005719 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005720
5721 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005722 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005723 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005724
5725 @Override
5726 public void handleMessage(Message msg) {
5727 switch (msg.what) {
5728 case DISMISS_DIALOG_UI_MSG: {
5729 final Dialog d = (Dialog) msg.obj;
5730 d.dismiss();
5731 break;
5732 }
5733 }
5734 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005735 }
5736
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005737 final class LocalService extends ActivityTaskManagerInternal {
5738 @Override
5739 public SleepToken acquireSleepToken(String tag, int displayId) {
5740 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005741 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005742 }
5743
5744 @Override
5745 public ComponentName getHomeActivityForUser(int userId) {
5746 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005747 final ActivityRecord homeActivity =
5748 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005749 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005750 }
5751 }
5752
5753 @Override
5754 public void onLocalVoiceInteractionStarted(IBinder activity,
5755 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5756 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005757 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005758 }
5759 }
5760
5761 @Override
5762 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5763 synchronized (mGlobalLock) {
5764 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5765 reasons, timestamp);
5766 }
5767 }
5768
5769 @Override
5770 public void notifyAppTransitionFinished() {
5771 synchronized (mGlobalLock) {
5772 mStackSupervisor.notifyAppTransitionDone();
5773 }
5774 }
5775
5776 @Override
5777 public void notifyAppTransitionCancelled() {
5778 synchronized (mGlobalLock) {
5779 mStackSupervisor.notifyAppTransitionDone();
5780 }
5781 }
5782
5783 @Override
5784 public List<IBinder> getTopVisibleActivities() {
5785 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005786 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005787 }
5788 }
5789
5790 @Override
5791 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5792 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005793 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005794 }
5795 }
5796
5797 @Override
5798 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5799 Bundle bOptions) {
5800 Preconditions.checkNotNull(intents, "intents");
5801 final String[] resolvedTypes = new String[intents.length];
5802
5803 // UID of the package on user userId.
5804 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5805 // packageUid may not be initialized.
5806 int packageUid = 0;
5807 final long ident = Binder.clearCallingIdentity();
5808
5809 try {
5810 for (int i = 0; i < intents.length; i++) {
5811 resolvedTypes[i] =
5812 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5813 }
5814
5815 packageUid = AppGlobals.getPackageManager().getPackageUid(
5816 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5817 } catch (RemoteException e) {
5818 // Shouldn't happen.
5819 } finally {
5820 Binder.restoreCallingIdentity(ident);
5821 }
5822
5823 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005824 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005825 packageUid, packageName,
5826 intents, resolvedTypes, null /* resultTo */,
5827 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005828 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5829 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005830 }
5831 }
5832
5833 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005834 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5835 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005836 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
5837 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005838 synchronized (mGlobalLock) {
5839 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5840 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005841 originatingPendingIntent, allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005842 }
5843 }
5844
5845 @Override
5846 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5847 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5848 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5849 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005850 PendingIntentRecord originatingPendingIntent,
5851 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005852 synchronized (mGlobalLock) {
5853 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5854 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5855 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005856 validateIncomingUser, originatingPendingIntent,
5857 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005858 }
5859 }
5860
5861 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005862 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5863 Intent intent, Bundle options, int userId) {
5864 return ActivityTaskManagerService.this.startActivityAsUser(
5865 caller, callerPacakge, intent,
5866 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5867 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5868 false /*validateIncomingUser*/);
5869 }
5870
5871 @Override
lumark588a3e82018-07-20 18:53:54 +08005872 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005873 synchronized (mGlobalLock) {
5874
5875 // We might change the visibilities here, so prepare an empty app transition which
5876 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005877 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005878 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005879 if (activityDisplay == null) {
5880 return;
5881 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005882 final DisplayContent dc = activityDisplay.mDisplayContent;
5883 final boolean wasTransitionSet =
5884 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005885 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005886 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005887 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005888 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005889
5890 // If there was a transition set already we don't want to interfere with it as we
5891 // might be starting it too early.
5892 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005893 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005894 }
5895 }
5896 if (callback != null) {
5897 callback.run();
5898 }
5899 }
5900
5901 @Override
5902 public void notifyKeyguardTrustedChanged() {
5903 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005904 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005905 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005906 }
5907 }
5908 }
5909
5910 /**
5911 * Called after virtual display Id is updated by
5912 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5913 * {@param vrVr2dDisplayId}.
5914 */
5915 @Override
5916 public void setVr2dDisplayId(int vr2dDisplayId) {
5917 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5918 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005919 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005920 }
5921 }
5922
5923 @Override
5924 public void setFocusedActivity(IBinder token) {
5925 synchronized (mGlobalLock) {
5926 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5927 if (r == null) {
5928 throw new IllegalArgumentException(
5929 "setFocusedActivity: No activity record matching token=" + token);
5930 }
Louis Chang19443452018-10-09 12:10:21 +08005931 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005932 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005933 }
5934 }
5935 }
5936
5937 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005938 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005939 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005940 }
5941
5942 @Override
5943 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005944 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005945 }
5946
5947 @Override
5948 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005949 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005950 }
5951
5952 @Override
5953 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5954 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5955 }
5956
5957 @Override
5958 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005959 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005960 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005961
5962 @Override
5963 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5964 synchronized (mGlobalLock) {
5965 mActiveVoiceInteractionServiceComponent = component;
5966 }
5967 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005968
5969 @Override
5970 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5971 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5972 return;
5973 }
5974 synchronized (mGlobalLock) {
5975 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5976 if (types == null) {
5977 if (uid < 0) {
5978 return;
5979 }
5980 types = new ArrayMap<>();
5981 mAllowAppSwitchUids.put(userId, types);
5982 }
5983 if (uid < 0) {
5984 types.remove(type);
5985 } else {
5986 types.put(type, uid);
5987 }
5988 }
5989 }
5990
5991 @Override
5992 public void onUserStopped(int userId) {
5993 synchronized (mGlobalLock) {
5994 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5995 mAllowAppSwitchUids.remove(userId);
5996 }
5997 }
5998
5999 @Override
6000 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6001 synchronized (mGlobalLock) {
6002 return ActivityTaskManagerService.this.isGetTasksAllowed(
6003 caller, callingPid, callingUid);
6004 }
6005 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006006
6007 @Override
6008 public void onProcessAdded(WindowProcessController proc) {
6009 synchronized (mGlobalLock) {
6010 mProcessNames.put(proc.mName, proc.mUid, proc);
6011 }
6012 }
6013
6014 @Override
6015 public void onProcessRemoved(String name, int uid) {
6016 synchronized (mGlobalLock) {
6017 mProcessNames.remove(name, uid);
6018 }
6019 }
6020
6021 @Override
6022 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6023 synchronized (mGlobalLock) {
6024 if (proc == mHomeProcess) {
6025 mHomeProcess = null;
6026 }
6027 if (proc == mPreviousProcess) {
6028 mPreviousProcess = null;
6029 }
6030 }
6031 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006032
6033 @Override
6034 public int getTopProcessState() {
6035 synchronized (mGlobalLock) {
6036 return mTopProcessState;
6037 }
6038 }
6039
6040 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006041 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6042 synchronized (mGlobalLock) {
6043 return proc == mHeavyWeightProcess;
6044 }
6045 }
6046
6047 @Override
6048 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6049 synchronized (mGlobalLock) {
6050 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6051 }
6052 }
6053
6054 @Override
6055 public void finishHeavyWeightApp() {
6056 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006057 if (mHeavyWeightProcess != null) {
6058 mHeavyWeightProcess.finishActivities();
6059 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006060 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6061 mHeavyWeightProcess);
6062 }
6063 }
6064
6065 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006066 public boolean isSleeping() {
6067 synchronized (mGlobalLock) {
6068 return isSleepingLocked();
6069 }
6070 }
6071
6072 @Override
6073 public boolean isShuttingDown() {
6074 synchronized (mGlobalLock) {
6075 return mShuttingDown;
6076 }
6077 }
6078
6079 @Override
6080 public boolean shuttingDown(boolean booted, int timeout) {
6081 synchronized (mGlobalLock) {
6082 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006083 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006084 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006085 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006086 return mStackSupervisor.shutdownLocked(timeout);
6087 }
6088 }
6089
6090 @Override
6091 public void enableScreenAfterBoot(boolean booted) {
6092 synchronized (mGlobalLock) {
6093 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6094 SystemClock.uptimeMillis());
6095 mWindowManager.enableScreenAfterBoot();
6096 updateEventDispatchingLocked(booted);
6097 }
6098 }
6099
6100 @Override
6101 public boolean showStrictModeViolationDialog() {
6102 synchronized (mGlobalLock) {
6103 return mShowDialogs && !mSleeping && !mShuttingDown;
6104 }
6105 }
6106
6107 @Override
6108 public void showSystemReadyErrorDialogsIfNeeded() {
6109 synchronized (mGlobalLock) {
6110 try {
6111 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6112 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6113 + " data partition or your device will be unstable.");
6114 mUiHandler.post(() -> {
6115 if (mShowDialogs) {
6116 AlertDialog d = new BaseErrorDialog(mUiContext);
6117 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6118 d.setCancelable(false);
6119 d.setTitle(mUiContext.getText(R.string.android_system_label));
6120 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6121 d.setButton(DialogInterface.BUTTON_POSITIVE,
6122 mUiContext.getText(R.string.ok),
6123 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6124 d.show();
6125 }
6126 });
6127 }
6128 } catch (RemoteException e) {
6129 }
6130
6131 if (!Build.isBuildConsistent()) {
6132 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6133 mUiHandler.post(() -> {
6134 if (mShowDialogs) {
6135 AlertDialog d = new BaseErrorDialog(mUiContext);
6136 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6137 d.setCancelable(false);
6138 d.setTitle(mUiContext.getText(R.string.android_system_label));
6139 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6140 d.setButton(DialogInterface.BUTTON_POSITIVE,
6141 mUiContext.getText(R.string.ok),
6142 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6143 d.show();
6144 }
6145 });
6146 }
6147 }
6148 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006149
6150 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006151 public void onProcessMapped(int pid, WindowProcessController proc) {
6152 synchronized (mGlobalLock) {
6153 mPidMap.put(pid, proc);
6154 }
6155 }
6156
6157 @Override
6158 public void onProcessUnMapped(int pid) {
6159 synchronized (mGlobalLock) {
6160 mPidMap.remove(pid);
6161 }
6162 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006163
6164 @Override
6165 public void onPackageDataCleared(String name) {
6166 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006167 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006168 mAppWarnings.onPackageDataCleared(name);
6169 }
6170 }
6171
6172 @Override
6173 public void onPackageUninstalled(String name) {
6174 synchronized (mGlobalLock) {
6175 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006176 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006177 }
6178 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006179
6180 @Override
6181 public void onPackageAdded(String name, boolean replacing) {
6182 synchronized (mGlobalLock) {
6183 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6184 }
6185 }
6186
6187 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006188 public void onPackageReplaced(ApplicationInfo aInfo) {
6189 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006190 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006191 }
6192 }
6193
6194 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006195 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6196 synchronized (mGlobalLock) {
6197 return compatibilityInfoForPackageLocked(ai);
6198 }
6199 }
6200
Yunfan Chen75157d72018-07-27 14:47:21 +09006201 /**
6202 * Set the corresponding display information for the process global configuration. To be
6203 * called when we need to show IME on a different display.
6204 *
6205 * @param pid The process id associated with the IME window.
6206 * @param displayId The ID of the display showing the IME.
6207 */
6208 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006209 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006210 if (pid == MY_PID || pid < 0) {
6211 if (DEBUG_CONFIGURATION) {
6212 Slog.w(TAG,
6213 "Trying to update display configuration for system/invalid process.");
6214 }
6215 return;
6216 }
6217 mH.post(() -> {
6218 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006219 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006220 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006221 if (activityDisplay == null) {
6222 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006223 if (DEBUG_CONFIGURATION) {
6224 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006225 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006226 }
6227 return;
6228 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006229 final WindowProcessController process = mPidMap.get(pid);
6230 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006231 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006232 Slog.w(TAG, "Trying to update display configuration for invalid "
6233 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006234 }
6235 return;
6236 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006237 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006238 }
6239 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006240
Yunfan Chen75157d72018-07-27 14:47:21 +09006241 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006242
6243 @Override
6244 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6245 int requestCode, int resultCode, Intent data) {
6246 synchronized (mGlobalLock) {
6247 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006248 if (r != null && r.getActivityStack() != null) {
6249 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6250 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006251 }
6252 }
6253 }
6254
6255 @Override
6256 public void clearPendingResultForActivity(IBinder activityToken,
6257 WeakReference<PendingIntentRecord> pir) {
6258 synchronized (mGlobalLock) {
6259 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6260 if (r != null && r.pendingResults != null) {
6261 r.pendingResults.remove(pir);
6262 }
6263 }
6264 }
6265
6266 @Override
6267 public IIntentSender getIntentSender(int type, String packageName,
6268 int callingUid, int userId, IBinder token, String resultWho,
6269 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6270 Bundle bOptions) {
6271 synchronized (mGlobalLock) {
6272 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6273 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6274 }
6275 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006276
6277 @Override
6278 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6279 synchronized (mGlobalLock) {
6280 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6281 if (r == null) {
6282 return null;
6283 }
6284 if (r.mServiceConnectionsHolder == null) {
6285 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6286 ActivityTaskManagerService.this, r);
6287 }
6288
6289 return r.mServiceConnectionsHolder;
6290 }
6291 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006292
6293 @Override
6294 public Intent getHomeIntent() {
6295 synchronized (mGlobalLock) {
6296 return ActivityTaskManagerService.this.getHomeIntent();
6297 }
6298 }
6299
6300 @Override
6301 public boolean startHomeActivity(int userId, String reason) {
6302 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006303 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006304 }
6305 }
6306
6307 @Override
6308 public boolean startHomeOnAllDisplays(int userId, String reason) {
6309 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006310 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006311 }
6312 }
6313
6314 @Override
6315 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6316 synchronized (mGlobalLock) {
6317 if (mFactoryTest == FACTORY_TEST_OFF) {
6318 return false;
6319 }
6320 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6321 && wpc.mName.equals(mTopComponent.getPackageName())) {
6322 return true;
6323 }
6324 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6325 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6326 }
6327 }
6328
6329 @Override
6330 public void updateTopComponentForFactoryTest() {
6331 synchronized (mGlobalLock) {
6332 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6333 return;
6334 }
6335 final ResolveInfo ri = mContext.getPackageManager()
6336 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6337 final CharSequence errorMsg;
6338 if (ri != null) {
6339 final ActivityInfo ai = ri.activityInfo;
6340 final ApplicationInfo app = ai.applicationInfo;
6341 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6342 mTopAction = Intent.ACTION_FACTORY_TEST;
6343 mTopData = null;
6344 mTopComponent = new ComponentName(app.packageName, ai.name);
6345 errorMsg = null;
6346 } else {
6347 errorMsg = mContext.getResources().getText(
6348 com.android.internal.R.string.factorytest_not_system);
6349 }
6350 } else {
6351 errorMsg = mContext.getResources().getText(
6352 com.android.internal.R.string.factorytest_no_action);
6353 }
6354 if (errorMsg == null) {
6355 return;
6356 }
6357
6358 mTopAction = null;
6359 mTopData = null;
6360 mTopComponent = null;
6361 mUiHandler.post(() -> {
6362 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6363 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006364 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006365 });
6366 }
6367 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006368
6369 @Override
6370 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6371 Runnable finishInstrumentationCallback) {
6372 synchronized (mGlobalLock) {
6373 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006374 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006375
6376 wpc.clearRecentTasks();
6377 wpc.clearActivities();
6378
6379 if (wpc.isInstrumenting()) {
6380 finishInstrumentationCallback.run();
6381 }
6382
Jorim Jaggid0752812018-10-16 16:07:20 +02006383 if (!restarting && hasVisibleActivities) {
6384 mWindowManager.deferSurfaceLayout();
6385 try {
6386 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6387 // If there was nothing to resume, and we are not already restarting
6388 // this process, but there is a visible activity that is hosted by the
6389 // process...then make sure all visible activities are running, taking
6390 // care of restarting this process.
6391 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6392 !PRESERVE_WINDOWS);
6393 }
6394 } finally {
6395 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006396 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006397 }
6398 }
6399 }
6400
6401 @Override
6402 public void closeSystemDialogs(String reason) {
6403 enforceNotIsolatedCaller("closeSystemDialogs");
6404
6405 final int pid = Binder.getCallingPid();
6406 final int uid = Binder.getCallingUid();
6407 final long origId = Binder.clearCallingIdentity();
6408 try {
6409 synchronized (mGlobalLock) {
6410 // Only allow this from foreground processes, so that background
6411 // applications can't abuse it to prevent system UI from being shown.
6412 if (uid >= FIRST_APPLICATION_UID) {
6413 final WindowProcessController proc = mPidMap.get(pid);
6414 if (!proc.isPerceptible()) {
6415 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6416 + " from background process " + proc);
6417 return;
6418 }
6419 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006420 mWindowManager.closeSystemDialogs(reason);
6421
Wale Ogunwaled32da472018-11-16 07:19:28 -08006422 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006423 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006424 // Call into AM outside the synchronized block.
6425 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006426 } finally {
6427 Binder.restoreCallingIdentity(origId);
6428 }
6429 }
6430
6431 @Override
6432 public void cleanupDisabledPackageComponents(
6433 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6434 synchronized (mGlobalLock) {
6435 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006436 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006437 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006438 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006439 mStackSupervisor.scheduleIdleLocked();
6440 }
6441
6442 // Clean-up disabled tasks
6443 getRecentTasks().cleanupDisabledPackageTasksLocked(
6444 packageName, disabledClasses, userId);
6445 }
6446 }
6447
6448 @Override
6449 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6450 int userId) {
6451 synchronized (mGlobalLock) {
6452
6453 boolean didSomething =
6454 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006455 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006456 null, doit, evenPersistent, userId);
6457 return didSomething;
6458 }
6459 }
6460
6461 @Override
6462 public void resumeTopActivities(boolean scheduleIdle) {
6463 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006464 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006465 if (scheduleIdle) {
6466 mStackSupervisor.scheduleIdleLocked();
6467 }
6468 }
6469 }
6470
6471 @Override
6472 public void preBindApplication(WindowProcessController wpc) {
6473 synchronized (mGlobalLock) {
6474 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6475 }
6476 }
6477
6478 @Override
6479 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6480 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006481 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006482 }
6483 }
6484
6485 @Override
6486 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6487 try {
6488 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6489 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6490 }
6491 } catch (RemoteException ex) {
6492 throw new SecurityException("Fail to check is caller a privileged app", ex);
6493 }
6494
6495 synchronized (mGlobalLock) {
6496 final long ident = Binder.clearCallingIdentity();
6497 try {
6498 if (mAmInternal.shouldConfirmCredentials(userId)) {
6499 if (mKeyguardController.isKeyguardLocked()) {
6500 // Showing launcher to avoid user entering credential twice.
6501 startHomeActivity(currentUserId, "notifyLockedProfile");
6502 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006503 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006504 }
6505 } finally {
6506 Binder.restoreCallingIdentity(ident);
6507 }
6508 }
6509 }
6510
6511 @Override
6512 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6513 mAmInternal.enforceCallingPermission(
6514 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6515
6516 synchronized (mGlobalLock) {
6517 final long ident = Binder.clearCallingIdentity();
6518 try {
6519 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6520 FLAG_ACTIVITY_TASK_ON_HOME);
6521 ActivityOptions activityOptions = options != null
6522 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006523 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006524 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006525 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006526 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006527 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006528 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6529 UserHandle.CURRENT);
6530 } finally {
6531 Binder.restoreCallingIdentity(ident);
6532 }
6533 }
6534 }
6535
6536 @Override
6537 public void writeActivitiesToProto(ProtoOutputStream proto) {
6538 synchronized (mGlobalLock) {
6539 // The output proto of "activity --proto activities"
6540 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006541 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006542 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6543 }
6544 }
6545
6546 @Override
6547 public void saveANRState(String reason) {
6548 synchronized (mGlobalLock) {
6549 final StringWriter sw = new StringWriter();
6550 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6551 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6552 if (reason != null) {
6553 pw.println(" Reason: " + reason);
6554 }
6555 pw.println();
6556 getActivityStartController().dump(pw, " ", null);
6557 pw.println();
6558 pw.println("-------------------------------------------------------------------------------");
6559 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6560 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6561 "" /* header */);
6562 pw.println();
6563 pw.close();
6564
6565 mLastANRState = sw.toString();
6566 }
6567 }
6568
6569 @Override
6570 public void clearSavedANRState() {
6571 synchronized (mGlobalLock) {
6572 mLastANRState = null;
6573 }
6574 }
6575
6576 @Override
6577 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6578 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6579 synchronized (mGlobalLock) {
6580 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6581 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6582 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6583 dumpLastANRLocked(pw);
6584 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6585 dumpLastANRTracesLocked(pw);
6586 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6587 dumpActivityStarterLocked(pw, dumpPackage);
6588 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6589 dumpActivityContainersLocked(pw);
6590 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6591 if (getRecentTasks() != null) {
6592 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6593 }
6594 }
6595 }
6596 }
6597
6598 @Override
6599 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6600 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6601 int wakefulness) {
6602 synchronized (mGlobalLock) {
6603 if (mHomeProcess != null && (dumpPackage == null
6604 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6605 if (needSep) {
6606 pw.println();
6607 needSep = false;
6608 }
6609 pw.println(" mHomeProcess: " + mHomeProcess);
6610 }
6611 if (mPreviousProcess != null && (dumpPackage == null
6612 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6613 if (needSep) {
6614 pw.println();
6615 needSep = false;
6616 }
6617 pw.println(" mPreviousProcess: " + mPreviousProcess);
6618 }
6619 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6620 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6621 StringBuilder sb = new StringBuilder(128);
6622 sb.append(" mPreviousProcessVisibleTime: ");
6623 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6624 pw.println(sb);
6625 }
6626 if (mHeavyWeightProcess != null && (dumpPackage == null
6627 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6628 if (needSep) {
6629 pw.println();
6630 needSep = false;
6631 }
6632 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6633 }
6634 if (dumpPackage == null) {
6635 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006636 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006637 }
6638 if (dumpAll) {
6639 if (dumpPackage == null) {
6640 pw.println(" mConfigWillChange: "
6641 + getTopDisplayFocusedStack().mConfigWillChange);
6642 }
6643 if (mCompatModePackages.getPackages().size() > 0) {
6644 boolean printed = false;
6645 for (Map.Entry<String, Integer> entry
6646 : mCompatModePackages.getPackages().entrySet()) {
6647 String pkg = entry.getKey();
6648 int mode = entry.getValue();
6649 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6650 continue;
6651 }
6652 if (!printed) {
6653 pw.println(" mScreenCompatPackages:");
6654 printed = true;
6655 }
6656 pw.println(" " + pkg + ": " + mode);
6657 }
6658 }
6659 }
6660
6661 if (dumpPackage == null) {
6662 pw.println(" mWakefulness="
6663 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006664 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006665 if (mRunningVoice != null) {
6666 pw.println(" mRunningVoice=" + mRunningVoice);
6667 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6668 }
6669 pw.println(" mSleeping=" + mSleeping);
6670 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6671 pw.println(" mVrController=" + mVrController);
6672 }
6673 if (mCurAppTimeTracker != null) {
6674 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6675 }
6676 if (mAllowAppSwitchUids.size() > 0) {
6677 boolean printed = false;
6678 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6679 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6680 for (int j = 0; j < types.size(); j++) {
6681 if (dumpPackage == null ||
6682 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6683 if (needSep) {
6684 pw.println();
6685 needSep = false;
6686 }
6687 if (!printed) {
6688 pw.println(" mAllowAppSwitchUids:");
6689 printed = true;
6690 }
6691 pw.print(" User ");
6692 pw.print(mAllowAppSwitchUids.keyAt(i));
6693 pw.print(": Type ");
6694 pw.print(types.keyAt(j));
6695 pw.print(" = ");
6696 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6697 pw.println();
6698 }
6699 }
6700 }
6701 }
6702 if (dumpPackage == null) {
6703 if (mController != null) {
6704 pw.println(" mController=" + mController
6705 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6706 }
6707 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6708 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6709 }
6710
6711 return needSep;
6712 }
6713 }
6714
6715 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006716 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6717 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 synchronized (mGlobalLock) {
6719 if (dumpPackage == null) {
6720 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6721 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006722 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6723 if (mRunningVoice != null) {
6724 final long vrToken = proto.start(
6725 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6726 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6727 mRunningVoice.toString());
6728 mVoiceWakeLock.writeToProto(
6729 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6730 proto.end(vrToken);
6731 }
6732 mVrController.writeToProto(proto,
6733 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734 if (mController != null) {
6735 final long token = proto.start(CONTROLLER);
6736 proto.write(CONTROLLER, mController.toString());
6737 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6738 proto.end(token);
6739 }
6740 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6741 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6742 }
6743
6744 if (mHomeProcess != null && (dumpPackage == null
6745 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006746 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006747 }
6748
6749 if (mPreviousProcess != null && (dumpPackage == null
6750 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006751 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6753 }
6754
6755 if (mHeavyWeightProcess != null && (dumpPackage == null
6756 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006757 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 }
6759
6760 for (Map.Entry<String, Integer> entry
6761 : mCompatModePackages.getPackages().entrySet()) {
6762 String pkg = entry.getKey();
6763 int mode = entry.getValue();
6764 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6765 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6766 proto.write(PACKAGE, pkg);
6767 proto.write(MODE, mode);
6768 proto.end(compatToken);
6769 }
6770 }
6771
6772 if (mCurAppTimeTracker != null) {
6773 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6774 }
6775
6776 }
6777 }
6778
6779 @Override
6780 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6781 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6782 boolean dumpFocusedStackOnly) {
6783 synchronized (mGlobalLock) {
6784 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6785 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6786 }
6787 }
6788
6789 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006790 public void dumpForOom(PrintWriter pw) {
6791 synchronized (mGlobalLock) {
6792 pw.println(" mHomeProcess: " + mHomeProcess);
6793 pw.println(" mPreviousProcess: " + mPreviousProcess);
6794 if (mHeavyWeightProcess != null) {
6795 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6796 }
6797 }
6798 }
6799
6800 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 public boolean canGcNow() {
6802 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006803 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 }
6805 }
6806
6807 @Override
6808 public WindowProcessController getTopApp() {
6809 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006810 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006811 return top != null ? top.app : null;
6812 }
6813 }
6814
6815 @Override
6816 public void rankTaskLayersIfNeeded() {
6817 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006818 if (mRootActivityContainer != null) {
6819 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 }
6821 }
6822 }
6823
6824 @Override
6825 public void scheduleDestroyAllActivities(String reason) {
6826 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006827 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006828 }
6829 }
6830
6831 @Override
6832 public void removeUser(int userId) {
6833 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006834 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835 }
6836 }
6837
6838 @Override
6839 public boolean switchUser(int userId, UserState userState) {
6840 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006841 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 }
6843 }
6844
6845 @Override
6846 public void onHandleAppCrash(WindowProcessController wpc) {
6847 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006848 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 }
6850 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006851
6852 @Override
6853 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6854 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006855 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006856 }
6857 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006858
6859 @Override
6860 public void onUidActive(int uid, int procState) {
6861 synchronized (mGlobalLock) {
6862 mActiveUids.put(uid, procState);
6863 }
6864 }
6865
6866 @Override
6867 public void onUidInactive(int uid) {
6868 synchronized (mGlobalLock) {
6869 mActiveUids.remove(uid);
6870 }
6871 }
6872
6873 @Override
6874 public void onActiveUidsCleared() {
6875 synchronized (mGlobalLock) {
6876 mActiveUids.clear();
6877 }
6878 }
6879
6880 @Override
6881 public void onUidProcStateChanged(int uid, int procState) {
6882 synchronized (mGlobalLock) {
6883 if (mActiveUids.get(uid) != null) {
6884 mActiveUids.put(uid, procState);
6885 }
6886 }
6887 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006888
6889 @Override
6890 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6891 synchronized (mGlobalLock) {
6892 mPendingTempWhitelist.put(uid, tag);
6893 }
6894 }
6895
6896 @Override
6897 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6898 synchronized (mGlobalLock) {
6899 mPendingTempWhitelist.remove(uid);
6900 }
6901 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006902
6903 @Override
6904 public boolean handleAppCrashInActivityController(String processName, int pid,
6905 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6906 Runnable killCrashingAppCallback) {
6907 synchronized (mGlobalLock) {
6908 if (mController == null) {
6909 return false;
6910 }
6911
6912 try {
6913 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6914 stackTrace)) {
6915 killCrashingAppCallback.run();
6916 return true;
6917 }
6918 } catch (RemoteException e) {
6919 mController = null;
6920 Watchdog.getInstance().setActivityController(null);
6921 }
6922 return false;
6923 }
6924 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006925
6926 @Override
6927 public void removeRecentTasksByPackageName(String packageName, int userId) {
6928 synchronized (mGlobalLock) {
6929 mRecentTasks.removeTasksByPackageName(packageName, userId);
6930 }
6931 }
6932
6933 @Override
6934 public void cleanupRecentTasksForUser(int userId) {
6935 synchronized (mGlobalLock) {
6936 mRecentTasks.cleanupLocked(userId);
6937 }
6938 }
6939
6940 @Override
6941 public void loadRecentTasksForUser(int userId) {
6942 synchronized (mGlobalLock) {
6943 mRecentTasks.loadUserRecentsLocked(userId);
6944 }
6945 }
6946
6947 @Override
6948 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6949 synchronized (mGlobalLock) {
6950 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6951 }
6952 }
6953
6954 @Override
6955 public void flushRecentTasks() {
6956 mRecentTasks.flush();
6957 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006958
6959 @Override
6960 public WindowProcessController getHomeProcess() {
6961 synchronized (mGlobalLock) {
6962 return mHomeProcess;
6963 }
6964 }
6965
6966 @Override
6967 public WindowProcessController getPreviousProcess() {
6968 synchronized (mGlobalLock) {
6969 return mPreviousProcess;
6970 }
6971 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006972
6973 @Override
6974 public void clearLockedTasks(String reason) {
6975 synchronized (mGlobalLock) {
6976 getLockTaskController().clearLockedTasks(reason);
6977 }
6978 }
6979
6980 @Override
6981 public void updateUserConfiguration() {
6982 synchronized (mGlobalLock) {
6983 final Configuration configuration = new Configuration(getGlobalConfiguration());
6984 final int currentUserId = mAmInternal.getCurrentUserId();
6985 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6986 configuration, currentUserId, Settings.System.canWrite(mContext));
6987 updateConfigurationLocked(configuration, null /* starting */,
6988 false /* initLocale */, false /* persistent */, currentUserId,
6989 false /* deferResume */);
6990 }
6991 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006992
6993 @Override
6994 public boolean canShowErrorDialogs() {
6995 synchronized (mGlobalLock) {
6996 return mShowDialogs && !mSleeping && !mShuttingDown
6997 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6998 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6999 mAmInternal.getCurrentUserId())
7000 && !(UserManager.isDeviceInDemoMode(mContext)
7001 && mAmInternal.getCurrentUser().isDemo());
7002 }
7003 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007004
7005 @Override
7006 public void setProfileApp(String profileApp) {
7007 synchronized (mGlobalLock) {
7008 mProfileApp = profileApp;
7009 }
7010 }
7011
7012 @Override
7013 public void setProfileProc(WindowProcessController wpc) {
7014 synchronized (mGlobalLock) {
7015 mProfileProc = wpc;
7016 }
7017 }
7018
7019 @Override
7020 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7021 synchronized (mGlobalLock) {
7022 mProfilerInfo = profilerInfo;
7023 }
7024 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007025
7026 @Override
7027 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7028 synchronized (mGlobalLock) {
7029 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7030 }
7031 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007032
7033 @Override
7034 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7035 synchronized (mGlobalLock) {
7036 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7037 }
7038 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007039 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007040}