blob: 791b2af8a5f25e1b88370241e8c85188eb793152 [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.ALWAYS_FINISH_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
62import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070063import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
64import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
66import 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;
94import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
95import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
96import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
97import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
98import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
115import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
116import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700117import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
119import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
120import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
122import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700123import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
124import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
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;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Looper;
194import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700197import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700248import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700263import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700264import com.android.server.pm.UserManagerService;
265import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267
Wale Ogunwale31913b52018-10-13 08:29:31 -0700268import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700271import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700274import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700275import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700276import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700278import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700279import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.util.Date;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700283import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Map;
285import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286
287/**
288 * System service for managing activities and their containers (task, stacks, displays,... ).
289 *
290 * {@hide}
291 */
292public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700293 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700295 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
296 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
297 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
298 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
299 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700300 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700302 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700303 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 /** Used to indicate that an app transition should be animated. */
308 static final boolean ANIMATE = true;
309
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700310 /** Hardware-reported OpenGLES version. */
311 final int GL_ES_VERSION;
312
Wale Ogunwale31913b52018-10-13 08:29:31 -0700313 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
314 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
315 public static final String DUMP_LASTANR_CMD = "lastanr" ;
316 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
317 public static final String DUMP_STARTER_CMD = "starter" ;
318 public static final String DUMP_CONTAINERS_CMD = "containers" ;
319 public static final String DUMP_RECENTS_CMD = "recents" ;
320 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
321
Wale Ogunwale64258362018-10-16 15:13:37 -0700322 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
323 public static final int RELAUNCH_REASON_NONE = 0;
324 /** This activity is being relaunched due to windowing mode change. */
325 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
326 /** This activity is being relaunched due to a free-resize operation. */
327 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
328
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700329 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700330
Wale Ogunwalef6733932018-06-27 05:14:34 -0700331 /**
332 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
333 * change at runtime. Use mContext for non-UI purposes.
334 */
335 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700336 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700337 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700340 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700341 private PackageManagerInternal mPmInternal;
Wale Ogunwale53783742018-09-16 10:21:51 -0700342 private ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700343 PowerManagerInternal mPowerManagerInternal;
344 private UsageStatsManagerInternal mUsageStatsInternal;
345
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700346 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 IntentFirewall mIntentFirewall;
348
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700349 /* Global service lock used by the package the owns this service. */
350 Object mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700351 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700353 private UserManagerService mUserManager;
354 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700355 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700356 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
357 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700358 /** All processes currently running that might have a window organized by name. */
359 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700360 /** All processes we currently have running mapped by pid */
361 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700362 /** This is the process holding what we currently consider to be the "home" activity. */
363 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700364 /** The currently running heavy-weight process, if any. */
365 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700366 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700367 /**
368 * This is the process holding the activity the user last visited that is in a different process
369 * from the one they are currently in.
370 */
371 WindowProcessController mPreviousProcess;
372 /** The time at which the previous process was last visible. */
373 long mPreviousProcessVisibleTime;
374
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 /** List of intents that were used to start the most recent tasks. */
376 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700377 /** State of external calls telling us if the device is awake or asleep. */
378 private boolean mKeyguardShown = false;
379
380 // Wrapper around VoiceInteractionServiceManager
381 private AssistUtils mAssistUtils;
382
383 // VoiceInteraction session ID that changes for each new request except when
384 // being called for multi-window assist in a single session.
385 private int mViSessionId = 1000;
386
387 // How long to wait in getAssistContextExtras for the activity and foreground services
388 // to respond with the result.
389 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
390
391 // How long top wait when going through the modern assist (which doesn't need to block
392 // on getting this result before starting to launch its UI).
393 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
394
395 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
396 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
397
398 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
399
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700400 // Keeps track of the active voice interaction service component, notified from
401 // VoiceInteractionManagerService
402 ComponentName mActiveVoiceInteractionServiceComponent;
403
Wale Ogunwalee2172292018-10-25 10:11:10 -0700404 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700405 KeyguardController mKeyguardController;
406 private final ClientLifecycleManager mLifecycleManager;
407 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700408 /** The controller for all operations related to locktask. */
409 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700410 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700411
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700412 boolean mSuppressResizeConfigChanges;
413
414 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
415 new UpdateConfigurationResult();
416
417 static final class UpdateConfigurationResult {
418 // Configuration changes that were updated.
419 int changes;
420 // If the activity was relaunched to match the new configuration.
421 boolean activityRelaunched;
422
423 void reset() {
424 changes = 0;
425 activityRelaunched = false;
426 }
427 }
428
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700429 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700430 private int mConfigurationSeq;
431 // To cache the list of supported system locales
432 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700433
434 /**
435 * Temp object used when global and/or display override configuration is updated. It is also
436 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
437 * anyone...
438 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700439 private Configuration mTempConfig = new Configuration();
440
Wale Ogunwalef6733932018-06-27 05:14:34 -0700441 /** Temporary to avoid allocations. */
442 final StringBuilder mStringBuilder = new StringBuilder(256);
443
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700444 // Amount of time after a call to stopAppSwitches() during which we will
445 // prevent further untrusted switches from happening.
446 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
447
448 /**
449 * The time at which we will allow normal application switches again,
450 * after a call to {@link #stopAppSwitches()}.
451 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700452 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700453 /**
454 * This is set to true after the first switch after mAppSwitchesAllowedTime
455 * is set; any switches after that will clear the time.
456 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700457 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700458
459 IActivityController mController = null;
460 boolean mControllerIsAMonkey = false;
461
Wale Ogunwale214f3482018-10-04 11:00:47 -0700462 final int mFactoryTest;
463
464 /** Used to control how we initialize the service. */
465 ComponentName mTopComponent;
466 String mTopAction = Intent.ACTION_MAIN;
467 String mTopData;
468
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700469 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700470 * Dump of the activity state at the time of the last ANR. Cleared after
471 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
472 */
473 String mLastANRState;
474
475 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700476 * Used to retain an update lock when the foreground activity is in
477 * immersive mode.
478 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700479 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480
481 /**
482 * Packages that are being allowed to perform unrestricted app switches. Mapping is
483 * User -> Type -> uid.
484 */
485 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
486
487 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700488 private int mThumbnailWidth;
489 private int mThumbnailHeight;
490 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491
492 /**
493 * Flag that indicates if multi-window is enabled.
494 *
495 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
496 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
497 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
498 * At least one of the forms of multi-window must be enabled in order for this flag to be
499 * initialized to 'true'.
500 *
501 * @see #mSupportsSplitScreenMultiWindow
502 * @see #mSupportsFreeformWindowManagement
503 * @see #mSupportsPictureInPicture
504 * @see #mSupportsMultiDisplay
505 */
506 boolean mSupportsMultiWindow;
507 boolean mSupportsSplitScreenMultiWindow;
508 boolean mSupportsFreeformWindowManagement;
509 boolean mSupportsPictureInPicture;
510 boolean mSupportsMultiDisplay;
511 boolean mForceResizableActivities;
512
513 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
514
515 // VR Vr2d Display Id.
516 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700517
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 /**
519 * Set while we are wanting to sleep, to prevent any
520 * activities from being started/resumed.
521 *
522 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
523 *
524 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
525 * while in the sleep state until there is a pending transition out of sleep, in which case
526 * mSleeping is set to false, and remains false while awake.
527 *
528 * Whether mSleeping can quickly toggled between true/false without the device actually
529 * display changing states is undefined.
530 */
531 private boolean mSleeping = false;
532
533 /**
534 * The process state used for processes that are running the top activities.
535 * This changes between TOP and TOP_SLEEPING to following mSleeping.
536 */
537 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
538
539 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
540 // automatically. Important for devices without direct input devices.
541 private boolean mShowDialogs = true;
542
543 /** Set if we are shutting down the system, similar to sleeping. */
544 boolean mShuttingDown = false;
545
546 /**
547 * We want to hold a wake lock while running a voice interaction session, since
548 * this may happen with the screen off and we need to keep the CPU running to
549 * be able to continue to interact with the user.
550 */
551 PowerManager.WakeLock mVoiceWakeLock;
552
553 /**
554 * Set while we are running a voice interaction. This overrides sleeping while it is active.
555 */
556 IVoiceInteractionSession mRunningVoice;
557
558 /**
559 * The last resumed activity. This is identical to the current resumed activity most
560 * of the time but could be different when we're pausing one activity before we resume
561 * another activity.
562 */
563 ActivityRecord mLastResumedActivity;
564
565 /**
566 * The activity that is currently being traced as the active resumed activity.
567 *
568 * @see #updateResumedAppTrace
569 */
570 private @Nullable ActivityRecord mTracedResumedActivity;
571
572 /** If non-null, we are tracking the time the user spends in the currently focused app. */
573 AppTimeTracker mCurAppTimeTracker;
574
Wale Ogunwale008163e2018-07-23 23:11:08 -0700575 private AppWarnings mAppWarnings;
576
Wale Ogunwale53783742018-09-16 10:21:51 -0700577 /**
578 * Packages that the user has asked to have run in screen size
579 * compatibility mode instead of filling the screen.
580 */
581 CompatModePackages mCompatModePackages;
582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 private FontScaleSettingObserver mFontScaleSettingObserver;
584
585 private final class FontScaleSettingObserver extends ContentObserver {
586 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
587 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
588
589 public FontScaleSettingObserver() {
590 super(mH);
591 final ContentResolver resolver = mContext.getContentResolver();
592 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
593 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
594 UserHandle.USER_ALL);
595 }
596
597 @Override
598 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
599 if (mFontScaleUri.equals(uri)) {
600 updateFontScaleIfNeeded(userId);
601 } else if (mHideErrorDialogsUri.equals(uri)) {
602 synchronized (mGlobalLock) {
603 updateShouldShowDialogsLocked(getGlobalConfiguration());
604 }
605 }
606 }
607 }
608
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700609 ActivityTaskManagerService(Context context) {
610 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700611 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700612 mSystemThread = ActivityThread.currentActivityThread();
613 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700614 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700615 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700616 }
617
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700618 public void onSystemReady() {
619 synchronized (mGlobalLock) {
620 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
621 PackageManager.FEATURE_CANT_SAVE_STATE);
622 mAssistUtils = new AssistUtils(mContext);
623 mVrController.onSystemReady();
624 mRecentTasks.onSystemReadyLocked();
625 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700626 }
627
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700628 public void onInitPowerManagement() {
629 synchronized (mGlobalLock) {
630 mStackSupervisor.initPowerManagement();
631 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
632 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
633 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
634 mVoiceWakeLock.setReferenceCounted(false);
635 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 }
637
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700638 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700639 mFontScaleSettingObserver = new FontScaleSettingObserver();
640 }
641
Wale Ogunwale59507092018-10-29 09:00:30 -0700642 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700643 final boolean freeformWindowManagement =
644 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
645 || Settings.Global.getInt(
646 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
647
648 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
649 final boolean supportsPictureInPicture = supportsMultiWindow &&
650 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
651 final boolean supportsSplitScreenMultiWindow =
652 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
653 final boolean supportsMultiDisplay = mContext.getPackageManager()
654 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
655 final boolean alwaysFinishActivities =
656 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
657 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
658 final boolean forceResizable = Settings.Global.getInt(
659 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700660 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700661
662 // Transfer any global setting for forcing RTL layout, into a System Property
663 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
664
665 final Configuration configuration = new Configuration();
666 Settings.System.getConfiguration(resolver, configuration);
667 if (forceRtl) {
668 // This will take care of setting the correct layout direction flags
669 configuration.setLayoutDirection(configuration.locale);
670 }
671
672 synchronized (mGlobalLock) {
673 mForceResizableActivities = forceResizable;
674 final boolean multiWindowFormEnabled = freeformWindowManagement
675 || supportsSplitScreenMultiWindow
676 || supportsPictureInPicture
677 || supportsMultiDisplay;
678 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
679 mSupportsMultiWindow = true;
680 mSupportsFreeformWindowManagement = freeformWindowManagement;
681 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
682 mSupportsPictureInPicture = supportsPictureInPicture;
683 mSupportsMultiDisplay = supportsMultiDisplay;
684 } else {
685 mSupportsMultiWindow = false;
686 mSupportsFreeformWindowManagement = false;
687 mSupportsSplitScreenMultiWindow = false;
688 mSupportsPictureInPicture = false;
689 mSupportsMultiDisplay = false;
690 }
691 mWindowManager.setForceResizableTasks(mForceResizableActivities);
692 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700693 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
694 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700695 // This happens before any activities are started, so we can change global configuration
696 // in-place.
697 updateConfigurationLocked(configuration, null, true);
698 final Configuration globalConfig = getGlobalConfiguration();
699 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
700
701 // Load resources only after the current configuration has been set.
702 final Resources res = mContext.getResources();
703 mThumbnailWidth = res.getDimensionPixelSize(
704 com.android.internal.R.dimen.thumbnail_width);
705 mThumbnailHeight = res.getDimensionPixelSize(
706 com.android.internal.R.dimen.thumbnail_height);
707
708 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
709 mFullscreenThumbnailScale = (float) res
710 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
711 (float) globalConfig.screenWidthDp;
712 } else {
713 mFullscreenThumbnailScale = res.getFraction(
714 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
715 }
716 }
717 }
718
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700719 // TODO: Will be converted to WM lock once transition is complete.
Wale Ogunwale59507092018-10-29 09:00:30 -0700720 public void setActivityManagerService(Object globalLock, Looper looper,
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700721 IntentFirewall intentFirewall, PendingIntentController intentController) {
Wale Ogunwale9de19442018-10-18 19:05:03 -0700722 mGlobalLock = globalLock;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700723 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700724 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700725 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700726 final File systemDir = SystemServiceManager.ensureSystemDir();
727 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
728 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700729 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700730
731 mTempConfig.setToDefaults();
732 mTempConfig.setLocales(LocaleList.getDefault());
733 mConfigurationSeq = mTempConfig.seq = 1;
734 mStackSupervisor = createStackSupervisor();
735 mStackSupervisor.onConfigurationChanged(mTempConfig);
736
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700737 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700738 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700739 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700740 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700741 mRecentTasks = createRecentTasks();
742 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700743 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700744 mKeyguardController = mStackSupervisor.getKeyguardController();
745 }
746
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700747 public void onActivityManagerInternalAdded() {
748 synchronized (mGlobalLock) {
749 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
750 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
751 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700752 }
753
Yunfan Chen75157d72018-07-27 14:47:21 +0900754 int increaseConfigurationSeqLocked() {
755 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
756 return mConfigurationSeq;
757 }
758
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700759 protected ActivityStackSupervisor createStackSupervisor() {
760 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
761 supervisor.initialize();
762 return supervisor;
763 }
764
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700765 public void setWindowManager(WindowManagerService wm) {
766 synchronized (mGlobalLock) {
767 mWindowManager = wm;
768 mLockTaskController.setWindowManager(wm);
769 mStackSupervisor.setWindowManager(wm);
770 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700771 }
772
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700773 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
774 synchronized (mGlobalLock) {
775 mUsageStatsInternal = usageStatsManager;
776 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700777 }
778
Wale Ogunwalef6733932018-06-27 05:14:34 -0700779 UserManagerService getUserManager() {
780 if (mUserManager == null) {
781 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
782 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
783 }
784 return mUserManager;
785 }
786
787 AppOpsService getAppOpsService() {
788 if (mAppOpsService == null) {
789 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
790 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
791 }
792 return mAppOpsService;
793 }
794
795 boolean hasUserRestriction(String restriction, int userId) {
796 return getUserManager().hasUserRestriction(restriction, userId);
797 }
798
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700799 protected RecentTasks createRecentTasks() {
800 return new RecentTasks(this, mStackSupervisor);
801 }
802
803 RecentTasks getRecentTasks() {
804 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700805 }
806
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700807 ClientLifecycleManager getLifecycleManager() {
808 return mLifecycleManager;
809 }
810
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700811 ActivityStartController getActivityStartController() {
812 return mActivityStartController;
813 }
814
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 TaskChangeNotificationController getTaskChangeNotificationController() {
816 return mTaskChangeNotificationController;
817 }
818
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700819 LockTaskController getLockTaskController() {
820 return mLockTaskController;
821 }
822
Yunfan Chen75157d72018-07-27 14:47:21 +0900823 /**
824 * Return the global configuration used by the process corresponding to the input pid. This is
825 * usually the global configuration with some overrides specific to that process.
826 */
827 Configuration getGlobalConfigurationForCallingPid() {
828 final int pid = Binder.getCallingPid();
829 if (pid == MY_PID || pid < 0) {
830 return getGlobalConfiguration();
831 }
832 synchronized (mGlobalLock) {
833 final WindowProcessController app = mPidMap.get(pid);
834 return app != null ? app.getConfiguration() : getGlobalConfiguration();
835 }
836 }
837
838 /**
839 * Return the device configuration info used by the process corresponding to the input pid.
840 * The value is consistent with the global configuration for the process.
841 */
842 @Override
843 public ConfigurationInfo getDeviceConfigurationInfo() {
844 ConfigurationInfo config = new ConfigurationInfo();
845 synchronized (mGlobalLock) {
846 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
847 config.reqTouchScreen = globalConfig.touchscreen;
848 config.reqKeyboardType = globalConfig.keyboard;
849 config.reqNavigation = globalConfig.navigation;
850 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
851 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
852 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
853 }
854 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
855 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
856 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
857 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700858 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900859 }
860 return config;
861 }
862
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700863 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700864 mInternal = new LocalService();
865 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700866 }
867
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700868 public static final class Lifecycle extends SystemService {
869 private final ActivityTaskManagerService mService;
870
871 public Lifecycle(Context context) {
872 super(context);
873 mService = new ActivityTaskManagerService(context);
874 }
875
876 @Override
877 public void onStart() {
878 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700879 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700880 }
881
882 public ActivityTaskManagerService getService() {
883 return mService;
884 }
885 }
886
887 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700888 public final int startActivity(IApplicationThread caller, String callingPackage,
889 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
890 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
891 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
892 resultWho, requestCode, startFlags, profilerInfo, bOptions,
893 UserHandle.getCallingUserId());
894 }
895
896 @Override
897 public final int startActivities(IApplicationThread caller, String callingPackage,
898 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
899 int userId) {
900 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700901 enforceNotIsolatedCaller(reason);
902 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700903 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700904 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100905 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
906 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700907 }
908
909 @Override
910 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
911 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
912 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
913 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
914 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
915 true /*validateIncomingUser*/);
916 }
917
918 int startActivityAsUser(IApplicationThread caller, String callingPackage,
919 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
920 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
921 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700922 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700923
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700924 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700925 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
926
927 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700928 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700929 .setCaller(caller)
930 .setCallingPackage(callingPackage)
931 .setResolvedType(resolvedType)
932 .setResultTo(resultTo)
933 .setResultWho(resultWho)
934 .setRequestCode(requestCode)
935 .setStartFlags(startFlags)
936 .setProfilerInfo(profilerInfo)
937 .setActivityOptions(bOptions)
938 .setMayWait(userId)
939 .execute();
940
941 }
942
943 @Override
944 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
945 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700946 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
947 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700948 // Refuse possible leaked file descriptors
949 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
950 throw new IllegalArgumentException("File descriptors passed in Intent");
951 }
952
953 if (!(target instanceof PendingIntentRecord)) {
954 throw new IllegalArgumentException("Bad PendingIntent object");
955 }
956
957 PendingIntentRecord pir = (PendingIntentRecord)target;
958
959 synchronized (mGlobalLock) {
960 // If this is coming from the currently resumed activity, it is
961 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700962 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700963 if (stack.mResumedActivity != null &&
964 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700965 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700966 }
967 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700968 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700970 }
971
972 @Override
973 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
974 Bundle bOptions) {
975 // Refuse possible leaked file descriptors
976 if (intent != null && intent.hasFileDescriptors()) {
977 throw new IllegalArgumentException("File descriptors passed in Intent");
978 }
979 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
980
981 synchronized (mGlobalLock) {
982 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
983 if (r == null) {
984 SafeActivityOptions.abort(options);
985 return false;
986 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700987 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700988 // The caller is not running... d'oh!
989 SafeActivityOptions.abort(options);
990 return false;
991 }
992 intent = new Intent(intent);
993 // The caller is not allowed to change the data.
994 intent.setDataAndType(r.intent.getData(), r.intent.getType());
995 // And we are resetting to find the next component...
996 intent.setComponent(null);
997
998 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
999
1000 ActivityInfo aInfo = null;
1001 try {
1002 List<ResolveInfo> resolves =
1003 AppGlobals.getPackageManager().queryIntentActivities(
1004 intent, r.resolvedType,
1005 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1006 UserHandle.getCallingUserId()).getList();
1007
1008 // Look for the original activity in the list...
1009 final int N = resolves != null ? resolves.size() : 0;
1010 for (int i=0; i<N; i++) {
1011 ResolveInfo rInfo = resolves.get(i);
1012 if (rInfo.activityInfo.packageName.equals(r.packageName)
1013 && rInfo.activityInfo.name.equals(r.info.name)) {
1014 // We found the current one... the next matching is
1015 // after it.
1016 i++;
1017 if (i<N) {
1018 aInfo = resolves.get(i).activityInfo;
1019 }
1020 if (debug) {
1021 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1022 + "/" + r.info.name);
1023 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1024 ? "null" : aInfo.packageName + "/" + aInfo.name));
1025 }
1026 break;
1027 }
1028 }
1029 } catch (RemoteException e) {
1030 }
1031
1032 if (aInfo == null) {
1033 // Nobody who is next!
1034 SafeActivityOptions.abort(options);
1035 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1036 return false;
1037 }
1038
1039 intent.setComponent(new ComponentName(
1040 aInfo.applicationInfo.packageName, aInfo.name));
1041 intent.setFlags(intent.getFlags()&~(
1042 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1043 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1044 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1045 FLAG_ACTIVITY_NEW_TASK));
1046
1047 // Okay now we need to start the new activity, replacing the currently running activity.
1048 // This is a little tricky because we want to start the new one as if the current one is
1049 // finished, but not finish the current one first so that there is no flicker.
1050 // And thus...
1051 final boolean wasFinishing = r.finishing;
1052 r.finishing = true;
1053
1054 // Propagate reply information over to the new activity.
1055 final ActivityRecord resultTo = r.resultTo;
1056 final String resultWho = r.resultWho;
1057 final int requestCode = r.requestCode;
1058 r.resultTo = null;
1059 if (resultTo != null) {
1060 resultTo.removeResultsLocked(r, resultWho, requestCode);
1061 }
1062
1063 final long origId = Binder.clearCallingIdentity();
1064 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001065 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001067 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001068 .setResolvedType(r.resolvedType)
1069 .setActivityInfo(aInfo)
1070 .setResultTo(resultTo != null ? resultTo.appToken : null)
1071 .setResultWho(resultWho)
1072 .setRequestCode(requestCode)
1073 .setCallingPid(-1)
1074 .setCallingUid(r.launchedFromUid)
1075 .setCallingPackage(r.launchedFromPackage)
1076 .setRealCallingPid(-1)
1077 .setRealCallingUid(r.launchedFromUid)
1078 .setActivityOptions(options)
1079 .execute();
1080 Binder.restoreCallingIdentity(origId);
1081
1082 r.finishing = wasFinishing;
1083 if (res != ActivityManager.START_SUCCESS) {
1084 return false;
1085 }
1086 return true;
1087 }
1088 }
1089
1090 @Override
1091 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1092 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1093 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1094 final WaitResult res = new WaitResult();
1095 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001096 enforceNotIsolatedCaller("startActivityAndWait");
1097 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1098 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001100 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001101 .setCaller(caller)
1102 .setCallingPackage(callingPackage)
1103 .setResolvedType(resolvedType)
1104 .setResultTo(resultTo)
1105 .setResultWho(resultWho)
1106 .setRequestCode(requestCode)
1107 .setStartFlags(startFlags)
1108 .setActivityOptions(bOptions)
1109 .setMayWait(userId)
1110 .setProfilerInfo(profilerInfo)
1111 .setWaitResult(res)
1112 .execute();
1113 }
1114 return res;
1115 }
1116
1117 @Override
1118 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1119 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1120 int startFlags, Configuration config, Bundle bOptions, int userId) {
1121 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001122 enforceNotIsolatedCaller("startActivityWithConfig");
1123 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1124 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001126 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001127 .setCaller(caller)
1128 .setCallingPackage(callingPackage)
1129 .setResolvedType(resolvedType)
1130 .setResultTo(resultTo)
1131 .setResultWho(resultWho)
1132 .setRequestCode(requestCode)
1133 .setStartFlags(startFlags)
1134 .setGlobalConfiguration(config)
1135 .setActivityOptions(bOptions)
1136 .setMayWait(userId)
1137 .execute();
1138 }
1139 }
1140
1141 @Override
1142 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1143 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1144 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
1145 int userId) {
1146
1147 // This is very dangerous -- it allows you to perform a start activity (including
1148 // permission grants) as any app that may launch one of your own activities. So
1149 // we will only allow this to be done from activities that are part of the core framework,
1150 // and then only when they are running as the system.
1151 final ActivityRecord sourceRecord;
1152 final int targetUid;
1153 final String targetPackage;
1154 final boolean isResolver;
1155 synchronized (mGlobalLock) {
1156 if (resultTo == null) {
1157 throw new SecurityException("Must be called from an activity");
1158 }
1159 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
1160 if (sourceRecord == null) {
1161 throw new SecurityException("Called with bad activity token: " + resultTo);
1162 }
1163 if (!sourceRecord.info.packageName.equals("android")) {
1164 throw new SecurityException(
1165 "Must be called from an activity that is declared in the android package");
1166 }
1167 if (sourceRecord.app == null) {
1168 throw new SecurityException("Called without a process attached to activity");
1169 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001170 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001171 // This is still okay, as long as this activity is running under the
1172 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001173 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001174 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001175 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001176 + " must be system uid or original calling uid "
1177 + sourceRecord.launchedFromUid);
1178 }
1179 }
1180 if (ignoreTargetSecurity) {
1181 if (intent.getComponent() == null) {
1182 throw new SecurityException(
1183 "Component must be specified with ignoreTargetSecurity");
1184 }
1185 if (intent.getSelector() != null) {
1186 throw new SecurityException(
1187 "Selector not allowed with ignoreTargetSecurity");
1188 }
1189 }
1190 targetUid = sourceRecord.launchedFromUid;
1191 targetPackage = sourceRecord.launchedFromPackage;
1192 isResolver = sourceRecord.isResolverOrChildActivity();
1193 }
1194
1195 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001196 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001197 }
1198
1199 // TODO: Switch to user app stacks here.
1200 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001201 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001202 .setCallingUid(targetUid)
1203 .setCallingPackage(targetPackage)
1204 .setResolvedType(resolvedType)
1205 .setResultTo(resultTo)
1206 .setResultWho(resultWho)
1207 .setRequestCode(requestCode)
1208 .setStartFlags(startFlags)
1209 .setActivityOptions(bOptions)
1210 .setMayWait(userId)
1211 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1212 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1213 .execute();
1214 } catch (SecurityException e) {
1215 // XXX need to figure out how to propagate to original app.
1216 // A SecurityException here is generally actually a fault of the original
1217 // calling activity (such as a fairly granting permissions), so propagate it
1218 // back to them.
1219 /*
1220 StringBuilder msg = new StringBuilder();
1221 msg.append("While launching");
1222 msg.append(intent.toString());
1223 msg.append(": ");
1224 msg.append(e.getMessage());
1225 */
1226 throw e;
1227 }
1228 }
1229
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001230 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1231 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1232 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1233 }
1234
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 @Override
1236 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1237 Intent intent, String resolvedType, IVoiceInteractionSession session,
1238 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1239 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001240 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001241 if (session == null || interactor == null) {
1242 throw new NullPointerException("null session or interactor");
1243 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001244 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001246 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001247 .setCallingUid(callingUid)
1248 .setCallingPackage(callingPackage)
1249 .setResolvedType(resolvedType)
1250 .setVoiceSession(session)
1251 .setVoiceInteractor(interactor)
1252 .setStartFlags(startFlags)
1253 .setProfilerInfo(profilerInfo)
1254 .setActivityOptions(bOptions)
1255 .setMayWait(userId)
1256 .execute();
1257 }
1258
1259 @Override
1260 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1261 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001262 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1263 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001265 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 .setCallingUid(callingUid)
1267 .setCallingPackage(callingPackage)
1268 .setResolvedType(resolvedType)
1269 .setActivityOptions(bOptions)
1270 .setMayWait(userId)
1271 .execute();
1272 }
1273
1274 @Override
1275 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1276 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001277 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 final int callingPid = Binder.getCallingPid();
1279 final long origId = Binder.clearCallingIdentity();
1280 try {
1281 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001282 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1283 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284
1285 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001286 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1287 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1289 recentsUid, assistDataReceiver);
1290 }
1291 } finally {
1292 Binder.restoreCallingIdentity(origId);
1293 }
1294 }
1295
1296 @Override
1297 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001298 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 "startActivityFromRecents()");
1300
1301 final int callingPid = Binder.getCallingPid();
1302 final int callingUid = Binder.getCallingUid();
1303 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1304 final long origId = Binder.clearCallingIdentity();
1305 try {
1306 synchronized (mGlobalLock) {
1307 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1308 safeOptions);
1309 }
1310 } finally {
1311 Binder.restoreCallingIdentity(origId);
1312 }
1313 }
1314
1315 /**
1316 * This is the internal entry point for handling Activity.finish().
1317 *
1318 * @param token The Binder token referencing the Activity we want to finish.
1319 * @param resultCode Result code, if any, from this Activity.
1320 * @param resultData Result data (Intent), if any, from this Activity.
1321 * @param finishTask Whether to finish the task associated with this Activity.
1322 *
1323 * @return Returns true if the activity successfully finished, or false if it is still running.
1324 */
1325 @Override
1326 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1327 int finishTask) {
1328 // Refuse possible leaked file descriptors
1329 if (resultData != null && resultData.hasFileDescriptors()) {
1330 throw new IllegalArgumentException("File descriptors passed in Intent");
1331 }
1332
1333 synchronized (mGlobalLock) {
1334 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1335 if (r == null) {
1336 return true;
1337 }
1338 // Keep track of the root activity of the task before we finish it
1339 TaskRecord tr = r.getTask();
1340 ActivityRecord rootR = tr.getRootActivity();
1341 if (rootR == null) {
1342 Slog.w(TAG, "Finishing task with all activities already finished");
1343 }
1344 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1345 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001346 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 return false;
1348 }
1349
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001350 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1351 // We should consolidate.
1352 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 // Find the first activity that is not finishing.
1354 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1355 if (next != null) {
1356 // ask watcher if this is allowed
1357 boolean resumeOK = true;
1358 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001359 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001361 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 Watchdog.getInstance().setActivityController(null);
1363 }
1364
1365 if (!resumeOK) {
1366 Slog.i(TAG, "Not finishing activity because controller resumed");
1367 return false;
1368 }
1369 }
1370 }
1371 final long origId = Binder.clearCallingIdentity();
1372 try {
1373 boolean res;
1374 final boolean finishWithRootActivity =
1375 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1376 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1377 || (finishWithRootActivity && r == rootR)) {
1378 // If requested, remove the task that is associated to this activity only if it
1379 // was the root activity in the task. The result code and data is ignored
1380 // because we don't support returning them across task boundaries. Also, to
1381 // keep backwards compatibility we remove the task from recents when finishing
1382 // task with root activity.
1383 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1384 finishWithRootActivity, "finish-activity");
1385 if (!res) {
1386 Slog.i(TAG, "Removing task failed to finish activity");
1387 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001388 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001389 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 } else {
1391 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1392 resultData, "app-request", true);
1393 if (!res) {
1394 Slog.i(TAG, "Failed to finish by app-request");
1395 }
1396 }
1397 return res;
1398 } finally {
1399 Binder.restoreCallingIdentity(origId);
1400 }
1401 }
1402 }
1403
1404 @Override
1405 public boolean finishActivityAffinity(IBinder token) {
1406 synchronized (mGlobalLock) {
1407 final long origId = Binder.clearCallingIdentity();
1408 try {
1409 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1410 if (r == null) {
1411 return false;
1412 }
1413
1414 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1415 // can finish.
1416 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001417 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 return false;
1419 }
1420 return task.getStack().finishActivityAffinityLocked(r);
1421 } finally {
1422 Binder.restoreCallingIdentity(origId);
1423 }
1424 }
1425 }
1426
1427 @Override
1428 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1429 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001430 try {
1431 WindowProcessController proc = null;
1432 synchronized (mGlobalLock) {
1433 ActivityStack stack = ActivityRecord.getStackLocked(token);
1434 if (stack == null) {
1435 return;
1436 }
1437 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1438 false /* fromTimeout */, false /* processPausingActivities */, config);
1439 if (r != null) {
1440 proc = r.app;
1441 }
1442 if (stopProfiling && proc != null) {
1443 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 }
1445 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001446 } finally {
1447 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 }
1450
1451 @Override
1452 public final void activityResumed(IBinder token) {
1453 final long origId = Binder.clearCallingIdentity();
1454 synchronized (mGlobalLock) {
1455 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001456 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 }
1458 Binder.restoreCallingIdentity(origId);
1459 }
1460
1461 @Override
1462 public final void activityPaused(IBinder token) {
1463 final long origId = Binder.clearCallingIdentity();
1464 synchronized (mGlobalLock) {
1465 ActivityStack stack = ActivityRecord.getStackLocked(token);
1466 if (stack != null) {
1467 stack.activityPausedLocked(token, false);
1468 }
1469 }
1470 Binder.restoreCallingIdentity(origId);
1471 }
1472
1473 @Override
1474 public final void activityStopped(IBinder token, Bundle icicle,
1475 PersistableBundle persistentState, CharSequence description) {
1476 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1477
1478 // Refuse possible leaked file descriptors
1479 if (icicle != null && icicle.hasFileDescriptors()) {
1480 throw new IllegalArgumentException("File descriptors passed in Bundle");
1481 }
1482
1483 final long origId = Binder.clearCallingIdentity();
1484
1485 synchronized (mGlobalLock) {
1486 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1487 if (r != null) {
1488 r.activityStoppedLocked(icicle, persistentState, description);
1489 }
1490 }
1491
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001492 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493
1494 Binder.restoreCallingIdentity(origId);
1495 }
1496
1497 @Override
1498 public final void activityDestroyed(IBinder token) {
1499 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1500 synchronized (mGlobalLock) {
1501 ActivityStack stack = ActivityRecord.getStackLocked(token);
1502 if (stack != null) {
1503 stack.activityDestroyedLocked(token, "activityDestroyed");
1504 }
1505 }
1506 }
1507
1508 @Override
1509 public final void activityRelaunched(IBinder token) {
1510 final long origId = Binder.clearCallingIdentity();
1511 synchronized (mGlobalLock) {
1512 mStackSupervisor.activityRelaunchedLocked(token);
1513 }
1514 Binder.restoreCallingIdentity(origId);
1515 }
1516
1517 public final void activitySlept(IBinder token) {
1518 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1519
1520 final long origId = Binder.clearCallingIdentity();
1521
1522 synchronized (mGlobalLock) {
1523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1524 if (r != null) {
1525 mStackSupervisor.activitySleptLocked(r);
1526 }
1527 }
1528
1529 Binder.restoreCallingIdentity(origId);
1530 }
1531
1532 @Override
1533 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1534 synchronized (mGlobalLock) {
1535 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1536 if (r == null) {
1537 return;
1538 }
1539 final long origId = Binder.clearCallingIdentity();
1540 try {
1541 r.setRequestedOrientation(requestedOrientation);
1542 } finally {
1543 Binder.restoreCallingIdentity(origId);
1544 }
1545 }
1546 }
1547
1548 @Override
1549 public int getRequestedOrientation(IBinder token) {
1550 synchronized (mGlobalLock) {
1551 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1552 if (r == null) {
1553 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1554 }
1555 return r.getRequestedOrientation();
1556 }
1557 }
1558
1559 @Override
1560 public void setImmersive(IBinder token, boolean immersive) {
1561 synchronized (mGlobalLock) {
1562 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1563 if (r == null) {
1564 throw new IllegalArgumentException();
1565 }
1566 r.immersive = immersive;
1567
1568 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001569 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001570 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001571 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 }
1573 }
1574 }
1575
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001576 void applyUpdateLockStateLocked(ActivityRecord r) {
1577 // Modifications to the UpdateLock state are done on our handler, outside
1578 // the activity manager's locks. The new state is determined based on the
1579 // state *now* of the relevant activity record. The object is passed to
1580 // the handler solely for logging detail, not to be consulted/modified.
1581 final boolean nextState = r != null && r.immersive;
1582 mH.post(() -> {
1583 if (mUpdateLock.isHeld() != nextState) {
1584 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1585 "Applying new update lock state '" + nextState + "' for " + r);
1586 if (nextState) {
1587 mUpdateLock.acquire();
1588 } else {
1589 mUpdateLock.release();
1590 }
1591 }
1592 });
1593 }
1594
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 @Override
1596 public boolean isImmersive(IBinder token) {
1597 synchronized (mGlobalLock) {
1598 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1599 if (r == null) {
1600 throw new IllegalArgumentException();
1601 }
1602 return r.immersive;
1603 }
1604 }
1605
1606 @Override
1607 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001608 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001610 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 return (r != null) ? r.immersive : false;
1612 }
1613 }
1614
1615 @Override
1616 public void overridePendingTransition(IBinder token, String packageName,
1617 int enterAnim, int exitAnim) {
1618 synchronized (mGlobalLock) {
1619 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1620 if (self == null) {
1621 return;
1622 }
1623
1624 final long origId = Binder.clearCallingIdentity();
1625
1626 if (self.isState(
1627 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001628 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1629 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001630 }
1631
1632 Binder.restoreCallingIdentity(origId);
1633 }
1634 }
1635
1636 @Override
1637 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001638 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001640 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001641 if (r == null) {
1642 return ActivityManager.COMPAT_MODE_UNKNOWN;
1643 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001644 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001645 }
1646 }
1647
1648 @Override
1649 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001650 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001652 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001654 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001655 if (r == null) {
1656 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1657 return;
1658 }
1659 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001660 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001661 }
1662 }
1663
1664 @Override
1665 public int getLaunchedFromUid(IBinder activityToken) {
1666 ActivityRecord srec;
1667 synchronized (mGlobalLock) {
1668 srec = ActivityRecord.forTokenLocked(activityToken);
1669 }
1670 if (srec == null) {
1671 return -1;
1672 }
1673 return srec.launchedFromUid;
1674 }
1675
1676 @Override
1677 public String getLaunchedFromPackage(IBinder activityToken) {
1678 ActivityRecord srec;
1679 synchronized (mGlobalLock) {
1680 srec = ActivityRecord.forTokenLocked(activityToken);
1681 }
1682 if (srec == null) {
1683 return null;
1684 }
1685 return srec.launchedFromPackage;
1686 }
1687
1688 @Override
1689 public boolean convertFromTranslucent(IBinder token) {
1690 final long origId = Binder.clearCallingIdentity();
1691 try {
1692 synchronized (mGlobalLock) {
1693 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1694 if (r == null) {
1695 return false;
1696 }
1697 final boolean translucentChanged = r.changeWindowTranslucency(true);
1698 if (translucentChanged) {
1699 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1700 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001701 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 return translucentChanged;
1703 }
1704 } finally {
1705 Binder.restoreCallingIdentity(origId);
1706 }
1707 }
1708
1709 @Override
1710 public boolean convertToTranslucent(IBinder token, Bundle options) {
1711 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1712 final long origId = Binder.clearCallingIdentity();
1713 try {
1714 synchronized (mGlobalLock) {
1715 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1716 if (r == null) {
1717 return false;
1718 }
1719 final TaskRecord task = r.getTask();
1720 int index = task.mActivities.lastIndexOf(r);
1721 if (index > 0) {
1722 ActivityRecord under = task.mActivities.get(index - 1);
1723 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1724 }
1725 final boolean translucentChanged = r.changeWindowTranslucency(false);
1726 if (translucentChanged) {
1727 r.getStack().convertActivityToTranslucent(r);
1728 }
1729 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001730 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 return translucentChanged;
1732 }
1733 } finally {
1734 Binder.restoreCallingIdentity(origId);
1735 }
1736 }
1737
1738 @Override
1739 public void notifyActivityDrawn(IBinder token) {
1740 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1741 synchronized (mGlobalLock) {
1742 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1743 if (r != null) {
1744 r.getStack().notifyActivityDrawnLocked(r);
1745 }
1746 }
1747 }
1748
1749 @Override
1750 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1751 synchronized (mGlobalLock) {
1752 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1753 if (r == null) {
1754 return;
1755 }
1756 r.reportFullyDrawnLocked(restoredFromBundle);
1757 }
1758 }
1759
1760 @Override
1761 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1762 synchronized (mGlobalLock) {
1763 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1764 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1765 return stack.mDisplayId;
1766 }
1767 return DEFAULT_DISPLAY;
1768 }
1769 }
1770
1771 @Override
1772 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001773 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 long ident = Binder.clearCallingIdentity();
1775 try {
1776 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001777 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 if (focusedStack != null) {
1779 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1780 }
1781 return null;
1782 }
1783 } finally {
1784 Binder.restoreCallingIdentity(ident);
1785 }
1786 }
1787
1788 @Override
1789 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1792 final long callingId = Binder.clearCallingIdentity();
1793 try {
1794 synchronized (mGlobalLock) {
1795 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1796 if (stack == null) {
1797 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1798 return;
1799 }
1800 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001801 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001802 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 }
1804 }
1805 } finally {
1806 Binder.restoreCallingIdentity(callingId);
1807 }
1808 }
1809
1810 @Override
1811 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001812 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1814 final long callingId = Binder.clearCallingIdentity();
1815 try {
1816 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001817 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1818 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 if (task == null) {
1820 return;
1821 }
1822 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001823 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001824 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 }
1826 }
1827 } finally {
1828 Binder.restoreCallingIdentity(callingId);
1829 }
1830 }
1831
1832 @Override
1833 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001834 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001835 synchronized (mGlobalLock) {
1836 final long ident = Binder.clearCallingIdentity();
1837 try {
1838 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1839 "remove-task");
1840 } finally {
1841 Binder.restoreCallingIdentity(ident);
1842 }
1843 }
1844 }
1845
1846 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001847 public void removeAllVisibleRecentTasks() {
1848 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1849 synchronized (mGlobalLock) {
1850 final long ident = Binder.clearCallingIdentity();
1851 try {
1852 getRecentTasks().removeAllVisibleTasks();
1853 } finally {
1854 Binder.restoreCallingIdentity(ident);
1855 }
1856 }
1857 }
1858
1859 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1861 synchronized (mGlobalLock) {
1862 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1863 if (srec != null) {
1864 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1865 }
1866 }
1867 return false;
1868 }
1869
1870 @Override
1871 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1872 Intent resultData) {
1873
1874 synchronized (mGlobalLock) {
1875 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1876 if (r != null) {
1877 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1878 }
1879 return false;
1880 }
1881 }
1882
1883 /**
1884 * Attempts to move a task backwards in z-order (the order of activities within the task is
1885 * unchanged).
1886 *
1887 * There are several possible results of this call:
1888 * - if the task is locked, then we will show the lock toast
1889 * - if there is a task behind the provided task, then that task is made visible and resumed as
1890 * this task is moved to the back
1891 * - otherwise, if there are no other tasks in the stack:
1892 * - if this task is in the pinned stack, then we remove the stack completely, which will
1893 * have the effect of moving the task to the top or bottom of the fullscreen stack
1894 * (depending on whether it is visible)
1895 * - otherwise, we simply return home and hide this task
1896 *
1897 * @param token A reference to the activity we wish to move
1898 * @param nonRoot If false then this only works if the activity is the root
1899 * of a task; if true it will work for any activity in a task.
1900 * @return Returns true if the move completed, false if not.
1901 */
1902 @Override
1903 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 synchronized (mGlobalLock) {
1906 final long origId = Binder.clearCallingIdentity();
1907 try {
1908 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1909 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1910 if (task != null) {
1911 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
1912 }
1913 } finally {
1914 Binder.restoreCallingIdentity(origId);
1915 }
1916 }
1917 return false;
1918 }
1919
1920 @Override
1921 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 long ident = Binder.clearCallingIdentity();
1924 Rect rect = new Rect();
1925 try {
1926 synchronized (mGlobalLock) {
1927 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1928 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1929 if (task == null) {
1930 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
1931 return rect;
1932 }
1933 if (task.getStack() != null) {
1934 // Return the bounds from window manager since it will be adjusted for various
1935 // things like the presense of a docked stack for tasks that aren't resizeable.
1936 task.getWindowContainerBounds(rect);
1937 } else {
1938 // Task isn't in window manager yet since it isn't associated with a stack.
1939 // Return the persist value from activity manager
1940 if (!task.matchParentBounds()) {
1941 rect.set(task.getBounds());
1942 } else if (task.mLastNonFullscreenBounds != null) {
1943 rect.set(task.mLastNonFullscreenBounds);
1944 }
1945 }
1946 }
1947 } finally {
1948 Binder.restoreCallingIdentity(ident);
1949 }
1950 return rect;
1951 }
1952
1953 @Override
1954 public ActivityManager.TaskDescription getTaskDescription(int id) {
1955 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001956 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
1958 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
1959 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1960 if (tr != null) {
1961 return tr.lastTaskDescription;
1962 }
1963 }
1964 return null;
1965 }
1966
1967 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001968 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
1969 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1970 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
1971 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
1972 return;
1973 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001974 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001975 synchronized (mGlobalLock) {
1976 final long ident = Binder.clearCallingIdentity();
1977 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001978 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1979 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001980 if (task == null) {
1981 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
1982 return;
1983 }
1984
1985 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
1986 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
1987
1988 if (!task.isActivityTypeStandardOrUndefined()) {
1989 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
1990 + " non-standard task " + taskId + " to windowing mode="
1991 + windowingMode);
1992 }
1993
1994 final ActivityStack stack = task.getStack();
1995 if (toTop) {
1996 stack.moveToFront("setTaskWindowingMode", task);
1997 }
1998 stack.setWindowingMode(windowingMode);
1999 } finally {
2000 Binder.restoreCallingIdentity(ident);
2001 }
2002 }
2003 }
2004
2005 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002007 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 ActivityRecord r = getCallingRecordLocked(token);
2009 return r != null ? r.info.packageName : null;
2010 }
2011 }
2012
2013 @Override
2014 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002015 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 ActivityRecord r = getCallingRecordLocked(token);
2017 return r != null ? r.intent.getComponent() : null;
2018 }
2019 }
2020
2021 private ActivityRecord getCallingRecordLocked(IBinder token) {
2022 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2023 if (r == null) {
2024 return null;
2025 }
2026 return r.resultTo;
2027 }
2028
2029 @Override
2030 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002031 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032
2033 synchronized (mGlobalLock) {
2034 final long origId = Binder.clearCallingIdentity();
2035 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002036 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 } finally {
2038 Binder.restoreCallingIdentity(origId);
2039 }
2040 }
2041 }
2042
2043 /**
2044 * TODO: Add mController hook
2045 */
2046 @Override
2047 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002048 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049
2050 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2051 synchronized (mGlobalLock) {
2052 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2053 false /* fromRecents */);
2054 }
2055 }
2056
2057 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2058 boolean fromRecents) {
2059
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002060 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 Binder.getCallingUid(), -1, -1, "Task to front")) {
2062 SafeActivityOptions.abort(options);
2063 return;
2064 }
2065 final long origId = Binder.clearCallingIdentity();
2066 try {
2067 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2068 if (task == null) {
2069 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002070 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 return;
2072 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002073 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002075 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 return;
2077 }
2078 ActivityOptions realOptions = options != null
2079 ? options.getOptions(mStackSupervisor)
2080 : null;
2081 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2082 false /* forceNonResizable */);
2083
2084 final ActivityRecord topActivity = task.getTopActivity();
2085 if (topActivity != null) {
2086
2087 // We are reshowing a task, use a starting window to hide the initial draw delay
2088 // so the transition can start earlier.
2089 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2090 true /* taskSwitch */, fromRecents);
2091 }
2092 } finally {
2093 Binder.restoreCallingIdentity(origId);
2094 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 }
2096
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002097 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2098 int callingPid, int callingUid, String name) {
2099 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2100 return true;
2101 }
2102
2103 if (getRecentTasks().isCallerRecents(sourceUid)) {
2104 return true;
2105 }
2106
2107 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2108 if (perm == PackageManager.PERMISSION_GRANTED) {
2109 return true;
2110 }
2111 if (checkAllowAppSwitchUid(sourceUid)) {
2112 return true;
2113 }
2114
2115 // If the actual IPC caller is different from the logical source, then
2116 // also see if they are allowed to control app switches.
2117 if (callingUid != -1 && callingUid != sourceUid) {
2118 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2119 if (perm == PackageManager.PERMISSION_GRANTED) {
2120 return true;
2121 }
2122 if (checkAllowAppSwitchUid(callingUid)) {
2123 return true;
2124 }
2125 }
2126
2127 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2128 return false;
2129 }
2130
2131 private boolean checkAllowAppSwitchUid(int uid) {
2132 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2133 if (types != null) {
2134 for (int i = types.size() - 1; i >= 0; i--) {
2135 if (types.valueAt(i).intValue() == uid) {
2136 return true;
2137 }
2138 }
2139 }
2140 return false;
2141 }
2142
2143 @Override
2144 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2145 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2146 "setActivityController()");
2147 synchronized (mGlobalLock) {
2148 mController = controller;
2149 mControllerIsAMonkey = imAMonkey;
2150 Watchdog.getInstance().setActivityController(controller);
2151 }
2152 }
2153
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002154 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002155 synchronized (mGlobalLock) {
2156 return mController != null && mControllerIsAMonkey;
2157 }
2158 }
2159
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002160 @Override
2161 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2162 synchronized (mGlobalLock) {
2163 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2164 }
2165 }
2166
2167 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002168 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2169 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2170 }
2171
2172 @Override
2173 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2174 @WindowConfiguration.ActivityType int ignoreActivityType,
2175 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2176 final int callingUid = Binder.getCallingUid();
2177 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2178
2179 synchronized (mGlobalLock) {
2180 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2181
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002182 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002183 callingUid);
2184 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2185 ignoreWindowingMode, callingUid, allowed);
2186 }
2187
2188 return list;
2189 }
2190
2191 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2193 synchronized (mGlobalLock) {
2194 final long origId = Binder.clearCallingIdentity();
2195 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2196 if (r != null) {
2197 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2198 }
2199 Binder.restoreCallingIdentity(origId);
2200 }
2201 }
2202
2203 @Override
2204 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002205 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 ActivityStack stack = ActivityRecord.getStackLocked(token);
2207 if (stack != null) {
2208 return stack.willActivityBeVisibleLocked(token);
2209 }
2210 return false;
2211 }
2212 }
2213
2214 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002215 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002216 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002217 synchronized (mGlobalLock) {
2218 final long ident = Binder.clearCallingIdentity();
2219 try {
2220 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2221 if (task == null) {
2222 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2223 return;
2224 }
2225
2226 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2227 + " to stackId=" + stackId + " toTop=" + toTop);
2228
2229 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2230 if (stack == null) {
2231 throw new IllegalStateException(
2232 "moveTaskToStack: No stack for stackId=" + stackId);
2233 }
2234 if (!stack.isActivityTypeStandardOrUndefined()) {
2235 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2236 + taskId + " to stack " + stackId);
2237 }
2238 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002239 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002240 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2241 }
2242 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2243 "moveTaskToStack");
2244 } finally {
2245 Binder.restoreCallingIdentity(ident);
2246 }
2247 }
2248 }
2249
2250 @Override
2251 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2252 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002253 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002254
2255 final long ident = Binder.clearCallingIdentity();
2256 try {
2257 synchronized (mGlobalLock) {
2258 if (animate) {
2259 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2260 if (stack == null) {
2261 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2262 return;
2263 }
2264 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2265 throw new IllegalArgumentException("Stack: " + stackId
2266 + " doesn't support animated resize.");
2267 }
2268 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2269 animationDuration, false /* fromFullscreen */);
2270 } else {
2271 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2272 if (stack == null) {
2273 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2274 return;
2275 }
2276 mStackSupervisor.resizeStackLocked(stack, destBounds,
2277 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2278 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2279 }
2280 }
2281 } finally {
2282 Binder.restoreCallingIdentity(ident);
2283 }
2284 }
2285
2286 /**
2287 * Moves the specified task to the primary-split-screen stack.
2288 *
2289 * @param taskId Id of task to move.
2290 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2291 * exist already. See
2292 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2293 * and
2294 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2295 * @param toTop If the task and stack should be moved to the top.
2296 * @param animate Whether we should play an animation for the moving the task.
2297 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2298 * stack. Pass {@code null} to use default bounds.
2299 * @param showRecents If the recents activity should be shown on the other side of the task
2300 * going into split-screen mode.
2301 */
2302 @Override
2303 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2304 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002306 "setTaskWindowingModeSplitScreenPrimary()");
2307 synchronized (mGlobalLock) {
2308 final long ident = Binder.clearCallingIdentity();
2309 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002310 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2311 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002312 if (task == null) {
2313 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2314 return false;
2315 }
2316 if (DEBUG_STACK) Slog.d(TAG_STACK,
2317 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2318 + " to createMode=" + createMode + " toTop=" + toTop);
2319 if (!task.isActivityTypeStandardOrUndefined()) {
2320 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2321 + " non-standard task " + taskId + " to split-screen windowing mode");
2322 }
2323
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002324 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002325 final int windowingMode = task.getWindowingMode();
2326 final ActivityStack stack = task.getStack();
2327 if (toTop) {
2328 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2329 }
2330 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2331 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2332 return windowingMode != task.getWindowingMode();
2333 } finally {
2334 Binder.restoreCallingIdentity(ident);
2335 }
2336 }
2337 }
2338
2339 /**
2340 * Removes stacks in the input windowing modes from the system if they are of activity type
2341 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2342 */
2343 @Override
2344 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002345 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002346 "removeStacksInWindowingModes()");
2347
2348 synchronized (mGlobalLock) {
2349 final long ident = Binder.clearCallingIdentity();
2350 try {
2351 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2352 } finally {
2353 Binder.restoreCallingIdentity(ident);
2354 }
2355 }
2356 }
2357
2358 @Override
2359 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002360 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002361 "removeStacksWithActivityTypes()");
2362
2363 synchronized (mGlobalLock) {
2364 final long ident = Binder.clearCallingIdentity();
2365 try {
2366 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2367 } finally {
2368 Binder.restoreCallingIdentity(ident);
2369 }
2370 }
2371 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372
2373 @Override
2374 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2375 int userId) {
2376 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002377 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2378 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002380 final boolean detailed = checkGetTasksPermission(
2381 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2382 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 == PackageManager.PERMISSION_GRANTED;
2384
2385 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002386 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 callingUid);
2388 }
2389 }
2390
2391 @Override
2392 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002393 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002394 long ident = Binder.clearCallingIdentity();
2395 try {
2396 synchronized (mGlobalLock) {
2397 return mStackSupervisor.getAllStackInfosLocked();
2398 }
2399 } finally {
2400 Binder.restoreCallingIdentity(ident);
2401 }
2402 }
2403
2404 @Override
2405 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002406 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 long ident = Binder.clearCallingIdentity();
2408 try {
2409 synchronized (mGlobalLock) {
2410 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2411 }
2412 } finally {
2413 Binder.restoreCallingIdentity(ident);
2414 }
2415 }
2416
2417 @Override
2418 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 final long callingUid = Binder.getCallingUid();
2421 final long origId = Binder.clearCallingIdentity();
2422 try {
2423 synchronized (mGlobalLock) {
2424 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002425 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002426 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2427 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2428 }
2429 } finally {
2430 Binder.restoreCallingIdentity(origId);
2431 }
2432 }
2433
2434 @Override
2435 public void startLockTaskModeByToken(IBinder token) {
2436 synchronized (mGlobalLock) {
2437 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2438 if (r == null) {
2439 return;
2440 }
2441 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2442 }
2443 }
2444
2445 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002446 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002447 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002448 // This makes inner call to look as if it was initiated by system.
2449 long ident = Binder.clearCallingIdentity();
2450 try {
2451 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002452 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2453 MATCH_TASK_IN_STACKS_ONLY);
2454 if (task == null) {
2455 return;
2456 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002457
2458 // When starting lock task mode the stack must be in front and focused
2459 task.getStack().moveToFront("startSystemLockTaskMode");
2460 startLockTaskModeLocked(task, true /* isSystemCaller */);
2461 }
2462 } finally {
2463 Binder.restoreCallingIdentity(ident);
2464 }
2465 }
2466
2467 @Override
2468 public void stopLockTaskModeByToken(IBinder token) {
2469 synchronized (mGlobalLock) {
2470 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2471 if (r == null) {
2472 return;
2473 }
2474 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2475 }
2476 }
2477
2478 /**
2479 * This API should be called by SystemUI only when user perform certain action to dismiss
2480 * lock task mode. We should only dismiss pinned lock task mode in this case.
2481 */
2482 @Override
2483 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002484 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002485 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2486 }
2487
2488 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2489 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2490 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2491 return;
2492 }
2493
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002494 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002495 if (stack == null || task != stack.topTask()) {
2496 throw new IllegalArgumentException("Invalid task, not in foreground");
2497 }
2498
2499 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2500 // system or a specific app.
2501 // * System-initiated requests will only start the pinned mode (screen pinning)
2502 // * App-initiated requests
2503 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2504 // - will start the pinned mode, otherwise
2505 final int callingUid = Binder.getCallingUid();
2506 long ident = Binder.clearCallingIdentity();
2507 try {
2508 // When a task is locked, dismiss the pinned stack if it exists
2509 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2510
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002511 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002512 } finally {
2513 Binder.restoreCallingIdentity(ident);
2514 }
2515 }
2516
2517 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2518 final int callingUid = Binder.getCallingUid();
2519 long ident = Binder.clearCallingIdentity();
2520 try {
2521 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002522 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523 }
2524 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2525 // task and jumping straight into a call in the case of emergency call back.
2526 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2527 if (tm != null) {
2528 tm.showInCallScreen(false);
2529 }
2530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
2533 }
2534
2535 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002536 public void updateLockTaskPackages(int userId, String[] packages) {
2537 final int callingUid = Binder.getCallingUid();
2538 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2539 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2540 "updateLockTaskPackages()");
2541 }
2542 synchronized (this) {
2543 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2544 + Arrays.toString(packages));
2545 getLockTaskController().updateLockTaskPackages(userId, packages);
2546 }
2547 }
2548
2549 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 public boolean isInLockTaskMode() {
2551 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2552 }
2553
2554 @Override
2555 public int getLockTaskModeState() {
2556 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002557 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 }
2559 }
2560
2561 @Override
2562 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2563 synchronized (mGlobalLock) {
2564 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2565 if (r != null) {
2566 r.setTaskDescription(td);
2567 final TaskRecord task = r.getTask();
2568 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002569 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002570 }
2571 }
2572 }
2573
2574 @Override
2575 public Bundle getActivityOptions(IBinder token) {
2576 final long origId = Binder.clearCallingIdentity();
2577 try {
2578 synchronized (mGlobalLock) {
2579 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2580 if (r != null) {
2581 final ActivityOptions activityOptions = r.takeOptionsLocked();
2582 return activityOptions == null ? null : activityOptions.toBundle();
2583 }
2584 return null;
2585 }
2586 } finally {
2587 Binder.restoreCallingIdentity(origId);
2588 }
2589 }
2590
2591 @Override
2592 public List<IBinder> getAppTasks(String callingPackage) {
2593 int callingUid = Binder.getCallingUid();
2594 long ident = Binder.clearCallingIdentity();
2595 try {
2596 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002597 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 }
2599 } finally {
2600 Binder.restoreCallingIdentity(ident);
2601 }
2602 }
2603
2604 @Override
2605 public void finishVoiceTask(IVoiceInteractionSession session) {
2606 synchronized (mGlobalLock) {
2607 final long origId = Binder.clearCallingIdentity();
2608 try {
2609 // TODO: VI Consider treating local voice interactions and voice tasks
2610 // differently here
2611 mStackSupervisor.finishVoiceTask(session);
2612 } finally {
2613 Binder.restoreCallingIdentity(origId);
2614 }
2615 }
2616
2617 }
2618
2619 @Override
2620 public boolean isTopOfTask(IBinder token) {
2621 synchronized (mGlobalLock) {
2622 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002623 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002624 }
2625 }
2626
2627 @Override
2628 public void notifyLaunchTaskBehindComplete(IBinder token) {
2629 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2630 }
2631
2632 @Override
2633 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002634 mH.post(() -> {
2635 synchronized (mGlobalLock) {
2636 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002637 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002638 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002639 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002640 } catch (RemoteException e) {
2641 }
2642 }
2643 }
2644
2645 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 }
2647
2648 /** Called from an app when assist data is ready. */
2649 @Override
2650 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2651 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002652 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 synchronized (pae) {
2654 pae.result = extras;
2655 pae.structure = structure;
2656 pae.content = content;
2657 if (referrer != null) {
2658 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2659 }
2660 if (structure != null) {
2661 structure.setHomeActivity(pae.isHome);
2662 }
2663 pae.haveResult = true;
2664 pae.notifyAll();
2665 if (pae.intent == null && pae.receiver == null) {
2666 // Caller is just waiting for the result.
2667 return;
2668 }
2669 }
2670 // We are now ready to launch the assist activity.
2671 IAssistDataReceiver sendReceiver = null;
2672 Bundle sendBundle = null;
2673 synchronized (mGlobalLock) {
2674 buildAssistBundleLocked(pae, extras);
2675 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002676 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002677 if (!exists) {
2678 // Timed out.
2679 return;
2680 }
2681
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002682 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002683 // Caller wants result sent back to them.
2684 sendBundle = new Bundle();
2685 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2686 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2687 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2688 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2689 }
2690 }
2691 if (sendReceiver != null) {
2692 try {
2693 sendReceiver.onHandleAssistData(sendBundle);
2694 } catch (RemoteException e) {
2695 }
2696 return;
2697 }
2698
2699 final long ident = Binder.clearCallingIdentity();
2700 try {
2701 if (TextUtils.equals(pae.intent.getAction(),
2702 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2703 pae.intent.putExtras(pae.extras);
2704 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2705 } else {
2706 pae.intent.replaceExtras(pae.extras);
2707 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2708 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2709 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002710 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002711
2712 try {
2713 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2714 } catch (ActivityNotFoundException e) {
2715 Slog.w(TAG, "No activity to handle assist action.", e);
2716 }
2717 }
2718 } finally {
2719 Binder.restoreCallingIdentity(ident);
2720 }
2721 }
2722
2723 @Override
2724 public int addAppTask(IBinder activityToken, Intent intent,
2725 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2726 final int callingUid = Binder.getCallingUid();
2727 final long callingIdent = Binder.clearCallingIdentity();
2728
2729 try {
2730 synchronized (mGlobalLock) {
2731 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2732 if (r == null) {
2733 throw new IllegalArgumentException("Activity does not exist; token="
2734 + activityToken);
2735 }
2736 ComponentName comp = intent.getComponent();
2737 if (comp == null) {
2738 throw new IllegalArgumentException("Intent " + intent
2739 + " must specify explicit component");
2740 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002741 if (thumbnail.getWidth() != mThumbnailWidth
2742 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 throw new IllegalArgumentException("Bad thumbnail size: got "
2744 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002745 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002746 }
2747 if (intent.getSelector() != null) {
2748 intent.setSelector(null);
2749 }
2750 if (intent.getSourceBounds() != null) {
2751 intent.setSourceBounds(null);
2752 }
2753 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2754 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2755 // The caller has added this as an auto-remove task... that makes no
2756 // sense, so turn off auto-remove.
2757 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2758 }
2759 }
2760 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2761 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2762 if (ainfo.applicationInfo.uid != callingUid) {
2763 throw new SecurityException(
2764 "Can't add task for another application: target uid="
2765 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2766 }
2767
2768 final ActivityStack stack = r.getStack();
2769 final TaskRecord task = stack.createTaskRecord(
2770 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2771 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002772 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 // The app has too many tasks already and we can't add any more
2774 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2775 return INVALID_TASK_ID;
2776 }
2777 task.lastTaskDescription.copyFrom(description);
2778
2779 // TODO: Send the thumbnail to WM to store it.
2780
2781 return task.taskId;
2782 }
2783 } finally {
2784 Binder.restoreCallingIdentity(callingIdent);
2785 }
2786 }
2787
2788 @Override
2789 public Point getAppTaskThumbnailSize() {
2790 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002791 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 }
2793 }
2794
2795 @Override
2796 public void setTaskResizeable(int taskId, int resizeableMode) {
2797 synchronized (mGlobalLock) {
2798 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2799 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2800 if (task == null) {
2801 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2802 return;
2803 }
2804 task.setResizeMode(resizeableMode);
2805 }
2806 }
2807
2808 @Override
2809 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 long ident = Binder.clearCallingIdentity();
2812 try {
2813 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002814 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2815 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 if (task == null) {
2817 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2818 return;
2819 }
2820 // Place the task in the right stack if it isn't there already based on
2821 // the requested bounds.
2822 // The stack transition logic is:
2823 // - a null bounds on a freeform task moves that task to fullscreen
2824 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2825 // that task to freeform
2826 // - otherwise the task is not moved
2827 ActivityStack stack = task.getStack();
2828 if (!task.getWindowConfiguration().canResizeTask()) {
2829 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2830 }
2831 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2832 stack = stack.getDisplay().getOrCreateStack(
2833 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2834 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2835 stack = stack.getDisplay().getOrCreateStack(
2836 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2837 }
2838
2839 // Reparent the task to the right stack if necessary
2840 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2841 if (stack != task.getStack()) {
2842 // Defer resume until the task is resized below
2843 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2844 DEFER_RESUME, "resizeTask");
2845 preserveWindow = false;
2846 }
2847
2848 // After reparenting (which only resizes the task to the stack bounds), resize the
2849 // task to the actual bounds provided
2850 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2851 }
2852 } finally {
2853 Binder.restoreCallingIdentity(ident);
2854 }
2855 }
2856
2857 @Override
2858 public boolean releaseActivityInstance(IBinder token) {
2859 synchronized (mGlobalLock) {
2860 final long origId = Binder.clearCallingIdentity();
2861 try {
2862 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2863 if (r == null) {
2864 return false;
2865 }
2866 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2867 } finally {
2868 Binder.restoreCallingIdentity(origId);
2869 }
2870 }
2871 }
2872
2873 @Override
2874 public void releaseSomeActivities(IApplicationThread appInt) {
2875 synchronized (mGlobalLock) {
2876 final long origId = Binder.clearCallingIdentity();
2877 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002878 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2880 } finally {
2881 Binder.restoreCallingIdentity(origId);
2882 }
2883 }
2884 }
2885
2886 @Override
2887 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002888 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002889 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 != PackageManager.PERMISSION_GRANTED) {
2891 throw new SecurityException("Requires permission "
2892 + android.Manifest.permission.DEVICE_POWER);
2893 }
2894
2895 synchronized (mGlobalLock) {
2896 long ident = Binder.clearCallingIdentity();
2897 if (mKeyguardShown != keyguardShowing) {
2898 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002899 final Message msg = PooledLambda.obtainMessage(
2900 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
2901 keyguardShowing);
2902 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 }
2904 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002905 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002906 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907 } finally {
2908 Binder.restoreCallingIdentity(ident);
2909 }
2910 }
2911
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002912 mH.post(() -> {
2913 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2914 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2915 }
2916 });
2917 }
2918
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002919 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002920 mH.post(() -> {
2921 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2922 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2923 }
2924 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 }
2926
2927 @Override
2928 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002929 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2930 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931
2932 final File passedIconFile = new File(filePath);
2933 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2934 passedIconFile.getName());
2935 if (!legitIconFile.getPath().equals(filePath)
2936 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2937 throw new IllegalArgumentException("Bad file path: " + filePath
2938 + " passed for userId " + userId);
2939 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002940 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 }
2942
2943 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002944 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2946 final ActivityOptions activityOptions = safeOptions != null
2947 ? safeOptions.getOptions(mStackSupervisor)
2948 : null;
2949 if (activityOptions == null
2950 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2951 || activityOptions.getCustomInPlaceResId() == 0) {
2952 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2953 "with valid animation");
2954 }
lumark588a3e82018-07-20 18:53:54 +08002955 // Get top display of front most application.
2956 final ActivityStack focusedStack = getTopDisplayFocusedStack();
2957 if (focusedStack != null) {
2958 final DisplayWindowController dwc =
2959 focusedStack.getDisplay().getWindowContainerController();
2960 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2961 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
2962 activityOptions.getCustomInPlaceResId());
2963 dwc.executeAppTransition();
2964 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 }
2966
2967 @Override
2968 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002969 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 synchronized (mGlobalLock) {
2971 final long ident = Binder.clearCallingIdentity();
2972 try {
2973 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2974 if (stack == null) {
2975 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2976 return;
2977 }
2978 if (!stack.isActivityTypeStandardOrUndefined()) {
2979 throw new IllegalArgumentException(
2980 "Removing non-standard stack is not allowed.");
2981 }
2982 mStackSupervisor.removeStack(stack);
2983 } finally {
2984 Binder.restoreCallingIdentity(ident);
2985 }
2986 }
2987 }
2988
2989 @Override
2990 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002991 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992
2993 synchronized (mGlobalLock) {
2994 final long ident = Binder.clearCallingIdentity();
2995 try {
2996 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
2997 + " to displayId=" + displayId);
2998 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
2999 } finally {
3000 Binder.restoreCallingIdentity(ident);
3001 }
3002 }
3003 }
3004
3005 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 public void exitFreeformMode(IBinder token) {
3007 synchronized (mGlobalLock) {
3008 long ident = Binder.clearCallingIdentity();
3009 try {
3010 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3011 if (r == null) {
3012 throw new IllegalArgumentException(
3013 "exitFreeformMode: No activity record matching token=" + token);
3014 }
3015
3016 final ActivityStack stack = r.getStack();
3017 if (stack == null || !stack.inFreeformWindowingMode()) {
3018 throw new IllegalStateException(
3019 "exitFreeformMode: You can only go fullscreen from freeform.");
3020 }
3021
3022 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3023 } finally {
3024 Binder.restoreCallingIdentity(ident);
3025 }
3026 }
3027 }
3028
3029 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3030 @Override
3031 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003032 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003034 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 }
3036
3037 /** Unregister a task stack listener so that it stops receiving callbacks. */
3038 @Override
3039 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003040 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003042 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 }
3044
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 @Override
3046 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3047 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3048 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3049 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3050 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3051 }
3052
3053 @Override
3054 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3055 IBinder activityToken, int flags) {
3056 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3057 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3058 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3059 }
3060
3061 @Override
3062 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3063 Bundle args) {
3064 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3065 true /* focused */, true /* newSessionId */, userHandle, args,
3066 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3067 }
3068
3069 @Override
3070 public Bundle getAssistContextExtras(int requestType) {
3071 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3072 null, null, true /* focused */, true /* newSessionId */,
3073 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3074 if (pae == null) {
3075 return null;
3076 }
3077 synchronized (pae) {
3078 while (!pae.haveResult) {
3079 try {
3080 pae.wait();
3081 } catch (InterruptedException e) {
3082 }
3083 }
3084 }
3085 synchronized (mGlobalLock) {
3086 buildAssistBundleLocked(pae, pae.result);
3087 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003088 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 }
3090 return pae.extras;
3091 }
3092
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003093 /**
3094 * Binder IPC calls go through the public entry point.
3095 * This can be called with or without the global lock held.
3096 */
3097 private static int checkCallingPermission(String permission) {
3098 return checkPermission(
3099 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3100 }
3101
3102 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003103 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003104 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3105 mAmInternal.enforceCallingPermission(permission, func);
3106 }
3107 }
3108
3109 @VisibleForTesting
3110 int checkGetTasksPermission(String permission, int pid, int uid) {
3111 return checkPermission(permission, pid, uid);
3112 }
3113
3114 static int checkPermission(String permission, int pid, int uid) {
3115 if (permission == null) {
3116 return PackageManager.PERMISSION_DENIED;
3117 }
3118 return checkComponentPermission(permission, pid, uid, -1, true);
3119 }
3120
Wale Ogunwale214f3482018-10-04 11:00:47 -07003121 public static int checkComponentPermission(String permission, int pid, int uid,
3122 int owningUid, boolean exported) {
3123 return ActivityManagerService.checkComponentPermission(
3124 permission, pid, uid, owningUid, exported);
3125 }
3126
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003127 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3128 if (getRecentTasks().isCallerRecents(callingUid)) {
3129 // Always allow the recents component to get tasks
3130 return true;
3131 }
3132
3133 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3134 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3135 if (!allowed) {
3136 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3137 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3138 // Temporary compatibility: some existing apps on the system image may
3139 // still be requesting the old permission and not switched to the new
3140 // one; if so, we'll still allow them full access. This means we need
3141 // to see if they are holding the old permission and are a system app.
3142 try {
3143 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3144 allowed = true;
3145 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3146 + " is using old GET_TASKS but privileged; allowing");
3147 }
3148 } catch (RemoteException e) {
3149 }
3150 }
3151 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3152 + " does not hold REAL_GET_TASKS; limiting output");
3153 }
3154 return allowed;
3155 }
3156
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3158 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3159 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3160 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003161 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 "enqueueAssistContext()");
3163
3164 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003165 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 if (activity == null) {
3167 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3168 return null;
3169 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003170 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3172 return null;
3173 }
3174 if (focused) {
3175 if (activityToken != null) {
3176 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3177 if (activity != caller) {
3178 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3179 + " is not current top " + activity);
3180 return null;
3181 }
3182 }
3183 } else {
3184 activity = ActivityRecord.forTokenLocked(activityToken);
3185 if (activity == null) {
3186 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3187 + " couldn't be found");
3188 return null;
3189 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003190 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3192 return null;
3193 }
3194 }
3195
3196 PendingAssistExtras pae;
3197 Bundle extras = new Bundle();
3198 if (args != null) {
3199 extras.putAll(args);
3200 }
3201 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003202 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203
3204 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3205 userHandle);
3206 pae.isHome = activity.isActivityTypeHome();
3207
3208 // Increment the sessionId if necessary
3209 if (newSessionId) {
3210 mViSessionId++;
3211 }
3212 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003213 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3214 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003216 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 } catch (RemoteException e) {
3218 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3219 return null;
3220 }
3221 return pae;
3222 }
3223 }
3224
3225 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3226 if (result != null) {
3227 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3228 }
3229 if (pae.hint != null) {
3230 pae.extras.putBoolean(pae.hint, true);
3231 }
3232 }
3233
3234 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3235 IAssistDataReceiver receiver;
3236 synchronized (mGlobalLock) {
3237 mPendingAssistExtras.remove(pae);
3238 receiver = pae.receiver;
3239 }
3240 if (receiver != null) {
3241 // Caller wants result sent back to them.
3242 Bundle sendBundle = new Bundle();
3243 // At least return the receiver extras
3244 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3245 try {
3246 pae.receiver.onHandleAssistData(sendBundle);
3247 } catch (RemoteException e) {
3248 }
3249 }
3250 }
3251
3252 public class PendingAssistExtras extends Binder implements Runnable {
3253 public final ActivityRecord activity;
3254 public boolean isHome;
3255 public final Bundle extras;
3256 public final Intent intent;
3257 public final String hint;
3258 public final IAssistDataReceiver receiver;
3259 public final int userHandle;
3260 public boolean haveResult = false;
3261 public Bundle result = null;
3262 public AssistStructure structure = null;
3263 public AssistContent content = null;
3264 public Bundle receiverExtras;
3265
3266 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3267 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3268 int _userHandle) {
3269 activity = _activity;
3270 extras = _extras;
3271 intent = _intent;
3272 hint = _hint;
3273 receiver = _receiver;
3274 receiverExtras = _receiverExtras;
3275 userHandle = _userHandle;
3276 }
3277
3278 @Override
3279 public void run() {
3280 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3281 synchronized (this) {
3282 haveResult = true;
3283 notifyAll();
3284 }
3285 pendingAssistExtrasTimedOut(this);
3286 }
3287 }
3288
3289 @Override
3290 public boolean isAssistDataAllowedOnCurrentActivity() {
3291 int userId;
3292 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003293 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003294 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3295 return false;
3296 }
3297
3298 final ActivityRecord activity = focusedStack.getTopActivity();
3299 if (activity == null) {
3300 return false;
3301 }
3302 userId = activity.userId;
3303 }
3304 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3305 }
3306
3307 @Override
3308 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3309 long ident = Binder.clearCallingIdentity();
3310 try {
3311 synchronized (mGlobalLock) {
3312 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003313 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 if (top != caller) {
3315 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3316 + " is not current top " + top);
3317 return false;
3318 }
3319 if (!top.nowVisible) {
3320 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3321 + " is not visible");
3322 return false;
3323 }
3324 }
3325 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3326 token);
3327 } finally {
3328 Binder.restoreCallingIdentity(ident);
3329 }
3330 }
3331
3332 @Override
3333 public boolean isRootVoiceInteraction(IBinder token) {
3334 synchronized (mGlobalLock) {
3335 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3336 if (r == null) {
3337 return false;
3338 }
3339 return r.rootVoiceInteraction;
3340 }
3341 }
3342
Wale Ogunwalef6733932018-06-27 05:14:34 -07003343 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3344 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3345 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3346 if (activityToCallback == null) return;
3347 activityToCallback.setVoiceSessionLocked(voiceSession);
3348
3349 // Inform the activity
3350 try {
3351 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3352 voiceInteractor);
3353 long token = Binder.clearCallingIdentity();
3354 try {
3355 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3356 } finally {
3357 Binder.restoreCallingIdentity(token);
3358 }
3359 // TODO: VI Should we cache the activity so that it's easier to find later
3360 // rather than scan through all the stacks and activities?
3361 } catch (RemoteException re) {
3362 activityToCallback.clearVoiceSessionLocked();
3363 // TODO: VI Should this terminate the voice session?
3364 }
3365 }
3366
3367 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3368 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3369 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3370 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3371 boolean wasRunningVoice = mRunningVoice != null;
3372 mRunningVoice = session;
3373 if (!wasRunningVoice) {
3374 mVoiceWakeLock.acquire();
3375 updateSleepIfNeededLocked();
3376 }
3377 }
3378 }
3379
3380 void finishRunningVoiceLocked() {
3381 if (mRunningVoice != null) {
3382 mRunningVoice = null;
3383 mVoiceWakeLock.release();
3384 updateSleepIfNeededLocked();
3385 }
3386 }
3387
3388 @Override
3389 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3390 synchronized (mGlobalLock) {
3391 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3392 if (keepAwake) {
3393 mVoiceWakeLock.acquire();
3394 } else {
3395 mVoiceWakeLock.release();
3396 }
3397 }
3398 }
3399 }
3400
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 @Override
3402 public ComponentName getActivityClassForToken(IBinder token) {
3403 synchronized (mGlobalLock) {
3404 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3405 if (r == null) {
3406 return null;
3407 }
3408 return r.intent.getComponent();
3409 }
3410 }
3411
3412 @Override
3413 public String getPackageForToken(IBinder token) {
3414 synchronized (mGlobalLock) {
3415 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3416 if (r == null) {
3417 return null;
3418 }
3419 return r.packageName;
3420 }
3421 }
3422
3423 @Override
3424 public void showLockTaskEscapeMessage(IBinder token) {
3425 synchronized (mGlobalLock) {
3426 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3427 if (r == null) {
3428 return;
3429 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003430 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 }
3432 }
3433
3434 @Override
3435 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003436 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 final long token = Binder.clearCallingIdentity();
3438 try {
3439 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003440 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003441 }
3442 } finally {
3443 Binder.restoreCallingIdentity(token);
3444 }
3445 }
3446
3447 /**
3448 * Try to place task to provided position. The final position might be different depending on
3449 * current user and stacks state. The task will be moved to target stack if it's currently in
3450 * different stack.
3451 */
3452 @Override
3453 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003454 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 synchronized (mGlobalLock) {
3456 long ident = Binder.clearCallingIdentity();
3457 try {
3458 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3459 + taskId + " in stackId=" + stackId + " at position=" + position);
3460 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3461 if (task == null) {
3462 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3463 + taskId);
3464 }
3465
3466 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3467
3468 if (stack == null) {
3469 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3470 + stackId);
3471 }
3472 if (!stack.isActivityTypeStandardOrUndefined()) {
3473 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3474 + " the position of task " + taskId + " in/to non-standard stack");
3475 }
3476
3477 // TODO: Have the callers of this API call a separate reparent method if that is
3478 // what they intended to do vs. having this method also do reparenting.
3479 if (task.getStack() == stack) {
3480 // Change position in current stack.
3481 stack.positionChildAt(task, position);
3482 } else {
3483 // Reparent to new stack.
3484 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3485 !DEFER_RESUME, "positionTaskInStack");
3486 }
3487 } finally {
3488 Binder.restoreCallingIdentity(ident);
3489 }
3490 }
3491 }
3492
3493 @Override
3494 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3495 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3496 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3497 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3498 synchronized (mGlobalLock) {
3499 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3500 if (record == null) {
3501 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3502 + "found for: " + token);
3503 }
3504 record.setSizeConfigurations(horizontalSizeConfiguration,
3505 verticalSizeConfigurations, smallestSizeConfigurations);
3506 }
3507 }
3508
3509 /**
3510 * Dismisses split-screen multi-window mode.
3511 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3512 */
3513 @Override
3514 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003515 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003516 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3517 final long ident = Binder.clearCallingIdentity();
3518 try {
3519 synchronized (mGlobalLock) {
3520 final ActivityStack stack =
3521 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3522 if (stack == null) {
3523 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3524 return;
3525 }
3526
3527 if (toTop) {
3528 // Caller wants the current split-screen primary stack to be the top stack after
3529 // it goes fullscreen, so move it to the front.
3530 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003531 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003532 // In this case the current split-screen primary stack shouldn't be the top
3533 // stack after it goes fullscreen, but it current has focus, so we move the
3534 // focus to the top-most split-screen secondary stack next to it.
3535 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3536 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3537 if (otherStack != null) {
3538 otherStack.moveToFront("dismissSplitScreenMode_other");
3539 }
3540 }
3541
Evan Rosky10475742018-09-05 19:02:48 -07003542 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003543 }
3544 } finally {
3545 Binder.restoreCallingIdentity(ident);
3546 }
3547 }
3548
3549 /**
3550 * Dismisses Pip
3551 * @param animate True if the dismissal should be animated.
3552 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3553 * default animation duration should be used.
3554 */
3555 @Override
3556 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 final long ident = Binder.clearCallingIdentity();
3559 try {
3560 synchronized (mGlobalLock) {
3561 final PinnedActivityStack stack =
3562 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3563 if (stack == null) {
3564 Slog.w(TAG, "dismissPip: pinned stack not found.");
3565 return;
3566 }
3567 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3568 throw new IllegalArgumentException("Stack: " + stack
3569 + " doesn't support animated resize.");
3570 }
3571 if (animate) {
3572 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3573 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3574 } else {
3575 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3576 }
3577 }
3578 } finally {
3579 Binder.restoreCallingIdentity(ident);
3580 }
3581 }
3582
3583 @Override
3584 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003585 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003586 synchronized (mGlobalLock) {
3587 mSuppressResizeConfigChanges = suppress;
3588 }
3589 }
3590
3591 /**
3592 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3593 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3594 * activity and clearing the task at the same time.
3595 */
3596 @Override
3597 // TODO: API should just be about changing windowing modes...
3598 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003599 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003600 "moveTasksToFullscreenStack()");
3601 synchronized (mGlobalLock) {
3602 final long origId = Binder.clearCallingIdentity();
3603 try {
3604 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3605 if (stack != null){
3606 if (!stack.isActivityTypeStandardOrUndefined()) {
3607 throw new IllegalArgumentException(
3608 "You can't move tasks from non-standard stacks.");
3609 }
3610 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3611 }
3612 } finally {
3613 Binder.restoreCallingIdentity(origId);
3614 }
3615 }
3616 }
3617
3618 /**
3619 * Moves the top activity in the input stackId to the pinned stack.
3620 *
3621 * @param stackId Id of stack to move the top activity to pinned stack.
3622 * @param bounds Bounds to use for pinned stack.
3623 *
3624 * @return True if the top activity of the input stack was successfully moved to the pinned
3625 * stack.
3626 */
3627 @Override
3628 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003629 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003630 "moveTopActivityToPinnedStack()");
3631 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003632 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003633 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3634 + "Device doesn't support picture-in-picture mode");
3635 }
3636
3637 long ident = Binder.clearCallingIdentity();
3638 try {
3639 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3640 } finally {
3641 Binder.restoreCallingIdentity(ident);
3642 }
3643 }
3644 }
3645
3646 @Override
3647 public boolean isInMultiWindowMode(IBinder token) {
3648 final long origId = Binder.clearCallingIdentity();
3649 try {
3650 synchronized (mGlobalLock) {
3651 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3652 if (r == null) {
3653 return false;
3654 }
3655 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3656 return r.inMultiWindowMode();
3657 }
3658 } finally {
3659 Binder.restoreCallingIdentity(origId);
3660 }
3661 }
3662
3663 @Override
3664 public boolean isInPictureInPictureMode(IBinder token) {
3665 final long origId = Binder.clearCallingIdentity();
3666 try {
3667 synchronized (mGlobalLock) {
3668 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3669 }
3670 } finally {
3671 Binder.restoreCallingIdentity(origId);
3672 }
3673 }
3674
3675 private boolean isInPictureInPictureMode(ActivityRecord r) {
3676 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3677 || r.getStack().isInStackLocked(r) == null) {
3678 return false;
3679 }
3680
3681 // If we are animating to fullscreen then we have already dispatched the PIP mode
3682 // changed, so we should reflect that check here as well.
3683 final PinnedActivityStack stack = r.getStack();
3684 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3685 return !windowController.isAnimatingBoundsToFullscreen();
3686 }
3687
3688 @Override
3689 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3690 final long origId = Binder.clearCallingIdentity();
3691 try {
3692 synchronized (mGlobalLock) {
3693 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3694 "enterPictureInPictureMode", token, params);
3695
3696 // If the activity is already in picture in picture mode, then just return early
3697 if (isInPictureInPictureMode(r)) {
3698 return true;
3699 }
3700
3701 // Activity supports picture-in-picture, now check that we can enter PiP at this
3702 // point, if it is
3703 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3704 false /* beforeStopping */)) {
3705 return false;
3706 }
3707
3708 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003709 synchronized (mGlobalLock) {
3710 // Only update the saved args from the args that are set
3711 r.pictureInPictureArgs.copyOnlySet(params);
3712 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3713 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3714 // Adjust the source bounds by the insets for the transition down
3715 final Rect sourceBounds = new Rect(
3716 r.pictureInPictureArgs.getSourceRectHint());
3717 mStackSupervisor.moveActivityToPinnedStackLocked(
3718 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3719 final PinnedActivityStack stack = r.getStack();
3720 stack.setPictureInPictureAspectRatio(aspectRatio);
3721 stack.setPictureInPictureActions(actions);
3722 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3723 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3724 logPictureInPictureArgs(params);
3725 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003726 };
3727
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003728 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 // If the keyguard is showing or occluded, then try and dismiss it before
3730 // entering picture-in-picture (this will prompt the user to authenticate if the
3731 // device is currently locked).
3732 dismissKeyguard(token, new KeyguardDismissCallback() {
3733 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003734 public void onDismissSucceeded() {
3735 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003736 }
3737 }, null /* message */);
3738 } else {
3739 // Enter picture in picture immediately otherwise
3740 enterPipRunnable.run();
3741 }
3742 return true;
3743 }
3744 } finally {
3745 Binder.restoreCallingIdentity(origId);
3746 }
3747 }
3748
3749 @Override
3750 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3751 final long origId = Binder.clearCallingIdentity();
3752 try {
3753 synchronized (mGlobalLock) {
3754 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3755 "setPictureInPictureParams", token, params);
3756
3757 // Only update the saved args from the args that are set
3758 r.pictureInPictureArgs.copyOnlySet(params);
3759 if (r.inPinnedWindowingMode()) {
3760 // If the activity is already in picture-in-picture, update the pinned stack now
3761 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3762 // be used the next time the activity enters PiP
3763 final PinnedActivityStack stack = r.getStack();
3764 if (!stack.isAnimatingBoundsToFullscreen()) {
3765 stack.setPictureInPictureAspectRatio(
3766 r.pictureInPictureArgs.getAspectRatio());
3767 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3768 }
3769 }
3770 logPictureInPictureArgs(params);
3771 }
3772 } finally {
3773 Binder.restoreCallingIdentity(origId);
3774 }
3775 }
3776
3777 @Override
3778 public int getMaxNumPictureInPictureActions(IBinder token) {
3779 // Currently, this is a static constant, but later, we may change this to be dependent on
3780 // the context of the activity
3781 return 3;
3782 }
3783
3784 private void logPictureInPictureArgs(PictureInPictureParams params) {
3785 if (params.hasSetActions()) {
3786 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3787 params.getActions().size());
3788 }
3789 if (params.hasSetAspectRatio()) {
3790 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3791 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3792 MetricsLogger.action(lm);
3793 }
3794 }
3795
3796 /**
3797 * Checks the state of the system and the activity associated with the given {@param token} to
3798 * verify that picture-in-picture is supported for that activity.
3799 *
3800 * @return the activity record for the given {@param token} if all the checks pass.
3801 */
3802 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3803 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003804 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003805 throw new IllegalStateException(caller
3806 + ": Device doesn't support picture-in-picture mode.");
3807 }
3808
3809 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3810 if (r == null) {
3811 throw new IllegalStateException(caller
3812 + ": Can't find activity for token=" + token);
3813 }
3814
3815 if (!r.supportsPictureInPicture()) {
3816 throw new IllegalStateException(caller
3817 + ": Current activity does not support picture-in-picture.");
3818 }
3819
3820 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003821 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 params.getAspectRatio())) {
3823 final float minAspectRatio = mContext.getResources().getFloat(
3824 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3825 final float maxAspectRatio = mContext.getResources().getFloat(
3826 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3827 throw new IllegalArgumentException(String.format(caller
3828 + ": Aspect ratio is too extreme (must be between %f and %f).",
3829 minAspectRatio, maxAspectRatio));
3830 }
3831
3832 // Truncate the number of actions if necessary
3833 params.truncateActions(getMaxNumPictureInPictureActions(token));
3834
3835 return r;
3836 }
3837
3838 @Override
3839 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003840 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 synchronized (mGlobalLock) {
3842 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3843 if (r == null) {
3844 throw new IllegalArgumentException("Activity does not exist; token="
3845 + activityToken);
3846 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003847 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 }
3849 }
3850
3851 @Override
3852 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3853 Rect tempDockedTaskInsetBounds,
3854 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003855 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003856 long ident = Binder.clearCallingIdentity();
3857 try {
3858 synchronized (mGlobalLock) {
3859 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3860 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3861 PRESERVE_WINDOWS);
3862 }
3863 } finally {
3864 Binder.restoreCallingIdentity(ident);
3865 }
3866 }
3867
3868 @Override
3869 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003870 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 final long ident = Binder.clearCallingIdentity();
3872 try {
3873 synchronized (mGlobalLock) {
3874 mStackSupervisor.setSplitScreenResizing(resizing);
3875 }
3876 } finally {
3877 Binder.restoreCallingIdentity(ident);
3878 }
3879 }
3880
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003881 /**
3882 * Check that we have the features required for VR-related API calls, and throw an exception if
3883 * not.
3884 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003885 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003886 if (!mContext.getPackageManager().hasSystemFeature(
3887 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3888 throw new UnsupportedOperationException("VR mode not supported on this device!");
3889 }
3890 }
3891
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003892 @Override
3893 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003894 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895
3896 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3897
3898 ActivityRecord r;
3899 synchronized (mGlobalLock) {
3900 r = ActivityRecord.isInStackLocked(token);
3901 }
3902
3903 if (r == null) {
3904 throw new IllegalArgumentException();
3905 }
3906
3907 int err;
3908 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3909 VrManagerInternal.NO_ERROR) {
3910 return err;
3911 }
3912
3913 // Clear the binder calling uid since this path may call moveToTask().
3914 final long callingId = Binder.clearCallingIdentity();
3915 try {
3916 synchronized (mGlobalLock) {
3917 r.requestedVrComponent = (enabled) ? packageName : null;
3918
3919 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003920 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003921 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 }
3923 return 0;
3924 }
3925 } finally {
3926 Binder.restoreCallingIdentity(callingId);
3927 }
3928 }
3929
3930 @Override
3931 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3932 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3933 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003934 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3936 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3937 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003938 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 || activity.voiceSession != null) {
3940 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3941 return;
3942 }
3943 if (activity.pendingVoiceInteractionStart) {
3944 Slog.w(TAG, "Pending start of voice interaction already.");
3945 return;
3946 }
3947 activity.pendingVoiceInteractionStart = true;
3948 }
3949 LocalServices.getService(VoiceInteractionManagerInternal.class)
3950 .startLocalVoiceInteraction(callingActivity, options);
3951 }
3952
3953 @Override
3954 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3955 LocalServices.getService(VoiceInteractionManagerInternal.class)
3956 .stopLocalVoiceInteraction(callingActivity);
3957 }
3958
3959 @Override
3960 public boolean supportsLocalVoiceInteraction() {
3961 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3962 .supportsLocalVoiceInteraction();
3963 }
3964
3965 /** Notifies all listeners when the pinned stack animation starts. */
3966 @Override
3967 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003968 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003969 }
3970
3971 /** Notifies all listeners when the pinned stack animation ends. */
3972 @Override
3973 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003974 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 }
3976
3977 @Override
3978 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003979 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 final long ident = Binder.clearCallingIdentity();
3981 try {
3982 synchronized (mGlobalLock) {
3983 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3984 }
3985 } finally {
3986 Binder.restoreCallingIdentity(ident);
3987 }
3988 }
3989
3990 @Override
3991 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993
3994 synchronized (mGlobalLock) {
3995 // Check if display is initialized in AM.
3996 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3997 // Call might come when display is not yet added or has already been removed.
3998 if (DEBUG_CONFIGURATION) {
3999 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4000 + displayId);
4001 }
4002 return false;
4003 }
4004
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004005 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 }
4009
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004010 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004011 final Message msg = PooledLambda.obtainMessage(
4012 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4013 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 }
4015
4016 final long origId = Binder.clearCallingIdentity();
4017 try {
4018 if (values != null) {
4019 Settings.System.clearConfiguration(values);
4020 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004021 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4023 return mTmpUpdateConfigurationResult.changes != 0;
4024 } finally {
4025 Binder.restoreCallingIdentity(origId);
4026 }
4027 }
4028 }
4029
4030 @Override
4031 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033
4034 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004035 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 }
4039
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004040 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004041 final Message msg = PooledLambda.obtainMessage(
4042 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4043 DEFAULT_DISPLAY);
4044 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 }
4046
4047 final long origId = Binder.clearCallingIdentity();
4048 try {
4049 if (values != null) {
4050 Settings.System.clearConfiguration(values);
4051 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004052 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 UserHandle.USER_NULL, false /* deferResume */,
4054 mTmpUpdateConfigurationResult);
4055 return mTmpUpdateConfigurationResult.changes != 0;
4056 } finally {
4057 Binder.restoreCallingIdentity(origId);
4058 }
4059 }
4060 }
4061
4062 @Override
4063 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4064 CharSequence message) {
4065 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004066 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4068 }
4069 final long callingId = Binder.clearCallingIdentity();
4070 try {
4071 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004072 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 }
4074 } finally {
4075 Binder.restoreCallingIdentity(callingId);
4076 }
4077 }
4078
4079 @Override
4080 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004081 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 "cancelTaskWindowTransition()");
4083 final long ident = Binder.clearCallingIdentity();
4084 try {
4085 synchronized (mGlobalLock) {
4086 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4087 MATCH_TASK_IN_STACKS_ONLY);
4088 if (task == null) {
4089 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4090 return;
4091 }
4092 task.cancelWindowTransition();
4093 }
4094 } finally {
4095 Binder.restoreCallingIdentity(ident);
4096 }
4097 }
4098
4099 @Override
4100 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004101 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004102 final long ident = Binder.clearCallingIdentity();
4103 try {
4104 final TaskRecord task;
4105 synchronized (mGlobalLock) {
4106 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4107 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4108 if (task == null) {
4109 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4110 return null;
4111 }
4112 }
4113 // Don't call this while holding the lock as this operation might hit the disk.
4114 return task.getSnapshot(reducedResolution);
4115 } finally {
4116 Binder.restoreCallingIdentity(ident);
4117 }
4118 }
4119
4120 @Override
4121 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4122 synchronized (mGlobalLock) {
4123 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4124 if (r == null) {
4125 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4126 + token);
4127 return;
4128 }
4129 final long origId = Binder.clearCallingIdentity();
4130 try {
4131 r.setDisablePreviewScreenshots(disable);
4132 } finally {
4133 Binder.restoreCallingIdentity(origId);
4134 }
4135 }
4136 }
4137
4138 /** Return the user id of the last resumed activity. */
4139 @Override
4140 public @UserIdInt
4141 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4144 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004145 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004146 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004148 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 }
4150 }
4151
4152 @Override
4153 public void updateLockTaskFeatures(int userId, int flags) {
4154 final int callingUid = Binder.getCallingUid();
4155 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 "updateLockTaskFeatures()");
4158 }
4159 synchronized (mGlobalLock) {
4160 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4161 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004162 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 }
4164 }
4165
4166 @Override
4167 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4168 synchronized (mGlobalLock) {
4169 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4170 if (r == null) {
4171 return;
4172 }
4173 final long origId = Binder.clearCallingIdentity();
4174 try {
4175 r.setShowWhenLocked(showWhenLocked);
4176 } finally {
4177 Binder.restoreCallingIdentity(origId);
4178 }
4179 }
4180 }
4181
4182 @Override
4183 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4184 synchronized (mGlobalLock) {
4185 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4186 if (r == null) {
4187 return;
4188 }
4189 final long origId = Binder.clearCallingIdentity();
4190 try {
4191 r.setTurnScreenOn(turnScreenOn);
4192 } finally {
4193 Binder.restoreCallingIdentity(origId);
4194 }
4195 }
4196 }
4197
4198 @Override
4199 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004200 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 "registerRemoteAnimations");
4202 definition.setCallingPid(Binder.getCallingPid());
4203 synchronized (mGlobalLock) {
4204 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4205 if (r == null) {
4206 return;
4207 }
4208 final long origId = Binder.clearCallingIdentity();
4209 try {
4210 r.registerRemoteAnimations(definition);
4211 } finally {
4212 Binder.restoreCallingIdentity(origId);
4213 }
4214 }
4215 }
4216
4217 @Override
4218 public void registerRemoteAnimationForNextActivityStart(String packageName,
4219 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004220 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 "registerRemoteAnimationForNextActivityStart");
4222 adapter.setCallingPid(Binder.getCallingPid());
4223 synchronized (mGlobalLock) {
4224 final long origId = Binder.clearCallingIdentity();
4225 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004226 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004227 packageName, adapter);
4228 } finally {
4229 Binder.restoreCallingIdentity(origId);
4230 }
4231 }
4232 }
4233
4234 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4235 @Override
4236 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4237 synchronized (mGlobalLock) {
4238 final long origId = Binder.clearCallingIdentity();
4239 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004240 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 } finally {
4242 Binder.restoreCallingIdentity(origId);
4243 }
4244 }
4245 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004246
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004247 @Override
4248 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004249 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004250 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004251 final int pid = Binder.getCallingPid();
4252 final WindowProcessController wpc = mPidMap.get(pid);
4253 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004254 }
4255 }
4256
4257 @Override
4258 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004259 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004260 != PERMISSION_GRANTED) {
4261 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4262 + Binder.getCallingPid()
4263 + ", uid=" + Binder.getCallingUid()
4264 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4265 Slog.w(TAG, msg);
4266 throw new SecurityException(msg);
4267 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004268 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004269 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004270 final int pid = Binder.getCallingPid();
4271 final WindowProcessController proc = mPidMap.get(pid);
4272 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004273 }
4274 }
4275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 @Override
4277 public void stopAppSwitches() {
4278 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4279 synchronized (mGlobalLock) {
4280 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4281 mDidAppSwitch = false;
4282 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4283 }
4284 }
4285
4286 @Override
4287 public void resumeAppSwitches() {
4288 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4289 synchronized (mGlobalLock) {
4290 // Note that we don't execute any pending app switches... we will
4291 // let those wait until either the timeout, or the next start
4292 // activity request.
4293 mAppSwitchesAllowedTime = 0;
4294 }
4295 }
4296
4297 void onStartActivitySetDidAppSwitch() {
4298 if (mDidAppSwitch) {
4299 // This is the second allowed switch since we stopped switches, so now just generally
4300 // allow switches. Use case:
4301 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4302 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4303 // anyone to switch again).
4304 mAppSwitchesAllowedTime = 0;
4305 } else {
4306 mDidAppSwitch = true;
4307 }
4308 }
4309
4310 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004311 boolean shouldDisableNonVrUiLocked() {
4312 return mVrController.shouldDisableNonVrUiLocked();
4313 }
4314
Wale Ogunwale53783742018-09-16 10:21:51 -07004315 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004316 // VR apps are expected to run in a main display. If an app is turning on VR for
4317 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4318 // fullscreen stack before enabling VR Mode.
4319 // TODO: The goal of this code is to keep the VR app on the main display. When the
4320 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4321 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4322 // option would be a better choice here.
4323 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4324 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4325 + " to main stack for VR");
4326 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4327 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4328 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4329 }
4330 mH.post(() -> {
4331 if (!mVrController.onVrModeChanged(r)) {
4332 return;
4333 }
4334 synchronized (mGlobalLock) {
4335 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4336 mWindowManager.disableNonVrUi(disableNonVrUi);
4337 if (disableNonVrUi) {
4338 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4339 // then remove the pinned stack.
4340 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4341 }
4342 }
4343 });
4344 }
4345
Wale Ogunwale53783742018-09-16 10:21:51 -07004346 @Override
4347 public int getPackageScreenCompatMode(String packageName) {
4348 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4349 synchronized (mGlobalLock) {
4350 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4351 }
4352 }
4353
4354 @Override
4355 public void setPackageScreenCompatMode(String packageName, int mode) {
4356 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4357 "setPackageScreenCompatMode");
4358 synchronized (mGlobalLock) {
4359 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4360 }
4361 }
4362
4363 @Override
4364 public boolean getPackageAskScreenCompat(String packageName) {
4365 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4366 synchronized (mGlobalLock) {
4367 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4368 }
4369 }
4370
4371 @Override
4372 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4373 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4374 "setPackageAskScreenCompat");
4375 synchronized (mGlobalLock) {
4376 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4377 }
4378 }
4379
Wale Ogunwale64258362018-10-16 15:13:37 -07004380 public static String relaunchReasonToString(int relaunchReason) {
4381 switch (relaunchReason) {
4382 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4383 return "window_resize";
4384 case RELAUNCH_REASON_FREE_RESIZE:
4385 return "free_resize";
4386 default:
4387 return null;
4388 }
4389 }
4390
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004391 ActivityStack getTopDisplayFocusedStack() {
4392 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 }
4394
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004395 /** Pokes the task persister. */
4396 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4397 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4398 }
4399
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004400 boolean isKeyguardLocked() {
4401 return mKeyguardController.isKeyguardLocked();
4402 }
4403
Wale Ogunwale31913b52018-10-13 08:29:31 -07004404 void dumpLastANRLocked(PrintWriter pw) {
4405 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4406 if (mLastANRState == null) {
4407 pw.println(" <no ANR has occurred since boot>");
4408 } else {
4409 pw.println(mLastANRState);
4410 }
4411 }
4412
4413 void dumpLastANRTracesLocked(PrintWriter pw) {
4414 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4415
4416 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4417 if (ArrayUtils.isEmpty(files)) {
4418 pw.println(" <no ANR has occurred since boot>");
4419 return;
4420 }
4421 // Find the latest file.
4422 File latest = null;
4423 for (File f : files) {
4424 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4425 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004426 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004427 }
4428 pw.print("File: ");
4429 pw.print(latest.getName());
4430 pw.println();
4431 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4432 String line;
4433 while ((line = in.readLine()) != null) {
4434 pw.println(line);
4435 }
4436 } catch (IOException e) {
4437 pw.print("Unable to read: ");
4438 pw.print(e);
4439 pw.println();
4440 }
4441 }
4442
4443 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4444 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4445 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4446 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4447 }
4448
4449 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4450 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4451 pw.println(header);
4452
4453 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4454 dumpPackage);
4455 boolean needSep = printedAnything;
4456
4457 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4458 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4459 " ResumedActivity: ");
4460 if (printed) {
4461 printedAnything = true;
4462 needSep = false;
4463 }
4464
4465 if (dumpPackage == null) {
4466 if (needSep) {
4467 pw.println();
4468 }
4469 printedAnything = true;
4470 mStackSupervisor.dump(pw, " ");
4471 }
4472
4473 if (!printedAnything) {
4474 pw.println(" (nothing)");
4475 }
4476 }
4477
4478 void dumpActivityContainersLocked(PrintWriter pw) {
4479 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4480 mStackSupervisor.dumpChildrenNames(pw, " ");
4481 pw.println(" ");
4482 }
4483
4484 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4485 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4486 getActivityStartController().dump(pw, "", dumpPackage);
4487 }
4488
4489 /**
4490 * There are three things that cmd can be:
4491 * - a flattened component name that matches an existing activity
4492 * - the cmd arg isn't the flattened component name of an existing activity:
4493 * dump all activity whose component contains the cmd as a substring
4494 * - A hex number of the ActivityRecord object instance.
4495 *
4496 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4497 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4498 */
4499 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4500 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4501 ArrayList<ActivityRecord> activities;
4502
4503 synchronized (mGlobalLock) {
4504 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4505 dumpFocusedStackOnly);
4506 }
4507
4508 if (activities.size() <= 0) {
4509 return false;
4510 }
4511
4512 String[] newArgs = new String[args.length - opti];
4513 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4514
4515 TaskRecord lastTask = null;
4516 boolean needSep = false;
4517 for (int i = activities.size() - 1; i >= 0; i--) {
4518 ActivityRecord r = activities.get(i);
4519 if (needSep) {
4520 pw.println();
4521 }
4522 needSep = true;
4523 synchronized (mGlobalLock) {
4524 final TaskRecord task = r.getTask();
4525 if (lastTask != task) {
4526 lastTask = task;
4527 pw.print("TASK "); pw.print(lastTask.affinity);
4528 pw.print(" id="); pw.print(lastTask.taskId);
4529 pw.print(" userId="); pw.println(lastTask.userId);
4530 if (dumpAll) {
4531 lastTask.dump(pw, " ");
4532 }
4533 }
4534 }
4535 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4536 }
4537 return true;
4538 }
4539
4540 /**
4541 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4542 * there is a thread associated with the activity.
4543 */
4544 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4545 final ActivityRecord r, String[] args, boolean dumpAll) {
4546 String innerPrefix = prefix + " ";
4547 synchronized (mGlobalLock) {
4548 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4549 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4550 pw.print(" pid=");
4551 if (r.hasProcess()) pw.println(r.app.getPid());
4552 else pw.println("(not running)");
4553 if (dumpAll) {
4554 r.dump(pw, innerPrefix);
4555 }
4556 }
4557 if (r.attachedToProcess()) {
4558 // flush anything that is already in the PrintWriter since the thread is going
4559 // to write to the file descriptor directly
4560 pw.flush();
4561 try {
4562 TransferPipe tp = new TransferPipe();
4563 try {
4564 r.app.getThread().dumpActivity(tp.getWriteFd(),
4565 r.appToken, innerPrefix, args);
4566 tp.go(fd);
4567 } finally {
4568 tp.kill();
4569 }
4570 } catch (IOException e) {
4571 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4572 } catch (RemoteException e) {
4573 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4574 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004575 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004576 }
4577
Wale Ogunwalef6733932018-06-27 05:14:34 -07004578 void writeSleepStateToProto(ProtoOutputStream proto) {
4579 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4580 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4581 st.toString());
4582 }
4583
4584 if (mRunningVoice != null) {
4585 final long vrToken = proto.start(
4586 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4587 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4588 mRunningVoice.toString());
4589 mVoiceWakeLock.writeToProto(
4590 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4591 proto.end(vrToken);
4592 }
4593
4594 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4595 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4596 mShuttingDown);
4597 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004598 }
4599
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004600 int getCurrentUserId() {
4601 return mAmInternal.getCurrentUserId();
4602 }
4603
4604 private void enforceNotIsolatedCaller(String caller) {
4605 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4606 throw new SecurityException("Isolated process not allowed to call " + caller);
4607 }
4608 }
4609
Wale Ogunwalef6733932018-06-27 05:14:34 -07004610 public Configuration getConfiguration() {
4611 Configuration ci;
4612 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004613 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004614 ci.userSetLocale = false;
4615 }
4616 return ci;
4617 }
4618
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004619 /**
4620 * Current global configuration information. Contains general settings for the entire system,
4621 * also corresponds to the merged configuration of the default display.
4622 */
4623 Configuration getGlobalConfiguration() {
4624 return mStackSupervisor.getConfiguration();
4625 }
4626
4627 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4628 boolean initLocale) {
4629 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4630 }
4631
4632 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4633 boolean initLocale, boolean deferResume) {
4634 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4635 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4636 UserHandle.USER_NULL, deferResume);
4637 }
4638
Wale Ogunwale59507092018-10-29 09:00:30 -07004639 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 final long origId = Binder.clearCallingIdentity();
4641 try {
4642 synchronized (mGlobalLock) {
4643 updateConfigurationLocked(values, null, false, true, userId,
4644 false /* deferResume */);
4645 }
4646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004651 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4652 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4653 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4654 deferResume, null /* result */);
4655 }
4656
4657 /**
4658 * Do either or both things: (1) change the current configuration, and (2)
4659 * make sure the given activity is running with the (now) current
4660 * configuration. Returns true if the activity has been left running, or
4661 * false if <var>starting</var> is being destroyed to match the new
4662 * configuration.
4663 *
4664 * @param userId is only used when persistent parameter is set to true to persist configuration
4665 * for that particular user
4666 */
4667 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4668 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4669 ActivityTaskManagerService.UpdateConfigurationResult result) {
4670 int changes = 0;
4671 boolean kept = true;
4672
4673 if (mWindowManager != null) {
4674 mWindowManager.deferSurfaceLayout();
4675 }
4676 try {
4677 if (values != null) {
4678 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4679 deferResume);
4680 }
4681
4682 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4683 } finally {
4684 if (mWindowManager != null) {
4685 mWindowManager.continueSurfaceLayout();
4686 }
4687 }
4688
4689 if (result != null) {
4690 result.changes = changes;
4691 result.activityRelaunched = !kept;
4692 }
4693 return kept;
4694 }
4695
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 /** Update default (global) configuration and notify listeners about changes. */
4697 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4698 boolean persistent, int userId, boolean deferResume) {
4699 mTempConfig.setTo(getGlobalConfiguration());
4700 final int changes = mTempConfig.updateFrom(values);
4701 if (changes == 0) {
4702 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4703 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4704 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4705 // (even if there are no actual changes) to unfreeze the window.
4706 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4707 return 0;
4708 }
4709
4710 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4711 "Updating global configuration to: " + values);
4712
4713 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4714 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4715 values.colorMode,
4716 values.densityDpi,
4717 values.fontScale,
4718 values.hardKeyboardHidden,
4719 values.keyboard,
4720 values.keyboardHidden,
4721 values.mcc,
4722 values.mnc,
4723 values.navigation,
4724 values.navigationHidden,
4725 values.orientation,
4726 values.screenHeightDp,
4727 values.screenLayout,
4728 values.screenWidthDp,
4729 values.smallestScreenWidthDp,
4730 values.touchscreen,
4731 values.uiMode);
4732
4733
4734 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4735 final LocaleList locales = values.getLocales();
4736 int bestLocaleIndex = 0;
4737 if (locales.size() > 1) {
4738 if (mSupportedSystemLocales == null) {
4739 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4740 }
4741 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4742 }
4743 SystemProperties.set("persist.sys.locale",
4744 locales.get(bestLocaleIndex).toLanguageTag());
4745 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004746
4747 final Message m = PooledLambda.obtainMessage(
4748 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4749 locales.get(bestLocaleIndex));
4750 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004751 }
4752
Yunfan Chen75157d72018-07-27 14:47:21 +09004753 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004754
4755 // Update stored global config and notify everyone about the change.
4756 mStackSupervisor.onConfigurationChanged(mTempConfig);
4757
4758 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4759 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004760 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004761
4762 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004763 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004764
4765 AttributeCache ac = AttributeCache.instance();
4766 if (ac != null) {
4767 ac.updateConfiguration(mTempConfig);
4768 }
4769
4770 // Make sure all resources in our process are updated right now, so that anyone who is going
4771 // to retrieve resource values after we return will be sure to get the new ones. This is
4772 // especially important during boot, where the first config change needs to guarantee all
4773 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004774 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004775
4776 // We need another copy of global config because we're scheduling some calls instead of
4777 // running them in place. We need to be sure that object we send will be handled unchanged.
4778 final Configuration configCopy = new Configuration(mTempConfig);
4779 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004780 final Message msg = PooledLambda.obtainMessage(
4781 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4782 this, userId, configCopy);
4783 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 }
4785
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004786 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004787 final int pid = mPidMap.keyAt(i);
4788 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004789 if (DEBUG_CONFIGURATION) {
4790 Slog.v(TAG_CONFIGURATION, "Update process config of "
4791 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004792 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004793 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004794 }
4795
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004796 final Message msg = PooledLambda.obtainMessage(
4797 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4798 mAmInternal, changes, initLocale);
4799 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004800
4801 // Override configuration of the default display duplicates global config, so we need to
4802 // update it also. This will also notify WindowManager about changes.
4803 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4804 DEFAULT_DISPLAY);
4805
4806 return changes;
4807 }
4808
4809 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4810 boolean deferResume, int displayId) {
4811 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4812 displayId, null /* result */);
4813 }
4814
4815 /**
4816 * Updates override configuration specific for the selected display. If no config is provided,
4817 * new one will be computed in WM based on current display info.
4818 */
4819 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4820 ActivityRecord starting, boolean deferResume, int displayId,
4821 ActivityTaskManagerService.UpdateConfigurationResult result) {
4822 int changes = 0;
4823 boolean kept = true;
4824
4825 if (mWindowManager != null) {
4826 mWindowManager.deferSurfaceLayout();
4827 }
4828 try {
4829 if (values != null) {
4830 if (displayId == DEFAULT_DISPLAY) {
4831 // Override configuration of the default display duplicates global config, so
4832 // we're calling global config update instead for default display. It will also
4833 // apply the correct override config.
4834 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4835 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4836 } else {
4837 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4838 }
4839 }
4840
4841 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4842 } finally {
4843 if (mWindowManager != null) {
4844 mWindowManager.continueSurfaceLayout();
4845 }
4846 }
4847
4848 if (result != null) {
4849 result.changes = changes;
4850 result.activityRelaunched = !kept;
4851 }
4852 return kept;
4853 }
4854
4855 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4856 int displayId) {
4857 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4858 final int changes = mTempConfig.updateFrom(values);
4859 if (changes != 0) {
4860 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4861 + mTempConfig + " for displayId=" + displayId);
4862 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4863
4864 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4865 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004866 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004867
Wale Ogunwale5c918702018-10-18 11:06:33 -07004868 // Post message to start process to avoid possible deadlock of calling into AMS with
4869 // the ATMS lock held.
4870 final Message msg = PooledLambda.obtainMessage(
4871 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4872 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4873 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004874 }
4875 }
4876
4877 // Update the configuration with WM first and check if any of the stacks need to be resized
4878 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4879 // necessary. This way we don't need to relaunch again afterwards in
4880 // ensureActivityConfiguration().
4881 if (mWindowManager != null) {
4882 final int[] resizedStacks =
4883 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4884 if (resizedStacks != null) {
4885 for (int stackId : resizedStacks) {
4886 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4887 }
4888 }
4889 }
4890
4891 return changes;
4892 }
4893
Wale Ogunwalef6733932018-06-27 05:14:34 -07004894 private void updateEventDispatchingLocked(boolean booted) {
4895 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4896 }
4897
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004898 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4899 final ContentResolver resolver = mContext.getContentResolver();
4900 Settings.System.putConfigurationForUser(resolver, config, userId);
4901 }
4902
4903 private void sendLocaleToMountDaemonMsg(Locale l) {
4904 try {
4905 IBinder service = ServiceManager.getService("mount");
4906 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4907 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
4908 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
4909 } catch (RemoteException e) {
4910 Log.e(TAG, "Error storing locale for decryption UI", e);
4911 }
4912 }
4913
4914 boolean isActivityStartsLoggingEnabled() {
4915 return mAmInternal.isActivityStartsLoggingEnabled();
4916 }
4917
Wale Ogunwalef6733932018-06-27 05:14:34 -07004918 void enableScreenAfterBoot(boolean booted) {
4919 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4920 SystemClock.uptimeMillis());
4921 mWindowManager.enableScreenAfterBoot();
4922
4923 synchronized (mGlobalLock) {
4924 updateEventDispatchingLocked(booted);
4925 }
4926 }
4927
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004928 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
4929 if (r == null || !r.hasProcess()) {
4930 return KEY_DISPATCHING_TIMEOUT_MS;
4931 }
4932 return getInputDispatchingTimeoutLocked(r.app);
4933 }
4934
4935 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07004936 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004937 }
4938
Wale Ogunwalef6733932018-06-27 05:14:34 -07004939 /**
4940 * Decide based on the configuration whether we should show the ANR,
4941 * crash, etc dialogs. The idea is that if there is no affordance to
4942 * press the on-screen buttons, or the user experience would be more
4943 * greatly impacted than the crash itself, we shouldn't show the dialog.
4944 *
4945 * A thought: SystemUI might also want to get told about this, the Power
4946 * dialog / global actions also might want different behaviors.
4947 */
4948 private void updateShouldShowDialogsLocked(Configuration config) {
4949 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4950 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4951 && config.navigation == Configuration.NAVIGATION_NONAV);
4952 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4953 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4954 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4955 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4956 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4957 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4958 HIDE_ERROR_DIALOGS, 0) != 0;
4959 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4960 }
4961
4962 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4963 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4964 FONT_SCALE, 1.0f, userId);
4965
4966 synchronized (this) {
4967 if (getGlobalConfiguration().fontScale == scaleFactor) {
4968 return;
4969 }
4970
4971 final Configuration configuration
4972 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4973 configuration.fontScale = scaleFactor;
4974 updatePersistentConfiguration(configuration, userId);
4975 }
4976 }
4977
4978 // Actually is sleeping or shutting down or whatever else in the future
4979 // is an inactive state.
4980 boolean isSleepingOrShuttingDownLocked() {
4981 return isSleepingLocked() || mShuttingDown;
4982 }
4983
4984 boolean isSleepingLocked() {
4985 return mSleeping;
4986 }
4987
Riddle Hsu16567132018-08-16 21:37:47 +08004988 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07004989 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4990 final TaskRecord task = r.getTask();
4991 if (task.isActivityTypeStandard()) {
4992 if (mCurAppTimeTracker != r.appTimeTracker) {
4993 // We are switching app tracking. Complete the current one.
4994 if (mCurAppTimeTracker != null) {
4995 mCurAppTimeTracker.stop();
4996 mH.obtainMessage(
4997 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4998 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4999 mCurAppTimeTracker = null;
5000 }
5001 if (r.appTimeTracker != null) {
5002 mCurAppTimeTracker = r.appTimeTracker;
5003 startTimeTrackingFocusedActivityLocked();
5004 }
5005 } else {
5006 startTimeTrackingFocusedActivityLocked();
5007 }
5008 } else {
5009 r.appTimeTracker = null;
5010 }
5011 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5012 // TODO: Probably not, because we don't want to resume voice on switching
5013 // back to this activity
5014 if (task.voiceInteractor != null) {
5015 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5016 } else {
5017 finishRunningVoiceLocked();
5018
5019 if (mLastResumedActivity != null) {
5020 final IVoiceInteractionSession session;
5021
5022 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5023 if (lastResumedActivityTask != null
5024 && lastResumedActivityTask.voiceSession != null) {
5025 session = lastResumedActivityTask.voiceSession;
5026 } else {
5027 session = mLastResumedActivity.voiceSession;
5028 }
5029
5030 if (session != null) {
5031 // We had been in a voice interaction session, but now focused has
5032 // move to something different. Just finish the session, we can't
5033 // return to it and retain the proper state and synchronization with
5034 // the voice interaction service.
5035 finishVoiceTask(session);
5036 }
5037 }
5038 }
5039
5040 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5041 mAmInternal.sendForegroundProfileChanged(r.userId);
5042 }
5043 updateResumedAppTrace(r);
5044 mLastResumedActivity = r;
5045
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005046 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005047
5048 applyUpdateLockStateLocked(r);
5049 applyUpdateVrModeLocked(r);
5050
5051 EventLogTags.writeAmSetResumedActivity(
5052 r == null ? -1 : r.userId,
5053 r == null ? "NULL" : r.shortComponentName,
5054 reason);
5055 }
5056
5057 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5058 synchronized (mGlobalLock) {
5059 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5060 updateSleepIfNeededLocked();
5061 return token;
5062 }
5063 }
5064
5065 void updateSleepIfNeededLocked() {
5066 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5067 final boolean wasSleeping = mSleeping;
5068 boolean updateOomAdj = false;
5069
5070 if (!shouldSleep) {
5071 // If wasSleeping is true, we need to wake up activity manager state from when
5072 // we started sleeping. In either case, we need to apply the sleep tokens, which
5073 // will wake up stacks or put them to sleep as appropriate.
5074 if (wasSleeping) {
5075 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005076 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5077 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 startTimeTrackingFocusedActivityLocked();
5079 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5080 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5081 }
5082 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5083 if (wasSleeping) {
5084 updateOomAdj = true;
5085 }
5086 } else if (!mSleeping && shouldSleep) {
5087 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005088 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5089 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005090 if (mCurAppTimeTracker != null) {
5091 mCurAppTimeTracker.stop();
5092 }
5093 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5094 mStackSupervisor.goingToSleepLocked();
5095 updateResumedAppTrace(null /* resumed */);
5096 updateOomAdj = true;
5097 }
5098 if (updateOomAdj) {
5099 mH.post(mAmInternal::updateOomAdj);
5100 }
5101 }
5102
5103 void updateOomAdj() {
5104 mH.post(mAmInternal::updateOomAdj);
5105 }
5106
Wale Ogunwale53783742018-09-16 10:21:51 -07005107 void updateCpuStats() {
5108 mH.post(mAmInternal::updateCpuStats);
5109 }
5110
5111 void updateUsageStats(ActivityRecord component, boolean resumed) {
5112 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5113 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5114 mH.sendMessage(m);
5115 }
5116
5117 void setBooting(boolean booting) {
5118 mAmInternal.setBooting(booting);
5119 }
5120
5121 boolean isBooting() {
5122 return mAmInternal.isBooting();
5123 }
5124
5125 void setBooted(boolean booted) {
5126 mAmInternal.setBooted(booted);
5127 }
5128
5129 boolean isBooted() {
5130 return mAmInternal.isBooted();
5131 }
5132
5133 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5134 mH.post(() -> {
5135 if (finishBooting) {
5136 mAmInternal.finishBooting();
5137 }
5138 if (enableScreen) {
5139 mInternal.enableScreenAfterBoot(isBooted());
5140 }
5141 });
5142 }
5143
5144 void setHeavyWeightProcess(ActivityRecord root) {
5145 mHeavyWeightProcess = root.app;
5146 final Message m = PooledLambda.obtainMessage(
5147 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5148 root.app, root.intent, root.userId);
5149 mH.sendMessage(m);
5150 }
5151
5152 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5153 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5154 return;
5155 }
5156
5157 mHeavyWeightProcess = null;
5158 final Message m = PooledLambda.obtainMessage(
5159 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5160 proc.mUserId);
5161 mH.sendMessage(m);
5162 }
5163
5164 private void cancelHeavyWeightProcessNotification(int userId) {
5165 final INotificationManager inm = NotificationManager.getService();
5166 if (inm == null) {
5167 return;
5168 }
5169 try {
5170 inm.cancelNotificationWithTag("android", null,
5171 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5172 } catch (RuntimeException e) {
5173 Slog.w(TAG, "Error canceling notification for service", e);
5174 } catch (RemoteException e) {
5175 }
5176
5177 }
5178
5179 private void postHeavyWeightProcessNotification(
5180 WindowProcessController proc, Intent intent, int userId) {
5181 if (proc == null) {
5182 return;
5183 }
5184
5185 final INotificationManager inm = NotificationManager.getService();
5186 if (inm == null) {
5187 return;
5188 }
5189
5190 try {
5191 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5192 String text = mContext.getString(R.string.heavy_weight_notification,
5193 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5194 Notification notification =
5195 new Notification.Builder(context,
5196 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5197 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5198 .setWhen(0)
5199 .setOngoing(true)
5200 .setTicker(text)
5201 .setColor(mContext.getColor(
5202 com.android.internal.R.color.system_notification_accent_color))
5203 .setContentTitle(text)
5204 .setContentText(
5205 mContext.getText(R.string.heavy_weight_notification_detail))
5206 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5207 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5208 new UserHandle(userId)))
5209 .build();
5210 try {
5211 inm.enqueueNotificationWithTag("android", "android", null,
5212 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5213 } catch (RuntimeException e) {
5214 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5215 } catch (RemoteException e) {
5216 }
5217 } catch (PackageManager.NameNotFoundException e) {
5218 Slog.w(TAG, "Unable to create context for heavy notification", e);
5219 }
5220
5221 }
5222
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005223 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5224 IBinder token, String resultWho, int requestCode, Intent[] intents,
5225 String[] resolvedTypes, int flags, Bundle bOptions) {
5226
5227 ActivityRecord activity = null;
5228 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5229 activity = ActivityRecord.isInStackLocked(token);
5230 if (activity == null) {
5231 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5232 return null;
5233 }
5234 if (activity.finishing) {
5235 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5236 return null;
5237 }
5238 }
5239
5240 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5241 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5242 bOptions);
5243 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5244 if (noCreate) {
5245 return rec;
5246 }
5247 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5248 if (activity.pendingResults == null) {
5249 activity.pendingResults = new HashSet<>();
5250 }
5251 activity.pendingResults.add(rec.ref);
5252 }
5253 return rec;
5254 }
5255
Andrii Kulian52d255c2018-07-13 11:32:19 -07005256 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005258 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005259 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5260 mCurAppTimeTracker.start(resumedActivity.packageName);
5261 }
5262 }
5263
5264 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5265 if (mTracedResumedActivity != null) {
5266 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5267 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5268 }
5269 if (resumed != null) {
5270 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5271 constructResumedTraceName(resumed.packageName), 0);
5272 }
5273 mTracedResumedActivity = resumed;
5274 }
5275
5276 private String constructResumedTraceName(String packageName) {
5277 return "focused app: " + packageName;
5278 }
5279
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280 /** Helper method that requests bounds from WM and applies them to stack. */
5281 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
5282 final Rect newStackBounds = new Rect();
5283 final ActivityStack stack = mStackSupervisor.getStack(stackId);
5284
5285 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
5286 if (stack == null) {
5287 final StringWriter writer = new StringWriter();
5288 final PrintWriter printWriter = new PrintWriter(writer);
5289 mStackSupervisor.dumpDisplays(printWriter);
5290 printWriter.flush();
5291
5292 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
5293 }
5294
5295 stack.getBoundsForNewConfiguration(newStackBounds);
5296 mStackSupervisor.resizeStackLocked(
5297 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
5298 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
5299 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
5300 }
5301
5302 /** Applies latest configuration and/or visibility updates if needed. */
5303 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5304 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005305 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306 // mainStack is null during startup.
5307 if (mainStack != null) {
5308 if (changes != 0 && starting == null) {
5309 // If the configuration changed, and the caller is not already
5310 // in the process of starting an activity, then find the top
5311 // activity to check if its configuration needs to change.
5312 starting = mainStack.topRunningActivityLocked();
5313 }
5314
5315 if (starting != null) {
5316 kept = starting.ensureActivityConfiguration(changes,
5317 false /* preserveWindow */);
5318 // And we need to make sure at this point that all other activities
5319 // are made visible with the correct configuration.
5320 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5321 !PRESERVE_WINDOWS);
5322 }
5323 }
5324
5325 return kept;
5326 }
5327
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005328 void scheduleAppGcsLocked() {
5329 mH.post(() -> mAmInternal.scheduleAppGcs());
5330 }
5331
Wale Ogunwale53783742018-09-16 10:21:51 -07005332 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5333 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5334 }
5335
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005336 /**
5337 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5338 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5339 * on demand.
5340 */
5341 IPackageManager getPackageManager() {
5342 return AppGlobals.getPackageManager();
5343 }
5344
5345 PackageManagerInternal getPackageManagerInternalLocked() {
5346 if (mPmInternal == null) {
5347 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5348 }
5349 return mPmInternal;
5350 }
5351
Wale Ogunwale008163e2018-07-23 23:11:08 -07005352 AppWarnings getAppWarningsLocked() {
5353 return mAppWarnings;
5354 }
5355
Wale Ogunwale214f3482018-10-04 11:00:47 -07005356 Intent getHomeIntent() {
5357 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5358 intent.setComponent(mTopComponent);
5359 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5360 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5361 intent.addCategory(Intent.CATEGORY_HOME);
5362 }
5363 return intent;
5364 }
5365
Wale Ogunwale214f3482018-10-04 11:00:47 -07005366 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5367 if (info == null) return null;
5368 ApplicationInfo newInfo = new ApplicationInfo(info);
5369 newInfo.initForUser(userId);
5370 return newInfo;
5371 }
5372
Wale Ogunwale9c103022018-10-18 07:44:54 -07005373 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005374 if (uid == SYSTEM_UID) {
5375 // The system gets to run in any process. If there are multiple processes with the same
5376 // uid, just pick the first (this should never happen).
5377 final SparseArray<WindowProcessController> procs =
5378 mProcessNames.getMap().get(processName);
5379 if (procs == null) return null;
5380 final int procCount = procs.size();
5381 for (int i = 0; i < procCount; i++) {
5382 final int procUid = procs.keyAt(i);
5383 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5384 // Don't use an app process or different user process for system component.
5385 continue;
5386 }
5387 return procs.valueAt(i);
5388 }
5389 }
5390
5391 return mProcessNames.get(processName, uid);
5392 }
5393
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005394 WindowProcessController getProcessController(IApplicationThread thread) {
5395 if (thread == null) {
5396 return null;
5397 }
5398
5399 final IBinder threadBinder = thread.asBinder();
5400 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5401 for (int i = pmap.size()-1; i >= 0; i--) {
5402 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5403 for (int j = procs.size() - 1; j >= 0; j--) {
5404 final WindowProcessController proc = procs.valueAt(j);
5405 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5406 return proc;
5407 }
5408 }
5409 }
5410
5411 return null;
5412 }
5413
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005414 int getUidStateLocked(int uid) {
5415 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5416 }
5417
Wale Ogunwale9de19442018-10-18 19:05:03 -07005418 /**
5419 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5420 * the whitelist
5421 */
5422 String getPendingTempWhitelistTagForUidLocked(int uid) {
5423 return mPendingTempWhitelist.get(uid);
5424 }
5425
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005426 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5427 if (true || Build.IS_USER) {
5428 return;
5429 }
5430
5431 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5432 StrictMode.allowThreadDiskWrites();
5433 try {
5434 File tracesDir = new File("/data/anr");
5435 File tracesFile = null;
5436 try {
5437 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5438
5439 StringBuilder sb = new StringBuilder();
5440 Time tobj = new Time();
5441 tobj.set(System.currentTimeMillis());
5442 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5443 sb.append(": ");
5444 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5445 sb.append(" since ");
5446 sb.append(msg);
5447 FileOutputStream fos = new FileOutputStream(tracesFile);
5448 fos.write(sb.toString().getBytes());
5449 if (app == null) {
5450 fos.write("\n*** No application process!".getBytes());
5451 }
5452 fos.close();
5453 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5454 } catch (IOException e) {
5455 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5456 return;
5457 }
5458
5459 if (app != null && app.getPid() > 0) {
5460 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5461 firstPids.add(app.getPid());
5462 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5463 }
5464
5465 File lastTracesFile = null;
5466 File curTracesFile = null;
5467 for (int i=9; i>=0; i--) {
5468 String name = String.format(Locale.US, "slow%02d.txt", i);
5469 curTracesFile = new File(tracesDir, name);
5470 if (curTracesFile.exists()) {
5471 if (lastTracesFile != null) {
5472 curTracesFile.renameTo(lastTracesFile);
5473 } else {
5474 curTracesFile.delete();
5475 }
5476 }
5477 lastTracesFile = curTracesFile;
5478 }
5479 tracesFile.renameTo(curTracesFile);
5480 } finally {
5481 StrictMode.setThreadPolicy(oldPolicy);
5482 }
5483 }
5484
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005485 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486 static final int REPORT_TIME_TRACKER_MSG = 1;
Wale Ogunwale98875612018-10-12 07:53:02 -07005487 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5488 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005490 public H(Looper looper) {
5491 super(looper, null, true);
5492 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493
5494 @Override
5495 public void handleMessage(Message msg) {
5496 switch (msg.what) {
5497 case REPORT_TIME_TRACKER_MSG: {
5498 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5499 tracker.deliverResult(mContext);
5500 } break;
5501 }
5502 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005503 }
5504
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005505 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005507
5508 public UiHandler() {
5509 super(com.android.server.UiThread.get().getLooper(), null, true);
5510 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511
5512 @Override
5513 public void handleMessage(Message msg) {
5514 switch (msg.what) {
5515 case DISMISS_DIALOG_UI_MSG: {
5516 final Dialog d = (Dialog) msg.obj;
5517 d.dismiss();
5518 break;
5519 }
5520 }
5521 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005522 }
5523
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005524 final class LocalService extends ActivityTaskManagerInternal {
5525 @Override
5526 public SleepToken acquireSleepToken(String tag, int displayId) {
5527 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005529 }
5530
5531 @Override
5532 public ComponentName getHomeActivityForUser(int userId) {
5533 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005534 ActivityRecord homeActivity =
5535 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005536 return homeActivity == null ? null : homeActivity.realActivity;
5537 }
5538 }
5539
5540 @Override
5541 public void onLocalVoiceInteractionStarted(IBinder activity,
5542 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5543 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005545 }
5546 }
5547
5548 @Override
5549 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5550 synchronized (mGlobalLock) {
5551 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5552 reasons, timestamp);
5553 }
5554 }
5555
5556 @Override
5557 public void notifyAppTransitionFinished() {
5558 synchronized (mGlobalLock) {
5559 mStackSupervisor.notifyAppTransitionDone();
5560 }
5561 }
5562
5563 @Override
5564 public void notifyAppTransitionCancelled() {
5565 synchronized (mGlobalLock) {
5566 mStackSupervisor.notifyAppTransitionDone();
5567 }
5568 }
5569
5570 @Override
5571 public List<IBinder> getTopVisibleActivities() {
5572 synchronized (mGlobalLock) {
5573 return mStackSupervisor.getTopVisibleActivities();
5574 }
5575 }
5576
5577 @Override
5578 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5579 synchronized (mGlobalLock) {
5580 mStackSupervisor.setDockedStackMinimized(minimized);
5581 }
5582 }
5583
5584 @Override
5585 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5586 Bundle bOptions) {
5587 Preconditions.checkNotNull(intents, "intents");
5588 final String[] resolvedTypes = new String[intents.length];
5589
5590 // UID of the package on user userId.
5591 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5592 // packageUid may not be initialized.
5593 int packageUid = 0;
5594 final long ident = Binder.clearCallingIdentity();
5595
5596 try {
5597 for (int i = 0; i < intents.length; i++) {
5598 resolvedTypes[i] =
5599 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5600 }
5601
5602 packageUid = AppGlobals.getPackageManager().getPackageUid(
5603 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5604 } catch (RemoteException e) {
5605 // Shouldn't happen.
5606 } finally {
5607 Binder.restoreCallingIdentity(ident);
5608 }
5609
5610 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005611 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005612 packageUid, packageName,
5613 intents, resolvedTypes, null /* resultTo */,
5614 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005615 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005616 }
5617 }
5618
5619 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005620 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5621 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5622 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5623 synchronized (mGlobalLock) {
5624 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5625 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5626 originatingPendingIntent);
5627 }
5628 }
5629
5630 @Override
5631 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5632 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5633 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5634 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5635 PendingIntentRecord originatingPendingIntent) {
5636 synchronized (mGlobalLock) {
5637 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5638 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5639 requestCode, startFlags, options, userId, inTask, reason,
5640 validateIncomingUser, originatingPendingIntent);
5641 }
5642 }
5643
5644 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005645 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5646 Intent intent, Bundle options, int userId) {
5647 return ActivityTaskManagerService.this.startActivityAsUser(
5648 caller, callerPacakge, intent,
5649 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5650 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5651 false /*validateIncomingUser*/);
5652 }
5653
5654 @Override
lumark588a3e82018-07-20 18:53:54 +08005655 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005656 synchronized (mGlobalLock) {
5657
5658 // We might change the visibilities here, so prepare an empty app transition which
5659 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005660 final ActivityDisplay activityDisplay =
5661 mStackSupervisor.getActivityDisplay(displayId);
5662 if (activityDisplay == null) {
5663 return;
5664 }
5665 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005666 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005667 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005668 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005669 }
5670 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5671
5672 // If there was a transition set already we don't want to interfere with it as we
5673 // might be starting it too early.
5674 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005675 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005676 }
5677 }
5678 if (callback != null) {
5679 callback.run();
5680 }
5681 }
5682
5683 @Override
5684 public void notifyKeyguardTrustedChanged() {
5685 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005686 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005687 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5688 }
5689 }
5690 }
5691
5692 /**
5693 * Called after virtual display Id is updated by
5694 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5695 * {@param vrVr2dDisplayId}.
5696 */
5697 @Override
5698 public void setVr2dDisplayId(int vr2dDisplayId) {
5699 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5700 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005701 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005702 }
5703 }
5704
5705 @Override
5706 public void setFocusedActivity(IBinder token) {
5707 synchronized (mGlobalLock) {
5708 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5709 if (r == null) {
5710 throw new IllegalArgumentException(
5711 "setFocusedActivity: No activity record matching token=" + token);
5712 }
Louis Chang19443452018-10-09 12:10:21 +08005713 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005714 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005715 }
5716 }
5717 }
5718
5719 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005720 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005721 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005722 }
5723
5724 @Override
5725 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005726 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005727 }
5728
5729 @Override
5730 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005731 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005732 }
5733
5734 @Override
5735 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5736 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5737 }
5738
5739 @Override
5740 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005741 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005742 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005743
5744 @Override
5745 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5746 synchronized (mGlobalLock) {
5747 mActiveVoiceInteractionServiceComponent = component;
5748 }
5749 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005750
5751 @Override
5752 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5753 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5754 return;
5755 }
5756 synchronized (mGlobalLock) {
5757 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5758 if (types == null) {
5759 if (uid < 0) {
5760 return;
5761 }
5762 types = new ArrayMap<>();
5763 mAllowAppSwitchUids.put(userId, types);
5764 }
5765 if (uid < 0) {
5766 types.remove(type);
5767 } else {
5768 types.put(type, uid);
5769 }
5770 }
5771 }
5772
5773 @Override
5774 public void onUserStopped(int userId) {
5775 synchronized (mGlobalLock) {
5776 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5777 mAllowAppSwitchUids.remove(userId);
5778 }
5779 }
5780
5781 @Override
5782 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5783 synchronized (mGlobalLock) {
5784 return ActivityTaskManagerService.this.isGetTasksAllowed(
5785 caller, callingPid, callingUid);
5786 }
5787 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005788
5789 @Override
5790 public void onProcessAdded(WindowProcessController proc) {
5791 synchronized (mGlobalLock) {
5792 mProcessNames.put(proc.mName, proc.mUid, proc);
5793 }
5794 }
5795
5796 @Override
5797 public void onProcessRemoved(String name, int uid) {
5798 synchronized (mGlobalLock) {
5799 mProcessNames.remove(name, uid);
5800 }
5801 }
5802
5803 @Override
5804 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5805 synchronized (mGlobalLock) {
5806 if (proc == mHomeProcess) {
5807 mHomeProcess = null;
5808 }
5809 if (proc == mPreviousProcess) {
5810 mPreviousProcess = null;
5811 }
5812 }
5813 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005814
5815 @Override
5816 public int getTopProcessState() {
5817 synchronized (mGlobalLock) {
5818 return mTopProcessState;
5819 }
5820 }
5821
5822 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005823 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5824 synchronized (mGlobalLock) {
5825 return proc == mHeavyWeightProcess;
5826 }
5827 }
5828
5829 @Override
5830 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5831 synchronized (mGlobalLock) {
5832 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5833 }
5834 }
5835
5836 @Override
5837 public void finishHeavyWeightApp() {
5838 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005839 if (mHeavyWeightProcess != null) {
5840 mHeavyWeightProcess.finishActivities();
5841 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005842 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5843 mHeavyWeightProcess);
5844 }
5845 }
5846
5847 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005848 public boolean isSleeping() {
5849 synchronized (mGlobalLock) {
5850 return isSleepingLocked();
5851 }
5852 }
5853
5854 @Override
5855 public boolean isShuttingDown() {
5856 synchronized (mGlobalLock) {
5857 return mShuttingDown;
5858 }
5859 }
5860
5861 @Override
5862 public boolean shuttingDown(boolean booted, int timeout) {
5863 synchronized (mGlobalLock) {
5864 mShuttingDown = true;
5865 mStackSupervisor.prepareForShutdownLocked();
5866 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005867 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005868 return mStackSupervisor.shutdownLocked(timeout);
5869 }
5870 }
5871
5872 @Override
5873 public void enableScreenAfterBoot(boolean booted) {
5874 synchronized (mGlobalLock) {
5875 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5876 SystemClock.uptimeMillis());
5877 mWindowManager.enableScreenAfterBoot();
5878 updateEventDispatchingLocked(booted);
5879 }
5880 }
5881
5882 @Override
5883 public boolean showStrictModeViolationDialog() {
5884 synchronized (mGlobalLock) {
5885 return mShowDialogs && !mSleeping && !mShuttingDown;
5886 }
5887 }
5888
5889 @Override
5890 public void showSystemReadyErrorDialogsIfNeeded() {
5891 synchronized (mGlobalLock) {
5892 try {
5893 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5894 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5895 + " data partition or your device will be unstable.");
5896 mUiHandler.post(() -> {
5897 if (mShowDialogs) {
5898 AlertDialog d = new BaseErrorDialog(mUiContext);
5899 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5900 d.setCancelable(false);
5901 d.setTitle(mUiContext.getText(R.string.android_system_label));
5902 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5903 d.setButton(DialogInterface.BUTTON_POSITIVE,
5904 mUiContext.getText(R.string.ok),
5905 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5906 d.show();
5907 }
5908 });
5909 }
5910 } catch (RemoteException e) {
5911 }
5912
5913 if (!Build.isBuildConsistent()) {
5914 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5915 mUiHandler.post(() -> {
5916 if (mShowDialogs) {
5917 AlertDialog d = new BaseErrorDialog(mUiContext);
5918 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5919 d.setCancelable(false);
5920 d.setTitle(mUiContext.getText(R.string.android_system_label));
5921 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5922 d.setButton(DialogInterface.BUTTON_POSITIVE,
5923 mUiContext.getText(R.string.ok),
5924 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5925 d.show();
5926 }
5927 });
5928 }
5929 }
5930 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005931
5932 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005933 public void onProcessMapped(int pid, WindowProcessController proc) {
5934 synchronized (mGlobalLock) {
5935 mPidMap.put(pid, proc);
5936 }
5937 }
5938
5939 @Override
5940 public void onProcessUnMapped(int pid) {
5941 synchronized (mGlobalLock) {
5942 mPidMap.remove(pid);
5943 }
5944 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07005945
5946 @Override
5947 public void onPackageDataCleared(String name) {
5948 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07005949 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07005950 mAppWarnings.onPackageDataCleared(name);
5951 }
5952 }
5953
5954 @Override
5955 public void onPackageUninstalled(String name) {
5956 synchronized (mGlobalLock) {
5957 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07005958 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07005959 }
5960 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005961
5962 @Override
5963 public void onPackageAdded(String name, boolean replacing) {
5964 synchronized (mGlobalLock) {
5965 mCompatModePackages.handlePackageAddedLocked(name, replacing);
5966 }
5967 }
5968
5969 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07005970 public void onPackageReplaced(ApplicationInfo aInfo) {
5971 synchronized (mGlobalLock) {
5972 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
5973 }
5974 }
5975
5976 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005977 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
5978 synchronized (mGlobalLock) {
5979 return compatibilityInfoForPackageLocked(ai);
5980 }
5981 }
5982
Yunfan Chen75157d72018-07-27 14:47:21 +09005983 /**
5984 * Set the corresponding display information for the process global configuration. To be
5985 * called when we need to show IME on a different display.
5986 *
5987 * @param pid The process id associated with the IME window.
5988 * @param displayId The ID of the display showing the IME.
5989 */
5990 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07005991 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005992 if (pid == MY_PID || pid < 0) {
5993 if (DEBUG_CONFIGURATION) {
5994 Slog.w(TAG,
5995 "Trying to update display configuration for system/invalid process.");
5996 }
5997 return;
5998 }
5999 mH.post(() -> {
6000 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006001 final ActivityDisplay activityDisplay =
6002 mStackSupervisor.getActivityDisplay(displayId);
6003 if (activityDisplay == null) {
6004 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006005 if (DEBUG_CONFIGURATION) {
6006 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006007 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006008 }
6009 return;
6010 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006011 final WindowProcessController process = mPidMap.get(pid);
6012 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006013 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006014 Slog.w(TAG, "Trying to update display configuration for invalid "
6015 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006016 }
6017 return;
6018 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006019 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006020 }
6021 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006022
Yunfan Chen75157d72018-07-27 14:47:21 +09006023 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006024
6025 @Override
6026 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6027 int requestCode, int resultCode, Intent data) {
6028 synchronized (mGlobalLock) {
6029 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6030 if (r != null && r.getStack() != null) {
6031 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6032 resultCode, data);
6033 }
6034 }
6035 }
6036
6037 @Override
6038 public void clearPendingResultForActivity(IBinder activityToken,
6039 WeakReference<PendingIntentRecord> pir) {
6040 synchronized (mGlobalLock) {
6041 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6042 if (r != null && r.pendingResults != null) {
6043 r.pendingResults.remove(pir);
6044 }
6045 }
6046 }
6047
6048 @Override
6049 public IIntentSender getIntentSender(int type, String packageName,
6050 int callingUid, int userId, IBinder token, String resultWho,
6051 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6052 Bundle bOptions) {
6053 synchronized (mGlobalLock) {
6054 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6055 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6056 }
6057 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006058
6059 @Override
6060 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6061 synchronized (mGlobalLock) {
6062 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6063 if (r == null) {
6064 return null;
6065 }
6066 if (r.mServiceConnectionsHolder == null) {
6067 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6068 ActivityTaskManagerService.this, r);
6069 }
6070
6071 return r.mServiceConnectionsHolder;
6072 }
6073 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006074
6075 @Override
6076 public Intent getHomeIntent() {
6077 synchronized (mGlobalLock) {
6078 return ActivityTaskManagerService.this.getHomeIntent();
6079 }
6080 }
6081
6082 @Override
6083 public boolean startHomeActivity(int userId, String reason) {
6084 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006085 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6086 }
6087 }
6088
6089 @Override
6090 public boolean startHomeOnAllDisplays(int userId, String reason) {
6091 synchronized (mGlobalLock) {
6092 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006093 }
6094 }
6095
6096 @Override
6097 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6098 synchronized (mGlobalLock) {
6099 if (mFactoryTest == FACTORY_TEST_OFF) {
6100 return false;
6101 }
6102 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6103 && wpc.mName.equals(mTopComponent.getPackageName())) {
6104 return true;
6105 }
6106 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6107 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6108 }
6109 }
6110
6111 @Override
6112 public void updateTopComponentForFactoryTest() {
6113 synchronized (mGlobalLock) {
6114 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6115 return;
6116 }
6117 final ResolveInfo ri = mContext.getPackageManager()
6118 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6119 final CharSequence errorMsg;
6120 if (ri != null) {
6121 final ActivityInfo ai = ri.activityInfo;
6122 final ApplicationInfo app = ai.applicationInfo;
6123 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6124 mTopAction = Intent.ACTION_FACTORY_TEST;
6125 mTopData = null;
6126 mTopComponent = new ComponentName(app.packageName, ai.name);
6127 errorMsg = null;
6128 } else {
6129 errorMsg = mContext.getResources().getText(
6130 com.android.internal.R.string.factorytest_not_system);
6131 }
6132 } else {
6133 errorMsg = mContext.getResources().getText(
6134 com.android.internal.R.string.factorytest_no_action);
6135 }
6136 if (errorMsg == null) {
6137 return;
6138 }
6139
6140 mTopAction = null;
6141 mTopData = null;
6142 mTopComponent = null;
6143 mUiHandler.post(() -> {
6144 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6145 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006146 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006147 });
6148 }
6149 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006150
6151 @Override
6152 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6153 Runnable finishInstrumentationCallback) {
6154 synchronized (mGlobalLock) {
6155 // Remove this application's activities from active lists.
6156 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6157
6158 wpc.clearRecentTasks();
6159 wpc.clearActivities();
6160
6161 if (wpc.isInstrumenting()) {
6162 finishInstrumentationCallback.run();
6163 }
6164
6165 mWindowManager.deferSurfaceLayout();
6166 try {
6167 if (!restarting && hasVisibleActivities
6168 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6169 // If there was nothing to resume, and we are not already restarting this
6170 // process, but there is a visible activity that is hosted by the process...
6171 // then make sure all visible activities are running, taking care of
6172 // restarting this process.
6173 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6174 }
6175 } finally {
6176 mWindowManager.continueSurfaceLayout();
6177 }
6178 }
6179 }
6180
6181 @Override
6182 public void closeSystemDialogs(String reason) {
6183 enforceNotIsolatedCaller("closeSystemDialogs");
6184
6185 final int pid = Binder.getCallingPid();
6186 final int uid = Binder.getCallingUid();
6187 final long origId = Binder.clearCallingIdentity();
6188 try {
6189 synchronized (mGlobalLock) {
6190 // Only allow this from foreground processes, so that background
6191 // applications can't abuse it to prevent system UI from being shown.
6192 if (uid >= FIRST_APPLICATION_UID) {
6193 final WindowProcessController proc = mPidMap.get(pid);
6194 if (!proc.isPerceptible()) {
6195 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6196 + " from background process " + proc);
6197 return;
6198 }
6199 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006200 mWindowManager.closeSystemDialogs(reason);
6201
6202 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006203 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006204 // Call into AM outside the synchronized block.
6205 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006206 } finally {
6207 Binder.restoreCallingIdentity(origId);
6208 }
6209 }
6210
6211 @Override
6212 public void cleanupDisabledPackageComponents(
6213 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6214 synchronized (mGlobalLock) {
6215 // Clean-up disabled activities.
6216 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6217 packageName, disabledClasses, true, false, userId) && booted) {
6218 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6219 mStackSupervisor.scheduleIdleLocked();
6220 }
6221
6222 // Clean-up disabled tasks
6223 getRecentTasks().cleanupDisabledPackageTasksLocked(
6224 packageName, disabledClasses, userId);
6225 }
6226 }
6227
6228 @Override
6229 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6230 int userId) {
6231 synchronized (mGlobalLock) {
6232
6233 boolean didSomething =
6234 getActivityStartController().clearPendingActivityLaunches(packageName);
6235 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6236 null, doit, evenPersistent, userId);
6237 return didSomething;
6238 }
6239 }
6240
6241 @Override
6242 public void resumeTopActivities(boolean scheduleIdle) {
6243 synchronized (mGlobalLock) {
6244 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6245 if (scheduleIdle) {
6246 mStackSupervisor.scheduleIdleLocked();
6247 }
6248 }
6249 }
6250
6251 @Override
6252 public void preBindApplication(WindowProcessController wpc) {
6253 synchronized (mGlobalLock) {
6254 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6255 }
6256 }
6257
6258 @Override
6259 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6260 synchronized (mGlobalLock) {
6261 return mStackSupervisor.attachApplicationLocked(wpc);
6262 }
6263 }
6264
6265 @Override
6266 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6267 try {
6268 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6269 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6270 }
6271 } catch (RemoteException ex) {
6272 throw new SecurityException("Fail to check is caller a privileged app", ex);
6273 }
6274
6275 synchronized (mGlobalLock) {
6276 final long ident = Binder.clearCallingIdentity();
6277 try {
6278 if (mAmInternal.shouldConfirmCredentials(userId)) {
6279 if (mKeyguardController.isKeyguardLocked()) {
6280 // Showing launcher to avoid user entering credential twice.
6281 startHomeActivity(currentUserId, "notifyLockedProfile");
6282 }
6283 mStackSupervisor.lockAllProfileTasks(userId);
6284 }
6285 } finally {
6286 Binder.restoreCallingIdentity(ident);
6287 }
6288 }
6289 }
6290
6291 @Override
6292 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6293 mAmInternal.enforceCallingPermission(
6294 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6295
6296 synchronized (mGlobalLock) {
6297 final long ident = Binder.clearCallingIdentity();
6298 try {
6299 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6300 FLAG_ACTIVITY_TASK_ON_HOME);
6301 ActivityOptions activityOptions = options != null
6302 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
6303 activityOptions.setLaunchTaskId(
6304 mStackSupervisor.getDefaultDisplayHomeActivity().getTask().taskId);
6305 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6306 UserHandle.CURRENT);
6307 } finally {
6308 Binder.restoreCallingIdentity(ident);
6309 }
6310 }
6311 }
6312
6313 @Override
6314 public void writeActivitiesToProto(ProtoOutputStream proto) {
6315 synchronized (mGlobalLock) {
6316 // The output proto of "activity --proto activities"
6317 // is ActivityManagerServiceDumpActivitiesProto
6318 mStackSupervisor.writeToProto(proto,
6319 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6320 }
6321 }
6322
6323 @Override
6324 public void saveANRState(String reason) {
6325 synchronized (mGlobalLock) {
6326 final StringWriter sw = new StringWriter();
6327 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6328 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6329 if (reason != null) {
6330 pw.println(" Reason: " + reason);
6331 }
6332 pw.println();
6333 getActivityStartController().dump(pw, " ", null);
6334 pw.println();
6335 pw.println("-------------------------------------------------------------------------------");
6336 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6337 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6338 "" /* header */);
6339 pw.println();
6340 pw.close();
6341
6342 mLastANRState = sw.toString();
6343 }
6344 }
6345
6346 @Override
6347 public void clearSavedANRState() {
6348 synchronized (mGlobalLock) {
6349 mLastANRState = null;
6350 }
6351 }
6352
6353 @Override
6354 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6355 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6356 synchronized (mGlobalLock) {
6357 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6358 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6359 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6360 dumpLastANRLocked(pw);
6361 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6362 dumpLastANRTracesLocked(pw);
6363 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6364 dumpActivityStarterLocked(pw, dumpPackage);
6365 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6366 dumpActivityContainersLocked(pw);
6367 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6368 if (getRecentTasks() != null) {
6369 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6370 }
6371 }
6372 }
6373 }
6374
6375 @Override
6376 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6377 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6378 int wakefulness) {
6379 synchronized (mGlobalLock) {
6380 if (mHomeProcess != null && (dumpPackage == null
6381 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6382 if (needSep) {
6383 pw.println();
6384 needSep = false;
6385 }
6386 pw.println(" mHomeProcess: " + mHomeProcess);
6387 }
6388 if (mPreviousProcess != null && (dumpPackage == null
6389 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6390 if (needSep) {
6391 pw.println();
6392 needSep = false;
6393 }
6394 pw.println(" mPreviousProcess: " + mPreviousProcess);
6395 }
6396 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6397 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6398 StringBuilder sb = new StringBuilder(128);
6399 sb.append(" mPreviousProcessVisibleTime: ");
6400 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6401 pw.println(sb);
6402 }
6403 if (mHeavyWeightProcess != null && (dumpPackage == null
6404 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6405 if (needSep) {
6406 pw.println();
6407 needSep = false;
6408 }
6409 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6410 }
6411 if (dumpPackage == null) {
6412 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6413 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6414 }
6415 if (dumpAll) {
6416 if (dumpPackage == null) {
6417 pw.println(" mConfigWillChange: "
6418 + getTopDisplayFocusedStack().mConfigWillChange);
6419 }
6420 if (mCompatModePackages.getPackages().size() > 0) {
6421 boolean printed = false;
6422 for (Map.Entry<String, Integer> entry
6423 : mCompatModePackages.getPackages().entrySet()) {
6424 String pkg = entry.getKey();
6425 int mode = entry.getValue();
6426 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6427 continue;
6428 }
6429 if (!printed) {
6430 pw.println(" mScreenCompatPackages:");
6431 printed = true;
6432 }
6433 pw.println(" " + pkg + ": " + mode);
6434 }
6435 }
6436 }
6437
6438 if (dumpPackage == null) {
6439 pw.println(" mWakefulness="
6440 + PowerManagerInternal.wakefulnessToString(wakefulness));
6441 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6442 if (mRunningVoice != null) {
6443 pw.println(" mRunningVoice=" + mRunningVoice);
6444 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6445 }
6446 pw.println(" mSleeping=" + mSleeping);
6447 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6448 pw.println(" mVrController=" + mVrController);
6449 }
6450 if (mCurAppTimeTracker != null) {
6451 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6452 }
6453 if (mAllowAppSwitchUids.size() > 0) {
6454 boolean printed = false;
6455 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6456 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6457 for (int j = 0; j < types.size(); j++) {
6458 if (dumpPackage == null ||
6459 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6460 if (needSep) {
6461 pw.println();
6462 needSep = false;
6463 }
6464 if (!printed) {
6465 pw.println(" mAllowAppSwitchUids:");
6466 printed = true;
6467 }
6468 pw.print(" User ");
6469 pw.print(mAllowAppSwitchUids.keyAt(i));
6470 pw.print(": Type ");
6471 pw.print(types.keyAt(j));
6472 pw.print(" = ");
6473 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6474 pw.println();
6475 }
6476 }
6477 }
6478 }
6479 if (dumpPackage == null) {
6480 if (mController != null) {
6481 pw.println(" mController=" + mController
6482 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6483 }
6484 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6485 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6486 }
6487
6488 return needSep;
6489 }
6490 }
6491
6492 @Override
6493 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6494 synchronized (mGlobalLock) {
6495 if (dumpPackage == null) {
6496 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6497 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6498 writeSleepStateToProto(proto);
6499 if (mController != null) {
6500 final long token = proto.start(CONTROLLER);
6501 proto.write(CONTROLLER, mController.toString());
6502 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6503 proto.end(token);
6504 }
6505 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6506 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6507 }
6508
6509 if (mHomeProcess != null && (dumpPackage == null
6510 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006511 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006512 }
6513
6514 if (mPreviousProcess != null && (dumpPackage == null
6515 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006516 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006517 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6518 }
6519
6520 if (mHeavyWeightProcess != null && (dumpPackage == null
6521 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006522 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006523 }
6524
6525 for (Map.Entry<String, Integer> entry
6526 : mCompatModePackages.getPackages().entrySet()) {
6527 String pkg = entry.getKey();
6528 int mode = entry.getValue();
6529 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6530 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6531 proto.write(PACKAGE, pkg);
6532 proto.write(MODE, mode);
6533 proto.end(compatToken);
6534 }
6535 }
6536
6537 if (mCurAppTimeTracker != null) {
6538 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6539 }
6540
6541 }
6542 }
6543
6544 @Override
6545 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6546 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6547 boolean dumpFocusedStackOnly) {
6548 synchronized (mGlobalLock) {
6549 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6550 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6551 }
6552 }
6553
6554 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006555 public void dumpForOom(PrintWriter pw) {
6556 synchronized (mGlobalLock) {
6557 pw.println(" mHomeProcess: " + mHomeProcess);
6558 pw.println(" mPreviousProcess: " + mPreviousProcess);
6559 if (mHeavyWeightProcess != null) {
6560 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6561 }
6562 }
6563 }
6564
6565 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006566 public boolean canGcNow() {
6567 synchronized (mGlobalLock) {
6568 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6569 }
6570 }
6571
6572 @Override
6573 public WindowProcessController getTopApp() {
6574 synchronized (mGlobalLock) {
6575 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6576 return top != null ? top.app : null;
6577 }
6578 }
6579
6580 @Override
6581 public void rankTaskLayersIfNeeded() {
6582 synchronized (mGlobalLock) {
6583 if (mStackSupervisor != null) {
6584 mStackSupervisor.rankTaskLayersIfNeeded();
6585 }
6586 }
6587 }
6588
6589 @Override
6590 public void scheduleDestroyAllActivities(String reason) {
6591 synchronized (mGlobalLock) {
6592 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6593 }
6594 }
6595
6596 @Override
6597 public void removeUser(int userId) {
6598 synchronized (mGlobalLock) {
6599 mStackSupervisor.removeUserLocked(userId);
6600 }
6601 }
6602
6603 @Override
6604 public boolean switchUser(int userId, UserState userState) {
6605 synchronized (mGlobalLock) {
6606 return mStackSupervisor.switchUserLocked(userId, userState);
6607 }
6608 }
6609
6610 @Override
6611 public void onHandleAppCrash(WindowProcessController wpc) {
6612 synchronized (mGlobalLock) {
6613 mStackSupervisor.handleAppCrashLocked(wpc);
6614 }
6615 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006616
6617 @Override
6618 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6619 synchronized (mGlobalLock) {
6620 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6621 }
6622 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006623
6624 @Override
6625 public void onUidActive(int uid, int procState) {
6626 synchronized (mGlobalLock) {
6627 mActiveUids.put(uid, procState);
6628 }
6629 }
6630
6631 @Override
6632 public void onUidInactive(int uid) {
6633 synchronized (mGlobalLock) {
6634 mActiveUids.remove(uid);
6635 }
6636 }
6637
6638 @Override
6639 public void onActiveUidsCleared() {
6640 synchronized (mGlobalLock) {
6641 mActiveUids.clear();
6642 }
6643 }
6644
6645 @Override
6646 public void onUidProcStateChanged(int uid, int procState) {
6647 synchronized (mGlobalLock) {
6648 if (mActiveUids.get(uid) != null) {
6649 mActiveUids.put(uid, procState);
6650 }
6651 }
6652 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006653
6654 @Override
6655 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6656 synchronized (mGlobalLock) {
6657 mPendingTempWhitelist.put(uid, tag);
6658 }
6659 }
6660
6661 @Override
6662 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6663 synchronized (mGlobalLock) {
6664 mPendingTempWhitelist.remove(uid);
6665 }
6666 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006667
6668 @Override
6669 public boolean handleAppCrashInActivityController(String processName, int pid,
6670 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6671 Runnable killCrashingAppCallback) {
6672 synchronized (mGlobalLock) {
6673 if (mController == null) {
6674 return false;
6675 }
6676
6677 try {
6678 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6679 stackTrace)) {
6680 killCrashingAppCallback.run();
6681 return true;
6682 }
6683 } catch (RemoteException e) {
6684 mController = null;
6685 Watchdog.getInstance().setActivityController(null);
6686 }
6687 return false;
6688 }
6689 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006690
6691 @Override
6692 public void removeRecentTasksByPackageName(String packageName, int userId) {
6693 synchronized (mGlobalLock) {
6694 mRecentTasks.removeTasksByPackageName(packageName, userId);
6695 }
6696 }
6697
6698 @Override
6699 public void cleanupRecentTasksForUser(int userId) {
6700 synchronized (mGlobalLock) {
6701 mRecentTasks.cleanupLocked(userId);
6702 }
6703 }
6704
6705 @Override
6706 public void loadRecentTasksForUser(int userId) {
6707 synchronized (mGlobalLock) {
6708 mRecentTasks.loadUserRecentsLocked(userId);
6709 }
6710 }
6711
6712 @Override
6713 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6714 synchronized (mGlobalLock) {
6715 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6716 }
6717 }
6718
6719 @Override
6720 public void flushRecentTasks() {
6721 mRecentTasks.flush();
6722 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006723
6724 @Override
6725 public WindowProcessController getHomeProcess() {
6726 synchronized (mGlobalLock) {
6727 return mHomeProcess;
6728 }
6729 }
6730
6731 @Override
6732 public WindowProcessController getPreviousProcess() {
6733 synchronized (mGlobalLock) {
6734 return mPreviousProcess;
6735 }
6736 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006737
6738 @Override
6739 public void clearLockedTasks(String reason) {
6740 synchronized (mGlobalLock) {
6741 getLockTaskController().clearLockedTasks(reason);
6742 }
6743 }
6744
6745 @Override
6746 public void updateUserConfiguration() {
6747 synchronized (mGlobalLock) {
6748 final Configuration configuration = new Configuration(getGlobalConfiguration());
6749 final int currentUserId = mAmInternal.getCurrentUserId();
6750 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6751 configuration, currentUserId, Settings.System.canWrite(mContext));
6752 updateConfigurationLocked(configuration, null /* starting */,
6753 false /* initLocale */, false /* persistent */, currentUserId,
6754 false /* deferResume */);
6755 }
6756 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006757
6758 @Override
6759 public boolean canShowErrorDialogs() {
6760 synchronized (mGlobalLock) {
6761 return mShowDialogs && !mSleeping && !mShuttingDown
6762 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6763 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6764 mAmInternal.getCurrentUserId())
6765 && !(UserManager.isDeviceInDemoMode(mContext)
6766 && mAmInternal.getCurrentUser().isDemo());
6767 }
6768 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006769 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07006770}