blob: 4a0f692265396b2db6cedde4f155a7aae446ccc2 [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
17package com.android.server.am;
18
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;
Wale Ogunwale906f9c62018-07-23 11:23:44 -070022import static android.Manifest.permission.FILTER_EVENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070023import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070024import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070025import static android.Manifest.permission.READ_FRAME_BUFFER;
26import static android.Manifest.permission.REMOVE_TASKS;
27import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070028import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070029import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalef6733932018-06-27 05:14:34 -070030import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
31import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
32import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070033import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef6733932018-06-27 05:14:34 -070034import static com.android.server.am.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
35import static com.android.server.am.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070036import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
37import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
38import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
39import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070042import static android.app.AppOpsManager.OP_NONE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070043import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070044import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
45import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070046import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
47import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070048import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070049import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070050import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
52import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070053import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070054import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
56import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
63import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070065import static android.view.WindowManager.TRANSIT_ACTIVITY_OPEN;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070068import static android.view.WindowManager.TRANSIT_TASK_OPEN;
69import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070070import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070071import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
72import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
73import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IMMERSIVE;
74import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070075import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070076import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070077import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070078import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070079import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070080import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
81import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IMMERSIVE;
82import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070083import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070084import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
85import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070086import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
87import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070088import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070089import static com.android.server.am.ActivityManagerService.ANIMATE;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070090import static com.android.server.am.ActivityManagerService.MY_PID;
91import static com.android.server.am.ActivityManagerService.SEND_LOCALE_TO_MOUNT_DAEMON_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070092import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070093import static com.android.server.am.ActivityManagerService.UPDATE_CONFIGURATION_MSG;
94import static com.android.server.am.ActivityManagerService.checkComponentPermission;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070095import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070096import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070097import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
98import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
99import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
100import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
101import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
102import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
103import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700104import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700105import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
106import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
107import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700108
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700109import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700110import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700111import android.annotation.Nullable;
112import android.annotation.UserIdInt;
113import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700114import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700115import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import android.app.ActivityOptions;
117import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700118import android.app.ActivityThread;
119import android.app.AlertDialog;
120import android.app.Dialog;
121import android.content.DialogInterface;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700122import android.content.pm.IPackageManager;
123import android.content.pm.PackageManagerInternal;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700124import android.database.ContentObserver;
125import android.os.IUserManager;
126import android.os.PowerManager;
127import android.os.ServiceManager;
128import android.os.Trace;
129import android.os.UserManager;
130import android.os.WorkSource;
131import android.view.WindowManager;
132import com.android.internal.R;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import com.android.internal.app.IAppOpsService;
134import com.android.server.AppOpsService;
135import com.android.server.pm.UserManagerService;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700136import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700137import com.android.server.wm.ActivityTaskManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
143import android.app.ITaskStackListener;
144import android.app.PictureInPictureParams;
145import android.app.ProfilerInfo;
146import android.app.RemoteAction;
147import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700148import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.admin.DevicePolicyCache;
150import android.app.assist.AssistContent;
151import android.app.assist.AssistStructure;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700152import android.app.servertransaction.ConfigurationChangeItem;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.usage.UsageEvents;
154import android.content.ActivityNotFoundException;
155import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700156import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700157import android.content.Context;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.IIntentSender;
159import android.content.Intent;
160import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.pm.ApplicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.pm.PackageManager;
163import android.content.pm.ParceledListSlice;
164import android.content.pm.ResolveInfo;
165import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.res.Resources;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.graphics.Bitmap;
168import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700169import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.metrics.LogMaker;
171import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700172import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700173import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.os.Bundle;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700175import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700176import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.os.IBinder;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700178import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700179import android.os.Looper;
180import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.os.PersistableBundle;
182import android.os.RemoteException;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700184import android.os.SystemClock;
185import android.os.SystemProperties;
186import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.UserHandle;
188import android.provider.Settings;
189import android.service.voice.IVoiceInteractionSession;
190import android.service.voice.VoiceInteractionManagerInternal;
191import android.telecom.TelecomManager;
192import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700193import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700194import android.util.ArrayMap;
195import android.util.EventLog;
196import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700197import android.util.Slog;
198
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700200import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700202import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700203import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.view.IRecentsAnimationRunner;
205import android.view.RemoteAnimationAdapter;
206import android.view.RemoteAnimationDefinition;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700207
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import com.android.internal.app.AssistUtils;
210import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700211import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import com.android.internal.logging.MetricsLogger;
213import com.android.internal.os.logging.MetricsLoggerWrapper;
214import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
215import com.android.internal.policy.IKeyguardDismissCallback;
216import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700217import com.android.internal.util.Preconditions;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700219import com.android.server.LocalServices;
220import com.android.server.SystemService;
221import com.android.server.Watchdog;
222import com.android.server.vr.VrManagerInternal;
223import com.android.server.wm.PinnedStackWindowController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import com.android.server.wm.WindowManagerService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225
226import java.io.File;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700227import java.io.FileOutputStream;
228import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700229import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import java.io.StringWriter;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231import java.util.ArrayList;
232import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import java.util.Locale;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
235/**
236 * System service for managing activities and their containers (task, stacks, displays,... ).
237 *
238 * {@hide}
239 */
240public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
241 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_AM;
242 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
244 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
245 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
246 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
247 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700249
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700250 // How long we wait until we timeout on key dispatching.
251 private static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
252 // How long we wait until we timeout on key dispatching during instrumentation.
253 private static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
254
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700255 Context mContext;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700256 /**
257 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
258 * change at runtime. Use mContext for non-UI purposes.
259 */
260 final Context mUiContext;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700261 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700262 UiHandler mUiHandler;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700263 ActivityManagerService mAm;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700264 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700265 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700266 private PackageManagerInternal mPmInternal;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700267 /* Global service lock used by the package the owns this service. */
268 Object mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700269 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700270 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700271 private UserManagerService mUserManager;
272 private AppOpsService mAppOpsService;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273 /** All processes currently running that might have a window organized by name. */
274 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700275 /** All processes we currently have running mapped by pid */
276 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277 /** This is the process holding what we currently consider to be the "home" activity. */
278 WindowProcessController mHomeProcess;
279 /**
280 * This is the process holding the activity the user last visited that is in a different process
281 * from the one they are currently in.
282 */
283 WindowProcessController mPreviousProcess;
284 /** The time at which the previous process was last visible. */
285 long mPreviousProcessVisibleTime;
286
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700287 /** List of intents that were used to start the most recent tasks. */
288 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700289 /** State of external calls telling us if the device is awake or asleep. */
290 private boolean mKeyguardShown = false;
291
292 // Wrapper around VoiceInteractionServiceManager
293 private AssistUtils mAssistUtils;
294
295 // VoiceInteraction session ID that changes for each new request except when
296 // being called for multi-window assist in a single session.
297 private int mViSessionId = 1000;
298
299 // How long to wait in getAssistContextExtras for the activity and foreground services
300 // to respond with the result.
301 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
302
303 // How long top wait when going through the modern assist (which doesn't need to block
304 // on getting this result before starting to launch its UI).
305 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
306
307 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
308 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
309
310 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
311
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700312 // Keeps track of the active voice interaction service component, notified from
313 // VoiceInteractionManagerService
314 ComponentName mActiveVoiceInteractionServiceComponent;
315
316 private VrController mVrController;
317 KeyguardController mKeyguardController;
318 private final ClientLifecycleManager mLifecycleManager;
319 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700320 /** The controller for all operations related to locktask. */
321 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700322 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700323
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700324 boolean mSuppressResizeConfigChanges;
325
326 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
327 new UpdateConfigurationResult();
328
329 static final class UpdateConfigurationResult {
330 // Configuration changes that were updated.
331 int changes;
332 // If the activity was relaunched to match the new configuration.
333 boolean activityRelaunched;
334
335 void reset() {
336 changes = 0;
337 activityRelaunched = false;
338 }
339 }
340
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700341 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700342 private int mConfigurationSeq;
343 // To cache the list of supported system locales
344 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700345
346 /**
347 * Temp object used when global and/or display override configuration is updated. It is also
348 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
349 * anyone...
350 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 private Configuration mTempConfig = new Configuration();
352
Wale Ogunwalef6733932018-06-27 05:14:34 -0700353 /** Temporary to avoid allocations. */
354 final StringBuilder mStringBuilder = new StringBuilder(256);
355
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 // Amount of time after a call to stopAppSwitches() during which we will
357 // prevent further untrusted switches from happening.
358 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
359
360 /**
361 * The time at which we will allow normal application switches again,
362 * after a call to {@link #stopAppSwitches()}.
363 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700364 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700365 /**
366 * This is set to true after the first switch after mAppSwitchesAllowedTime
367 * is set; any switches after that will clear the time.
368 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700369 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700370
371 IActivityController mController = null;
372 boolean mControllerIsAMonkey = false;
373
374 /**
375 * Used to retain an update lock when the foreground activity is in
376 * immersive mode.
377 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700379
380 /**
381 * Packages that are being allowed to perform unrestricted app switches. Mapping is
382 * User -> Type -> uid.
383 */
384 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
385
386 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700387 private int mThumbnailWidth;
388 private int mThumbnailHeight;
389 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700390
391 /**
392 * Flag that indicates if multi-window is enabled.
393 *
394 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
395 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
396 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
397 * At least one of the forms of multi-window must be enabled in order for this flag to be
398 * initialized to 'true'.
399 *
400 * @see #mSupportsSplitScreenMultiWindow
401 * @see #mSupportsFreeformWindowManagement
402 * @see #mSupportsPictureInPicture
403 * @see #mSupportsMultiDisplay
404 */
405 boolean mSupportsMultiWindow;
406 boolean mSupportsSplitScreenMultiWindow;
407 boolean mSupportsFreeformWindowManagement;
408 boolean mSupportsPictureInPicture;
409 boolean mSupportsMultiDisplay;
410 boolean mForceResizableActivities;
411
412 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
413
414 // VR Vr2d Display Id.
415 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700416
Wale Ogunwalef6733932018-06-27 05:14:34 -0700417 /**
418 * Set while we are wanting to sleep, to prevent any
419 * activities from being started/resumed.
420 *
421 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
422 *
423 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
424 * while in the sleep state until there is a pending transition out of sleep, in which case
425 * mSleeping is set to false, and remains false while awake.
426 *
427 * Whether mSleeping can quickly toggled between true/false without the device actually
428 * display changing states is undefined.
429 */
430 private boolean mSleeping = false;
431
432 /**
433 * The process state used for processes that are running the top activities.
434 * This changes between TOP and TOP_SLEEPING to following mSleeping.
435 */
436 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
437
438 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
439 // automatically. Important for devices without direct input devices.
440 private boolean mShowDialogs = true;
441
442 /** Set if we are shutting down the system, similar to sleeping. */
443 boolean mShuttingDown = false;
444
445 /**
446 * We want to hold a wake lock while running a voice interaction session, since
447 * this may happen with the screen off and we need to keep the CPU running to
448 * be able to continue to interact with the user.
449 */
450 PowerManager.WakeLock mVoiceWakeLock;
451
452 /**
453 * Set while we are running a voice interaction. This overrides sleeping while it is active.
454 */
455 IVoiceInteractionSession mRunningVoice;
456
457 /**
458 * The last resumed activity. This is identical to the current resumed activity most
459 * of the time but could be different when we're pausing one activity before we resume
460 * another activity.
461 */
462 ActivityRecord mLastResumedActivity;
463
464 /**
465 * The activity that is currently being traced as the active resumed activity.
466 *
467 * @see #updateResumedAppTrace
468 */
469 private @Nullable ActivityRecord mTracedResumedActivity;
470
471 /** If non-null, we are tracking the time the user spends in the currently focused app. */
472 AppTimeTracker mCurAppTimeTracker;
473
474 private FontScaleSettingObserver mFontScaleSettingObserver;
475
476 private final class FontScaleSettingObserver extends ContentObserver {
477 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
478 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
479
480 public FontScaleSettingObserver() {
481 super(mH);
482 final ContentResolver resolver = mContext.getContentResolver();
483 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
484 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
485 UserHandle.USER_ALL);
486 }
487
488 @Override
489 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
490 if (mFontScaleUri.equals(uri)) {
491 updateFontScaleIfNeeded(userId);
492 } else if (mHideErrorDialogsUri.equals(uri)) {
493 synchronized (mGlobalLock) {
494 updateShouldShowDialogsLocked(getGlobalConfiguration());
495 }
496 }
497 }
498 }
499
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700500 ActivityTaskManagerService(Context context) {
501 mContext = context;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700502 mUiContext = ActivityThread.currentActivityThread().getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700503 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700504 }
505
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700506 void onSystemReady() {
507 mAssistUtils = new AssistUtils(mContext);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700508 mVrController.onSystemReady();
509 mRecentTasks.onSystemReadyLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700510 }
511
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 void onInitPowerManagement() {
513 mStackSupervisor.initPowerManagement();
514 final PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
515 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
516 mVoiceWakeLock.setReferenceCounted(false);
517 }
518
519 void installSystemProviders() {
520 mFontScaleSettingObserver = new FontScaleSettingObserver();
521 }
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 void retrieveSettings(ContentResolver resolver) {
524 final boolean freeformWindowManagement =
525 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
526 || Settings.Global.getInt(
527 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
528
529 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
530 final boolean supportsPictureInPicture = supportsMultiWindow &&
531 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
532 final boolean supportsSplitScreenMultiWindow =
533 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
534 final boolean supportsMultiDisplay = mContext.getPackageManager()
535 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
536 final boolean alwaysFinishActivities =
537 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
538 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
539 final boolean forceResizable = Settings.Global.getInt(
540 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
541
542 // Transfer any global setting for forcing RTL layout, into a System Property
543 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
544
545 final Configuration configuration = new Configuration();
546 Settings.System.getConfiguration(resolver, configuration);
547 if (forceRtl) {
548 // This will take care of setting the correct layout direction flags
549 configuration.setLayoutDirection(configuration.locale);
550 }
551
552 synchronized (mGlobalLock) {
553 mForceResizableActivities = forceResizable;
554 final boolean multiWindowFormEnabled = freeformWindowManagement
555 || supportsSplitScreenMultiWindow
556 || supportsPictureInPicture
557 || supportsMultiDisplay;
558 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
559 mSupportsMultiWindow = true;
560 mSupportsFreeformWindowManagement = freeformWindowManagement;
561 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
562 mSupportsPictureInPicture = supportsPictureInPicture;
563 mSupportsMultiDisplay = supportsMultiDisplay;
564 } else {
565 mSupportsMultiWindow = false;
566 mSupportsFreeformWindowManagement = false;
567 mSupportsSplitScreenMultiWindow = false;
568 mSupportsPictureInPicture = false;
569 mSupportsMultiDisplay = false;
570 }
571 mWindowManager.setForceResizableTasks(mForceResizableActivities);
572 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
573 // This happens before any activities are started, so we can change global configuration
574 // in-place.
575 updateConfigurationLocked(configuration, null, true);
576 final Configuration globalConfig = getGlobalConfiguration();
577 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
578
579 // Load resources only after the current configuration has been set.
580 final Resources res = mContext.getResources();
581 mThumbnailWidth = res.getDimensionPixelSize(
582 com.android.internal.R.dimen.thumbnail_width);
583 mThumbnailHeight = res.getDimensionPixelSize(
584 com.android.internal.R.dimen.thumbnail_height);
585
586 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
587 mFullscreenThumbnailScale = (float) res
588 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
589 (float) globalConfig.screenWidthDp;
590 } else {
591 mFullscreenThumbnailScale = res.getFraction(
592 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
593 }
594 }
595 }
596
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700597 // TODO: Will be converted to WM lock once transition is complete.
598 void setActivityManagerService(ActivityManagerService am) {
599 mAm = am;
600 mGlobalLock = mAm;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700601 mH = new H(mAm.mHandlerThread.getLooper());
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700602 mUiHandler = new UiHandler();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700603
604 mTempConfig.setToDefaults();
605 mTempConfig.setLocales(LocaleList.getDefault());
606 mConfigurationSeq = mTempConfig.seq = 1;
607 mStackSupervisor = createStackSupervisor();
608 mStackSupervisor.onConfigurationChanged(mTempConfig);
609
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700610 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700611 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700612 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700613 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700614 mRecentTasks = createRecentTasks();
615 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700616 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700617 mKeyguardController = mStackSupervisor.getKeyguardController();
618 }
619
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700620 void onActivityManagerInternalAdded() {
621 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700622 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700623 }
624
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700625 protected ActivityStackSupervisor createStackSupervisor() {
626 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
627 supervisor.initialize();
628 return supervisor;
629 }
630
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700631 void setWindowManager(WindowManagerService wm) {
632 mWindowManager = wm;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700633 mLockTaskController.setWindowManager(wm);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700634 }
635
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 UserManagerService getUserManager() {
637 if (mUserManager == null) {
638 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
639 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
640 }
641 return mUserManager;
642 }
643
644 AppOpsService getAppOpsService() {
645 if (mAppOpsService == null) {
646 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
647 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
648 }
649 return mAppOpsService;
650 }
651
652 boolean hasUserRestriction(String restriction, int userId) {
653 return getUserManager().hasUserRestriction(restriction, userId);
654 }
655
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700656 protected RecentTasks createRecentTasks() {
657 return new RecentTasks(this, mStackSupervisor);
658 }
659
660 RecentTasks getRecentTasks() {
661 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700662 }
663
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700664 ClientLifecycleManager getLifecycleManager() {
665 return mLifecycleManager;
666 }
667
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700668 ActivityStartController getActivityStartController() {
669 return mActivityStartController;
670 }
671
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700672 TaskChangeNotificationController getTaskChangeNotificationController() {
673 return mTaskChangeNotificationController;
674 }
675
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700676 LockTaskController getLockTaskController() {
677 return mLockTaskController;
678 }
679
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700680 private void start() {
681 LocalServices.addService(ActivityTaskManagerInternal.class, new LocalService());
682 }
683
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 public static final class Lifecycle extends SystemService {
685 private final ActivityTaskManagerService mService;
686
687 public Lifecycle(Context context) {
688 super(context);
689 mService = new ActivityTaskManagerService(context);
690 }
691
692 @Override
693 public void onStart() {
694 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700695 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700696 }
697
698 public ActivityTaskManagerService getService() {
699 return mService;
700 }
701 }
702
703 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700704 public final int startActivity(IApplicationThread caller, String callingPackage,
705 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
706 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
707 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
708 resultWho, requestCode, startFlags, profilerInfo, bOptions,
709 UserHandle.getCallingUserId());
710 }
711
712 @Override
713 public final int startActivities(IApplicationThread caller, String callingPackage,
714 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
715 int userId) {
716 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700717 enforceNotIsolatedCaller(reason);
718 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700719 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700720 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700721 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason);
722 }
723
724 @Override
725 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
726 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
727 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
728 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
729 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
730 true /*validateIncomingUser*/);
731 }
732
733 int startActivityAsUser(IApplicationThread caller, String callingPackage,
734 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
735 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
736 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700738
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700739 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700740 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
741
742 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700743 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700744 .setCaller(caller)
745 .setCallingPackage(callingPackage)
746 .setResolvedType(resolvedType)
747 .setResultTo(resultTo)
748 .setResultWho(resultWho)
749 .setRequestCode(requestCode)
750 .setStartFlags(startFlags)
751 .setProfilerInfo(profilerInfo)
752 .setActivityOptions(bOptions)
753 .setMayWait(userId)
754 .execute();
755
756 }
757
758 @Override
759 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
760 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
762 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700763 // Refuse possible leaked file descriptors
764 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
765 throw new IllegalArgumentException("File descriptors passed in Intent");
766 }
767
768 if (!(target instanceof PendingIntentRecord)) {
769 throw new IllegalArgumentException("Bad PendingIntent object");
770 }
771
772 PendingIntentRecord pir = (PendingIntentRecord)target;
773
774 synchronized (mGlobalLock) {
775 // If this is coming from the currently resumed activity, it is
776 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700777 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700778 if (stack.mResumedActivity != null &&
779 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700781 }
782 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700784 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700785 }
786
787 @Override
788 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
789 Bundle bOptions) {
790 // Refuse possible leaked file descriptors
791 if (intent != null && intent.hasFileDescriptors()) {
792 throw new IllegalArgumentException("File descriptors passed in Intent");
793 }
794 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
795
796 synchronized (mGlobalLock) {
797 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
798 if (r == null) {
799 SafeActivityOptions.abort(options);
800 return false;
801 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700802 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700803 // The caller is not running... d'oh!
804 SafeActivityOptions.abort(options);
805 return false;
806 }
807 intent = new Intent(intent);
808 // The caller is not allowed to change the data.
809 intent.setDataAndType(r.intent.getData(), r.intent.getType());
810 // And we are resetting to find the next component...
811 intent.setComponent(null);
812
813 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
814
815 ActivityInfo aInfo = null;
816 try {
817 List<ResolveInfo> resolves =
818 AppGlobals.getPackageManager().queryIntentActivities(
819 intent, r.resolvedType,
820 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
821 UserHandle.getCallingUserId()).getList();
822
823 // Look for the original activity in the list...
824 final int N = resolves != null ? resolves.size() : 0;
825 for (int i=0; i<N; i++) {
826 ResolveInfo rInfo = resolves.get(i);
827 if (rInfo.activityInfo.packageName.equals(r.packageName)
828 && rInfo.activityInfo.name.equals(r.info.name)) {
829 // We found the current one... the next matching is
830 // after it.
831 i++;
832 if (i<N) {
833 aInfo = resolves.get(i).activityInfo;
834 }
835 if (debug) {
836 Slog.v(TAG, "Next matching activity: found current " + r.packageName
837 + "/" + r.info.name);
838 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
839 ? "null" : aInfo.packageName + "/" + aInfo.name));
840 }
841 break;
842 }
843 }
844 } catch (RemoteException e) {
845 }
846
847 if (aInfo == null) {
848 // Nobody who is next!
849 SafeActivityOptions.abort(options);
850 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
851 return false;
852 }
853
854 intent.setComponent(new ComponentName(
855 aInfo.applicationInfo.packageName, aInfo.name));
856 intent.setFlags(intent.getFlags()&~(
857 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
858 Intent.FLAG_ACTIVITY_CLEAR_TOP|
859 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
860 FLAG_ACTIVITY_NEW_TASK));
861
862 // Okay now we need to start the new activity, replacing the currently running activity.
863 // This is a little tricky because we want to start the new one as if the current one is
864 // finished, but not finish the current one first so that there is no flicker.
865 // And thus...
866 final boolean wasFinishing = r.finishing;
867 r.finishing = true;
868
869 // Propagate reply information over to the new activity.
870 final ActivityRecord resultTo = r.resultTo;
871 final String resultWho = r.resultWho;
872 final int requestCode = r.requestCode;
873 r.resultTo = null;
874 if (resultTo != null) {
875 resultTo.removeResultsLocked(r, resultWho, requestCode);
876 }
877
878 final long origId = Binder.clearCallingIdentity();
879 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700880 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700881 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700882 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700883 .setResolvedType(r.resolvedType)
884 .setActivityInfo(aInfo)
885 .setResultTo(resultTo != null ? resultTo.appToken : null)
886 .setResultWho(resultWho)
887 .setRequestCode(requestCode)
888 .setCallingPid(-1)
889 .setCallingUid(r.launchedFromUid)
890 .setCallingPackage(r.launchedFromPackage)
891 .setRealCallingPid(-1)
892 .setRealCallingUid(r.launchedFromUid)
893 .setActivityOptions(options)
894 .execute();
895 Binder.restoreCallingIdentity(origId);
896
897 r.finishing = wasFinishing;
898 if (res != ActivityManager.START_SUCCESS) {
899 return false;
900 }
901 return true;
902 }
903 }
904
905 @Override
906 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
907 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
908 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
909 final WaitResult res = new WaitResult();
910 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700911 enforceNotIsolatedCaller("startActivityAndWait");
912 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
913 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700914 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700915 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700916 .setCaller(caller)
917 .setCallingPackage(callingPackage)
918 .setResolvedType(resolvedType)
919 .setResultTo(resultTo)
920 .setResultWho(resultWho)
921 .setRequestCode(requestCode)
922 .setStartFlags(startFlags)
923 .setActivityOptions(bOptions)
924 .setMayWait(userId)
925 .setProfilerInfo(profilerInfo)
926 .setWaitResult(res)
927 .execute();
928 }
929 return res;
930 }
931
932 @Override
933 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
934 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
935 int startFlags, Configuration config, Bundle bOptions, int userId) {
936 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700937 enforceNotIsolatedCaller("startActivityWithConfig");
938 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
939 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700940 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700941 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700942 .setCaller(caller)
943 .setCallingPackage(callingPackage)
944 .setResolvedType(resolvedType)
945 .setResultTo(resultTo)
946 .setResultWho(resultWho)
947 .setRequestCode(requestCode)
948 .setStartFlags(startFlags)
949 .setGlobalConfiguration(config)
950 .setActivityOptions(bOptions)
951 .setMayWait(userId)
952 .execute();
953 }
954 }
955
956 @Override
957 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
958 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
959 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
960 int userId) {
961
962 // This is very dangerous -- it allows you to perform a start activity (including
963 // permission grants) as any app that may launch one of your own activities. So
964 // we will only allow this to be done from activities that are part of the core framework,
965 // and then only when they are running as the system.
966 final ActivityRecord sourceRecord;
967 final int targetUid;
968 final String targetPackage;
969 final boolean isResolver;
970 synchronized (mGlobalLock) {
971 if (resultTo == null) {
972 throw new SecurityException("Must be called from an activity");
973 }
974 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
975 if (sourceRecord == null) {
976 throw new SecurityException("Called with bad activity token: " + resultTo);
977 }
978 if (!sourceRecord.info.packageName.equals("android")) {
979 throw new SecurityException(
980 "Must be called from an activity that is declared in the android package");
981 }
982 if (sourceRecord.app == null) {
983 throw new SecurityException("Called without a process attached to activity");
984 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700985 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 // This is still okay, as long as this activity is running under the
987 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700988 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700989 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700990 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700991 + " must be system uid or original calling uid "
992 + sourceRecord.launchedFromUid);
993 }
994 }
995 if (ignoreTargetSecurity) {
996 if (intent.getComponent() == null) {
997 throw new SecurityException(
998 "Component must be specified with ignoreTargetSecurity");
999 }
1000 if (intent.getSelector() != null) {
1001 throw new SecurityException(
1002 "Selector not allowed with ignoreTargetSecurity");
1003 }
1004 }
1005 targetUid = sourceRecord.launchedFromUid;
1006 targetPackage = sourceRecord.launchedFromPackage;
1007 isResolver = sourceRecord.isResolverOrChildActivity();
1008 }
1009
1010 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001011 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 }
1013
1014 // TODO: Switch to user app stacks here.
1015 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001016 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 .setCallingUid(targetUid)
1018 .setCallingPackage(targetPackage)
1019 .setResolvedType(resolvedType)
1020 .setResultTo(resultTo)
1021 .setResultWho(resultWho)
1022 .setRequestCode(requestCode)
1023 .setStartFlags(startFlags)
1024 .setActivityOptions(bOptions)
1025 .setMayWait(userId)
1026 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1027 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1028 .execute();
1029 } catch (SecurityException e) {
1030 // XXX need to figure out how to propagate to original app.
1031 // A SecurityException here is generally actually a fault of the original
1032 // calling activity (such as a fairly granting permissions), so propagate it
1033 // back to them.
1034 /*
1035 StringBuilder msg = new StringBuilder();
1036 msg.append("While launching");
1037 msg.append(intent.toString());
1038 msg.append(": ");
1039 msg.append(e.getMessage());
1040 */
1041 throw e;
1042 }
1043 }
1044
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001045 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1046 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1047 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1048 }
1049
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 @Override
1051 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1052 Intent intent, String resolvedType, IVoiceInteractionSession session,
1053 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1054 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001055 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 if (session == null || interactor == null) {
1057 throw new NullPointerException("null session or interactor");
1058 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001059 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001061 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 .setCallingUid(callingUid)
1063 .setCallingPackage(callingPackage)
1064 .setResolvedType(resolvedType)
1065 .setVoiceSession(session)
1066 .setVoiceInteractor(interactor)
1067 .setStartFlags(startFlags)
1068 .setProfilerInfo(profilerInfo)
1069 .setActivityOptions(bOptions)
1070 .setMayWait(userId)
1071 .execute();
1072 }
1073
1074 @Override
1075 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1076 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001077 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1078 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001080 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 .setCallingUid(callingUid)
1082 .setCallingPackage(callingPackage)
1083 .setResolvedType(resolvedType)
1084 .setActivityOptions(bOptions)
1085 .setMayWait(userId)
1086 .execute();
1087 }
1088
1089 @Override
1090 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1091 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001092 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001093 final int callingPid = Binder.getCallingPid();
1094 final long origId = Binder.clearCallingIdentity();
1095 try {
1096 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001097 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1098 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099
1100 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001101 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1102 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1104 recentsUid, assistDataReceiver);
1105 }
1106 } finally {
1107 Binder.restoreCallingIdentity(origId);
1108 }
1109 }
1110
1111 @Override
1112 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001113 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 "startActivityFromRecents()");
1115
1116 final int callingPid = Binder.getCallingPid();
1117 final int callingUid = Binder.getCallingUid();
1118 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1119 final long origId = Binder.clearCallingIdentity();
1120 try {
1121 synchronized (mGlobalLock) {
1122 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1123 safeOptions);
1124 }
1125 } finally {
1126 Binder.restoreCallingIdentity(origId);
1127 }
1128 }
1129
1130 /**
1131 * This is the internal entry point for handling Activity.finish().
1132 *
1133 * @param token The Binder token referencing the Activity we want to finish.
1134 * @param resultCode Result code, if any, from this Activity.
1135 * @param resultData Result data (Intent), if any, from this Activity.
1136 * @param finishTask Whether to finish the task associated with this Activity.
1137 *
1138 * @return Returns true if the activity successfully finished, or false if it is still running.
1139 */
1140 @Override
1141 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1142 int finishTask) {
1143 // Refuse possible leaked file descriptors
1144 if (resultData != null && resultData.hasFileDescriptors()) {
1145 throw new IllegalArgumentException("File descriptors passed in Intent");
1146 }
1147
1148 synchronized (mGlobalLock) {
1149 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1150 if (r == null) {
1151 return true;
1152 }
1153 // Keep track of the root activity of the task before we finish it
1154 TaskRecord tr = r.getTask();
1155 ActivityRecord rootR = tr.getRootActivity();
1156 if (rootR == null) {
1157 Slog.w(TAG, "Finishing task with all activities already finished");
1158 }
1159 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1160 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001161 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001162 return false;
1163 }
1164
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001165 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1166 // We should consolidate.
1167 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 // Find the first activity that is not finishing.
1169 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1170 if (next != null) {
1171 // ask watcher if this is allowed
1172 boolean resumeOK = true;
1173 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001174 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001175 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001176 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 Watchdog.getInstance().setActivityController(null);
1178 }
1179
1180 if (!resumeOK) {
1181 Slog.i(TAG, "Not finishing activity because controller resumed");
1182 return false;
1183 }
1184 }
1185 }
1186 final long origId = Binder.clearCallingIdentity();
1187 try {
1188 boolean res;
1189 final boolean finishWithRootActivity =
1190 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1191 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1192 || (finishWithRootActivity && r == rootR)) {
1193 // If requested, remove the task that is associated to this activity only if it
1194 // was the root activity in the task. The result code and data is ignored
1195 // because we don't support returning them across task boundaries. Also, to
1196 // keep backwards compatibility we remove the task from recents when finishing
1197 // task with root activity.
1198 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1199 finishWithRootActivity, "finish-activity");
1200 if (!res) {
1201 Slog.i(TAG, "Removing task failed to finish activity");
1202 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001203 // Explicitly dismissing the activity so reset its relaunch flag.
1204 r.mRelaunchReason = ActivityRecord.RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001205 } else {
1206 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1207 resultData, "app-request", true);
1208 if (!res) {
1209 Slog.i(TAG, "Failed to finish by app-request");
1210 }
1211 }
1212 return res;
1213 } finally {
1214 Binder.restoreCallingIdentity(origId);
1215 }
1216 }
1217 }
1218
1219 @Override
1220 public boolean finishActivityAffinity(IBinder token) {
1221 synchronized (mGlobalLock) {
1222 final long origId = Binder.clearCallingIdentity();
1223 try {
1224 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1225 if (r == null) {
1226 return false;
1227 }
1228
1229 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1230 // can finish.
1231 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001232 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001233 return false;
1234 }
1235 return task.getStack().finishActivityAffinityLocked(r);
1236 } finally {
1237 Binder.restoreCallingIdentity(origId);
1238 }
1239 }
1240 }
1241
1242 @Override
1243 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1244 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001245 try {
1246 WindowProcessController proc = null;
1247 synchronized (mGlobalLock) {
1248 ActivityStack stack = ActivityRecord.getStackLocked(token);
1249 if (stack == null) {
1250 return;
1251 }
1252 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1253 false /* fromTimeout */, false /* processPausingActivities */, config);
1254 if (r != null) {
1255 proc = r.app;
1256 }
1257 if (stopProfiling && proc != null) {
1258 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001259 }
1260 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001261 } finally {
1262 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001263 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 }
1265
1266 @Override
1267 public final void activityResumed(IBinder token) {
1268 final long origId = Binder.clearCallingIdentity();
1269 synchronized (mGlobalLock) {
1270 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001271 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001272 }
1273 Binder.restoreCallingIdentity(origId);
1274 }
1275
1276 @Override
1277 public final void activityPaused(IBinder token) {
1278 final long origId = Binder.clearCallingIdentity();
1279 synchronized (mGlobalLock) {
1280 ActivityStack stack = ActivityRecord.getStackLocked(token);
1281 if (stack != null) {
1282 stack.activityPausedLocked(token, false);
1283 }
1284 }
1285 Binder.restoreCallingIdentity(origId);
1286 }
1287
1288 @Override
1289 public final void activityStopped(IBinder token, Bundle icicle,
1290 PersistableBundle persistentState, CharSequence description) {
1291 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1292
1293 // Refuse possible leaked file descriptors
1294 if (icicle != null && icicle.hasFileDescriptors()) {
1295 throw new IllegalArgumentException("File descriptors passed in Bundle");
1296 }
1297
1298 final long origId = Binder.clearCallingIdentity();
1299
1300 synchronized (mGlobalLock) {
1301 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1302 if (r != null) {
1303 r.activityStoppedLocked(icicle, persistentState, description);
1304 }
1305 }
1306
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001307 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308
1309 Binder.restoreCallingIdentity(origId);
1310 }
1311
1312 @Override
1313 public final void activityDestroyed(IBinder token) {
1314 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1315 synchronized (mGlobalLock) {
1316 ActivityStack stack = ActivityRecord.getStackLocked(token);
1317 if (stack != null) {
1318 stack.activityDestroyedLocked(token, "activityDestroyed");
1319 }
1320 }
1321 }
1322
1323 @Override
1324 public final void activityRelaunched(IBinder token) {
1325 final long origId = Binder.clearCallingIdentity();
1326 synchronized (mGlobalLock) {
1327 mStackSupervisor.activityRelaunchedLocked(token);
1328 }
1329 Binder.restoreCallingIdentity(origId);
1330 }
1331
1332 public final void activitySlept(IBinder token) {
1333 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1334
1335 final long origId = Binder.clearCallingIdentity();
1336
1337 synchronized (mGlobalLock) {
1338 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1339 if (r != null) {
1340 mStackSupervisor.activitySleptLocked(r);
1341 }
1342 }
1343
1344 Binder.restoreCallingIdentity(origId);
1345 }
1346
1347 @Override
1348 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1349 synchronized (mGlobalLock) {
1350 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1351 if (r == null) {
1352 return;
1353 }
1354 final long origId = Binder.clearCallingIdentity();
1355 try {
1356 r.setRequestedOrientation(requestedOrientation);
1357 } finally {
1358 Binder.restoreCallingIdentity(origId);
1359 }
1360 }
1361 }
1362
1363 @Override
1364 public int getRequestedOrientation(IBinder token) {
1365 synchronized (mGlobalLock) {
1366 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1367 if (r == null) {
1368 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1369 }
1370 return r.getRequestedOrientation();
1371 }
1372 }
1373
1374 @Override
1375 public void setImmersive(IBinder token, boolean immersive) {
1376 synchronized (mGlobalLock) {
1377 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1378 if (r == null) {
1379 throw new IllegalArgumentException();
1380 }
1381 r.immersive = immersive;
1382
1383 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001384 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001386 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 }
1388 }
1389 }
1390
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001391 void applyUpdateLockStateLocked(ActivityRecord r) {
1392 // Modifications to the UpdateLock state are done on our handler, outside
1393 // the activity manager's locks. The new state is determined based on the
1394 // state *now* of the relevant activity record. The object is passed to
1395 // the handler solely for logging detail, not to be consulted/modified.
1396 final boolean nextState = r != null && r.immersive;
1397 mH.post(() -> {
1398 if (mUpdateLock.isHeld() != nextState) {
1399 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1400 "Applying new update lock state '" + nextState + "' for " + r);
1401 if (nextState) {
1402 mUpdateLock.acquire();
1403 } else {
1404 mUpdateLock.release();
1405 }
1406 }
1407 });
1408 }
1409
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 @Override
1411 public boolean isImmersive(IBinder token) {
1412 synchronized (mGlobalLock) {
1413 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1414 if (r == null) {
1415 throw new IllegalArgumentException();
1416 }
1417 return r.immersive;
1418 }
1419 }
1420
1421 @Override
1422 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001425 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 return (r != null) ? r.immersive : false;
1427 }
1428 }
1429
1430 @Override
1431 public void overridePendingTransition(IBinder token, String packageName,
1432 int enterAnim, int exitAnim) {
1433 synchronized (mGlobalLock) {
1434 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1435 if (self == null) {
1436 return;
1437 }
1438
1439 final long origId = Binder.clearCallingIdentity();
1440
1441 if (self.isState(
1442 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 mWindowManager.overridePendingAppTransition(packageName,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 enterAnim, exitAnim, null);
1445 }
1446
1447 Binder.restoreCallingIdentity(origId);
1448 }
1449 }
1450
1451 @Override
1452 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
1454 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001456 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001457 if (r == null) {
1458 return ActivityManager.COMPAT_MODE_UNKNOWN;
1459 }
1460 ai = r.info.applicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001461 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001462
1463 return mAmInternal.getPackageScreenCompatMode(ai);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 }
1465
1466 @Override
1467 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001468 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001470 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001472 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001473 if (r == null) {
1474 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1475 return;
1476 }
1477 ai = r.info.applicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001479
1480 mAmInternal.setPackageScreenCompatMode(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001481 }
1482
1483 @Override
1484 public int getLaunchedFromUid(IBinder activityToken) {
1485 ActivityRecord srec;
1486 synchronized (mGlobalLock) {
1487 srec = ActivityRecord.forTokenLocked(activityToken);
1488 }
1489 if (srec == null) {
1490 return -1;
1491 }
1492 return srec.launchedFromUid;
1493 }
1494
1495 @Override
1496 public String getLaunchedFromPackage(IBinder activityToken) {
1497 ActivityRecord srec;
1498 synchronized (mGlobalLock) {
1499 srec = ActivityRecord.forTokenLocked(activityToken);
1500 }
1501 if (srec == null) {
1502 return null;
1503 }
1504 return srec.launchedFromPackage;
1505 }
1506
1507 @Override
1508 public boolean convertFromTranslucent(IBinder token) {
1509 final long origId = Binder.clearCallingIdentity();
1510 try {
1511 synchronized (mGlobalLock) {
1512 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1513 if (r == null) {
1514 return false;
1515 }
1516 final boolean translucentChanged = r.changeWindowTranslucency(true);
1517 if (translucentChanged) {
1518 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1519 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001520 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 return translucentChanged;
1522 }
1523 } finally {
1524 Binder.restoreCallingIdentity(origId);
1525 }
1526 }
1527
1528 @Override
1529 public boolean convertToTranslucent(IBinder token, Bundle options) {
1530 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1531 final long origId = Binder.clearCallingIdentity();
1532 try {
1533 synchronized (mGlobalLock) {
1534 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1535 if (r == null) {
1536 return false;
1537 }
1538 final TaskRecord task = r.getTask();
1539 int index = task.mActivities.lastIndexOf(r);
1540 if (index > 0) {
1541 ActivityRecord under = task.mActivities.get(index - 1);
1542 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1543 }
1544 final boolean translucentChanged = r.changeWindowTranslucency(false);
1545 if (translucentChanged) {
1546 r.getStack().convertActivityToTranslucent(r);
1547 }
1548 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001549 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 return translucentChanged;
1551 }
1552 } finally {
1553 Binder.restoreCallingIdentity(origId);
1554 }
1555 }
1556
1557 @Override
1558 public void notifyActivityDrawn(IBinder token) {
1559 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1560 synchronized (mGlobalLock) {
1561 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1562 if (r != null) {
1563 r.getStack().notifyActivityDrawnLocked(r);
1564 }
1565 }
1566 }
1567
1568 @Override
1569 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1570 synchronized (mGlobalLock) {
1571 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1572 if (r == null) {
1573 return;
1574 }
1575 r.reportFullyDrawnLocked(restoredFromBundle);
1576 }
1577 }
1578
1579 @Override
1580 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1581 synchronized (mGlobalLock) {
1582 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1583 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1584 return stack.mDisplayId;
1585 }
1586 return DEFAULT_DISPLAY;
1587 }
1588 }
1589
1590 @Override
1591 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001592 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 long ident = Binder.clearCallingIdentity();
1594 try {
1595 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001596 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 if (focusedStack != null) {
1598 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1599 }
1600 return null;
1601 }
1602 } finally {
1603 Binder.restoreCallingIdentity(ident);
1604 }
1605 }
1606
1607 @Override
1608 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001609 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1611 final long callingId = Binder.clearCallingIdentity();
1612 try {
1613 synchronized (mGlobalLock) {
1614 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1615 if (stack == null) {
1616 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1617 return;
1618 }
1619 final ActivityRecord r = stack.topRunningActivityLocked();
1620 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
1621 r, "setFocusedStack")) {
1622 mStackSupervisor.resumeFocusedStackTopActivityLocked();
1623 }
1624 }
1625 } finally {
1626 Binder.restoreCallingIdentity(callingId);
1627 }
1628 }
1629
1630 @Override
1631 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001632 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001633 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1634 final long callingId = Binder.clearCallingIdentity();
1635 try {
1636 synchronized (mGlobalLock) {
1637 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1638 if (task == null) {
1639 return;
1640 }
1641 final ActivityRecord r = task.topRunningActivityLocked();
1642 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedTask")) {
1643 mStackSupervisor.resumeFocusedStackTopActivityLocked();
1644 }
1645 }
1646 } finally {
1647 Binder.restoreCallingIdentity(callingId);
1648 }
1649 }
1650
1651 @Override
1652 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001653 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 synchronized (mGlobalLock) {
1655 final long ident = Binder.clearCallingIdentity();
1656 try {
1657 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1658 "remove-task");
1659 } finally {
1660 Binder.restoreCallingIdentity(ident);
1661 }
1662 }
1663 }
1664
1665 @Override
1666 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1667 synchronized (mGlobalLock) {
1668 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1669 if (srec != null) {
1670 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1671 }
1672 }
1673 return false;
1674 }
1675
1676 @Override
1677 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1678 Intent resultData) {
1679
1680 synchronized (mGlobalLock) {
1681 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1682 if (r != null) {
1683 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1684 }
1685 return false;
1686 }
1687 }
1688
1689 /**
1690 * Attempts to move a task backwards in z-order (the order of activities within the task is
1691 * unchanged).
1692 *
1693 * There are several possible results of this call:
1694 * - if the task is locked, then we will show the lock toast
1695 * - if there is a task behind the provided task, then that task is made visible and resumed as
1696 * this task is moved to the back
1697 * - otherwise, if there are no other tasks in the stack:
1698 * - if this task is in the pinned stack, then we remove the stack completely, which will
1699 * have the effect of moving the task to the top or bottom of the fullscreen stack
1700 * (depending on whether it is visible)
1701 * - otherwise, we simply return home and hide this task
1702 *
1703 * @param token A reference to the activity we wish to move
1704 * @param nonRoot If false then this only works if the activity is the root
1705 * of a task; if true it will work for any activity in a task.
1706 * @return Returns true if the move completed, false if not.
1707 */
1708 @Override
1709 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001710 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 synchronized (mGlobalLock) {
1712 final long origId = Binder.clearCallingIdentity();
1713 try {
1714 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1715 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1716 if (task != null) {
1717 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
1718 }
1719 } finally {
1720 Binder.restoreCallingIdentity(origId);
1721 }
1722 }
1723 return false;
1724 }
1725
1726 @Override
1727 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001728 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 long ident = Binder.clearCallingIdentity();
1730 Rect rect = new Rect();
1731 try {
1732 synchronized (mGlobalLock) {
1733 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1734 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1735 if (task == null) {
1736 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
1737 return rect;
1738 }
1739 if (task.getStack() != null) {
1740 // Return the bounds from window manager since it will be adjusted for various
1741 // things like the presense of a docked stack for tasks that aren't resizeable.
1742 task.getWindowContainerBounds(rect);
1743 } else {
1744 // Task isn't in window manager yet since it isn't associated with a stack.
1745 // Return the persist value from activity manager
1746 if (!task.matchParentBounds()) {
1747 rect.set(task.getBounds());
1748 } else if (task.mLastNonFullscreenBounds != null) {
1749 rect.set(task.mLastNonFullscreenBounds);
1750 }
1751 }
1752 }
1753 } finally {
1754 Binder.restoreCallingIdentity(ident);
1755 }
1756 return rect;
1757 }
1758
1759 @Override
1760 public ActivityManager.TaskDescription getTaskDescription(int id) {
1761 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001762 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
1764 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
1765 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1766 if (tr != null) {
1767 return tr.lastTaskDescription;
1768 }
1769 }
1770 return null;
1771 }
1772
1773 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001774 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
1775 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1776 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
1777 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
1778 return;
1779 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001780 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001781 synchronized (mGlobalLock) {
1782 final long ident = Binder.clearCallingIdentity();
1783 try {
1784 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1785 if (task == null) {
1786 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
1787 return;
1788 }
1789
1790 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
1791 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
1792
1793 if (!task.isActivityTypeStandardOrUndefined()) {
1794 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
1795 + " non-standard task " + taskId + " to windowing mode="
1796 + windowingMode);
1797 }
1798
1799 final ActivityStack stack = task.getStack();
1800 if (toTop) {
1801 stack.moveToFront("setTaskWindowingMode", task);
1802 }
1803 stack.setWindowingMode(windowingMode);
1804 } finally {
1805 Binder.restoreCallingIdentity(ident);
1806 }
1807 }
1808 }
1809
1810 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001812 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 ActivityRecord r = getCallingRecordLocked(token);
1814 return r != null ? r.info.packageName : null;
1815 }
1816 }
1817
1818 @Override
1819 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001820 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 ActivityRecord r = getCallingRecordLocked(token);
1822 return r != null ? r.intent.getComponent() : null;
1823 }
1824 }
1825
1826 private ActivityRecord getCallingRecordLocked(IBinder token) {
1827 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1828 if (r == null) {
1829 return null;
1830 }
1831 return r.resultTo;
1832 }
1833
1834 @Override
1835 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837
1838 synchronized (mGlobalLock) {
1839 final long origId = Binder.clearCallingIdentity();
1840 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001841 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 } finally {
1843 Binder.restoreCallingIdentity(origId);
1844 }
1845 }
1846 }
1847
1848 /**
1849 * TODO: Add mController hook
1850 */
1851 @Override
1852 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854
1855 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
1856 synchronized (mGlobalLock) {
1857 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
1858 false /* fromRecents */);
1859 }
1860 }
1861
1862 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
1863 boolean fromRecents) {
1864
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001865 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 Binder.getCallingUid(), -1, -1, "Task to front")) {
1867 SafeActivityOptions.abort(options);
1868 return;
1869 }
1870 final long origId = Binder.clearCallingIdentity();
1871 try {
1872 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1873 if (task == null) {
1874 Slog.d(TAG, "Could not find task for id: "+ taskId);
1875 return;
1876 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001877 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
1879 return;
1880 }
1881 ActivityOptions realOptions = options != null
1882 ? options.getOptions(mStackSupervisor)
1883 : null;
1884 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
1885 false /* forceNonResizable */);
1886
1887 final ActivityRecord topActivity = task.getTopActivity();
1888 if (topActivity != null) {
1889
1890 // We are reshowing a task, use a starting window to hide the initial draw delay
1891 // so the transition can start earlier.
1892 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
1893 true /* taskSwitch */, fromRecents);
1894 }
1895 } finally {
1896 Binder.restoreCallingIdentity(origId);
1897 }
1898 SafeActivityOptions.abort(options);
1899 }
1900
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
1902 int callingPid, int callingUid, String name) {
1903 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
1904 return true;
1905 }
1906
1907 if (getRecentTasks().isCallerRecents(sourceUid)) {
1908 return true;
1909 }
1910
1911 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
1912 if (perm == PackageManager.PERMISSION_GRANTED) {
1913 return true;
1914 }
1915 if (checkAllowAppSwitchUid(sourceUid)) {
1916 return true;
1917 }
1918
1919 // If the actual IPC caller is different from the logical source, then
1920 // also see if they are allowed to control app switches.
1921 if (callingUid != -1 && callingUid != sourceUid) {
1922 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
1923 if (perm == PackageManager.PERMISSION_GRANTED) {
1924 return true;
1925 }
1926 if (checkAllowAppSwitchUid(callingUid)) {
1927 return true;
1928 }
1929 }
1930
1931 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
1932 return false;
1933 }
1934
1935 private boolean checkAllowAppSwitchUid(int uid) {
1936 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
1937 if (types != null) {
1938 for (int i = types.size() - 1; i >= 0; i--) {
1939 if (types.valueAt(i).intValue() == uid) {
1940 return true;
1941 }
1942 }
1943 }
1944 return false;
1945 }
1946
1947 @Override
1948 public void setActivityController(IActivityController controller, boolean imAMonkey) {
1949 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
1950 "setActivityController()");
1951 synchronized (mGlobalLock) {
1952 mController = controller;
1953 mControllerIsAMonkey = imAMonkey;
1954 Watchdog.getInstance().setActivityController(controller);
1955 }
1956 }
1957
1958 boolean isControllerAMonkey() {
1959 synchronized (mGlobalLock) {
1960 return mController != null && mControllerIsAMonkey;
1961 }
1962 }
1963
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 @Override
1965 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
1966 synchronized (mGlobalLock) {
1967 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
1968 }
1969 }
1970
1971 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001972 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
1973 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
1974 }
1975
1976 @Override
1977 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
1978 @WindowConfiguration.ActivityType int ignoreActivityType,
1979 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
1980 final int callingUid = Binder.getCallingUid();
1981 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
1982
1983 synchronized (mGlobalLock) {
1984 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
1985
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001986 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001987 callingUid);
1988 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
1989 ignoreWindowingMode, callingUid, allowed);
1990 }
1991
1992 return list;
1993 }
1994
1995 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
1997 synchronized (mGlobalLock) {
1998 final long origId = Binder.clearCallingIdentity();
1999 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2000 if (r != null) {
2001 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2002 }
2003 Binder.restoreCallingIdentity(origId);
2004 }
2005 }
2006
2007 @Override
2008 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 ActivityStack stack = ActivityRecord.getStackLocked(token);
2011 if (stack != null) {
2012 return stack.willActivityBeVisibleLocked(token);
2013 }
2014 return false;
2015 }
2016 }
2017
2018 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002019 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002020 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002021 synchronized (mGlobalLock) {
2022 final long ident = Binder.clearCallingIdentity();
2023 try {
2024 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2025 if (task == null) {
2026 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2027 return;
2028 }
2029
2030 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2031 + " to stackId=" + stackId + " toTop=" + toTop);
2032
2033 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2034 if (stack == null) {
2035 throw new IllegalStateException(
2036 "moveTaskToStack: No stack for stackId=" + stackId);
2037 }
2038 if (!stack.isActivityTypeStandardOrUndefined()) {
2039 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2040 + taskId + " to stack " + stackId);
2041 }
2042 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002043 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002044 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2045 }
2046 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2047 "moveTaskToStack");
2048 } finally {
2049 Binder.restoreCallingIdentity(ident);
2050 }
2051 }
2052 }
2053
2054 @Override
2055 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2056 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002057 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002058
2059 final long ident = Binder.clearCallingIdentity();
2060 try {
2061 synchronized (mGlobalLock) {
2062 if (animate) {
2063 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2064 if (stack == null) {
2065 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2066 return;
2067 }
2068 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2069 throw new IllegalArgumentException("Stack: " + stackId
2070 + " doesn't support animated resize.");
2071 }
2072 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2073 animationDuration, false /* fromFullscreen */);
2074 } else {
2075 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2076 if (stack == null) {
2077 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2078 return;
2079 }
2080 mStackSupervisor.resizeStackLocked(stack, destBounds,
2081 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2082 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2083 }
2084 }
2085 } finally {
2086 Binder.restoreCallingIdentity(ident);
2087 }
2088 }
2089
2090 /**
2091 * Moves the specified task to the primary-split-screen stack.
2092 *
2093 * @param taskId Id of task to move.
2094 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2095 * exist already. See
2096 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2097 * and
2098 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2099 * @param toTop If the task and stack should be moved to the top.
2100 * @param animate Whether we should play an animation for the moving the task.
2101 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2102 * stack. Pass {@code null} to use default bounds.
2103 * @param showRecents If the recents activity should be shown on the other side of the task
2104 * going into split-screen mode.
2105 */
2106 @Override
2107 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2108 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002109 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002110 "setTaskWindowingModeSplitScreenPrimary()");
2111 synchronized (mGlobalLock) {
2112 final long ident = Binder.clearCallingIdentity();
2113 try {
2114 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2115 if (task == null) {
2116 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2117 return false;
2118 }
2119 if (DEBUG_STACK) Slog.d(TAG_STACK,
2120 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2121 + " to createMode=" + createMode + " toTop=" + toTop);
2122 if (!task.isActivityTypeStandardOrUndefined()) {
2123 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2124 + " non-standard task " + taskId + " to split-screen windowing mode");
2125 }
2126
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002127 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002128 final int windowingMode = task.getWindowingMode();
2129 final ActivityStack stack = task.getStack();
2130 if (toTop) {
2131 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2132 }
2133 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2134 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2135 return windowingMode != task.getWindowingMode();
2136 } finally {
2137 Binder.restoreCallingIdentity(ident);
2138 }
2139 }
2140 }
2141
2142 /**
2143 * Removes stacks in the input windowing modes from the system if they are of activity type
2144 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2145 */
2146 @Override
2147 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002148 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002149 "removeStacksInWindowingModes()");
2150
2151 synchronized (mGlobalLock) {
2152 final long ident = Binder.clearCallingIdentity();
2153 try {
2154 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2155 } finally {
2156 Binder.restoreCallingIdentity(ident);
2157 }
2158 }
2159 }
2160
2161 @Override
2162 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002163 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002164 "removeStacksWithActivityTypes()");
2165
2166 synchronized (mGlobalLock) {
2167 final long ident = Binder.clearCallingIdentity();
2168 try {
2169 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2170 } finally {
2171 Binder.restoreCallingIdentity(ident);
2172 }
2173 }
2174 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175
2176 @Override
2177 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2178 int userId) {
2179 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002180 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2181 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002183 final boolean detailed = checkGetTasksPermission(
2184 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2185 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 == PackageManager.PERMISSION_GRANTED;
2187
2188 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002189 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 callingUid);
2191 }
2192 }
2193
2194 @Override
2195 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002196 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 long ident = Binder.clearCallingIdentity();
2198 try {
2199 synchronized (mGlobalLock) {
2200 return mStackSupervisor.getAllStackInfosLocked();
2201 }
2202 } finally {
2203 Binder.restoreCallingIdentity(ident);
2204 }
2205 }
2206
2207 @Override
2208 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002209 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 long ident = Binder.clearCallingIdentity();
2211 try {
2212 synchronized (mGlobalLock) {
2213 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2214 }
2215 } finally {
2216 Binder.restoreCallingIdentity(ident);
2217 }
2218 }
2219
2220 @Override
2221 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 final long callingUid = Binder.getCallingUid();
2224 final long origId = Binder.clearCallingIdentity();
2225 try {
2226 synchronized (mGlobalLock) {
2227 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2230 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2231 }
2232 } finally {
2233 Binder.restoreCallingIdentity(origId);
2234 }
2235 }
2236
2237 @Override
2238 public void startLockTaskModeByToken(IBinder token) {
2239 synchronized (mGlobalLock) {
2240 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2241 if (r == null) {
2242 return;
2243 }
2244 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2245 }
2246 }
2247
2248 @Override
2249 public void startSystemLockTaskMode(int taskId) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002250 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002251 // This makes inner call to look as if it was initiated by system.
2252 long ident = Binder.clearCallingIdentity();
2253 try {
2254 synchronized (mGlobalLock) {
2255 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2256
2257 // When starting lock task mode the stack must be in front and focused
2258 task.getStack().moveToFront("startSystemLockTaskMode");
2259 startLockTaskModeLocked(task, true /* isSystemCaller */);
2260 }
2261 } finally {
2262 Binder.restoreCallingIdentity(ident);
2263 }
2264 }
2265
2266 @Override
2267 public void stopLockTaskModeByToken(IBinder token) {
2268 synchronized (mGlobalLock) {
2269 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2270 if (r == null) {
2271 return;
2272 }
2273 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2274 }
2275 }
2276
2277 /**
2278 * This API should be called by SystemUI only when user perform certain action to dismiss
2279 * lock task mode. We should only dismiss pinned lock task mode in this case.
2280 */
2281 @Override
2282 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002283 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002284 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2285 }
2286
2287 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2288 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2289 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2290 return;
2291 }
2292
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002293 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 if (stack == null || task != stack.topTask()) {
2295 throw new IllegalArgumentException("Invalid task, not in foreground");
2296 }
2297
2298 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2299 // system or a specific app.
2300 // * System-initiated requests will only start the pinned mode (screen pinning)
2301 // * App-initiated requests
2302 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2303 // - will start the pinned mode, otherwise
2304 final int callingUid = Binder.getCallingUid();
2305 long ident = Binder.clearCallingIdentity();
2306 try {
2307 // When a task is locked, dismiss the pinned stack if it exists
2308 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2309
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002310 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 } finally {
2312 Binder.restoreCallingIdentity(ident);
2313 }
2314 }
2315
2316 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2317 final int callingUid = Binder.getCallingUid();
2318 long ident = Binder.clearCallingIdentity();
2319 try {
2320 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002321 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 }
2323 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2324 // task and jumping straight into a call in the case of emergency call back.
2325 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2326 if (tm != null) {
2327 tm.showInCallScreen(false);
2328 }
2329 } finally {
2330 Binder.restoreCallingIdentity(ident);
2331 }
2332 }
2333
2334 @Override
2335 public boolean isInLockTaskMode() {
2336 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2337 }
2338
2339 @Override
2340 public int getLockTaskModeState() {
2341 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002342 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343 }
2344 }
2345
2346 @Override
2347 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2348 synchronized (mGlobalLock) {
2349 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2350 if (r != null) {
2351 r.setTaskDescription(td);
2352 final TaskRecord task = r.getTask();
2353 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002354 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 }
2356 }
2357 }
2358
2359 @Override
2360 public Bundle getActivityOptions(IBinder token) {
2361 final long origId = Binder.clearCallingIdentity();
2362 try {
2363 synchronized (mGlobalLock) {
2364 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2365 if (r != null) {
2366 final ActivityOptions activityOptions = r.takeOptionsLocked();
2367 return activityOptions == null ? null : activityOptions.toBundle();
2368 }
2369 return null;
2370 }
2371 } finally {
2372 Binder.restoreCallingIdentity(origId);
2373 }
2374 }
2375
2376 @Override
2377 public List<IBinder> getAppTasks(String callingPackage) {
2378 int callingUid = Binder.getCallingUid();
2379 long ident = Binder.clearCallingIdentity();
2380 try {
2381 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002382 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 }
2384 } finally {
2385 Binder.restoreCallingIdentity(ident);
2386 }
2387 }
2388
2389 @Override
2390 public void finishVoiceTask(IVoiceInteractionSession session) {
2391 synchronized (mGlobalLock) {
2392 final long origId = Binder.clearCallingIdentity();
2393 try {
2394 // TODO: VI Consider treating local voice interactions and voice tasks
2395 // differently here
2396 mStackSupervisor.finishVoiceTask(session);
2397 } finally {
2398 Binder.restoreCallingIdentity(origId);
2399 }
2400 }
2401
2402 }
2403
2404 @Override
2405 public boolean isTopOfTask(IBinder token) {
2406 synchronized (mGlobalLock) {
2407 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2408 if (r == null) {
2409 throw new IllegalArgumentException();
2410 }
2411 return r.getTask().getTopActivity() == r;
2412 }
2413 }
2414
2415 @Override
2416 public void notifyLaunchTaskBehindComplete(IBinder token) {
2417 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2418 }
2419
2420 @Override
2421 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002422 mH.post(() -> {
2423 synchronized (mGlobalLock) {
2424 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002425 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002426 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002427 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002428 } catch (RemoteException e) {
2429 }
2430 }
2431 }
2432
2433 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002434 }
2435
2436 /** Called from an app when assist data is ready. */
2437 @Override
2438 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2439 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002440 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002441 synchronized (pae) {
2442 pae.result = extras;
2443 pae.structure = structure;
2444 pae.content = content;
2445 if (referrer != null) {
2446 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2447 }
2448 if (structure != null) {
2449 structure.setHomeActivity(pae.isHome);
2450 }
2451 pae.haveResult = true;
2452 pae.notifyAll();
2453 if (pae.intent == null && pae.receiver == null) {
2454 // Caller is just waiting for the result.
2455 return;
2456 }
2457 }
2458 // We are now ready to launch the assist activity.
2459 IAssistDataReceiver sendReceiver = null;
2460 Bundle sendBundle = null;
2461 synchronized (mGlobalLock) {
2462 buildAssistBundleLocked(pae, extras);
2463 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002464 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002465 if (!exists) {
2466 // Timed out.
2467 return;
2468 }
2469
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002470 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002471 // Caller wants result sent back to them.
2472 sendBundle = new Bundle();
2473 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2474 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2475 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2476 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2477 }
2478 }
2479 if (sendReceiver != null) {
2480 try {
2481 sendReceiver.onHandleAssistData(sendBundle);
2482 } catch (RemoteException e) {
2483 }
2484 return;
2485 }
2486
2487 final long ident = Binder.clearCallingIdentity();
2488 try {
2489 if (TextUtils.equals(pae.intent.getAction(),
2490 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2491 pae.intent.putExtras(pae.extras);
2492 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2493 } else {
2494 pae.intent.replaceExtras(pae.extras);
2495 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2496 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2497 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002498 mAmInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002499
2500 try {
2501 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2502 } catch (ActivityNotFoundException e) {
2503 Slog.w(TAG, "No activity to handle assist action.", e);
2504 }
2505 }
2506 } finally {
2507 Binder.restoreCallingIdentity(ident);
2508 }
2509 }
2510
2511 @Override
2512 public int addAppTask(IBinder activityToken, Intent intent,
2513 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2514 final int callingUid = Binder.getCallingUid();
2515 final long callingIdent = Binder.clearCallingIdentity();
2516
2517 try {
2518 synchronized (mGlobalLock) {
2519 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2520 if (r == null) {
2521 throw new IllegalArgumentException("Activity does not exist; token="
2522 + activityToken);
2523 }
2524 ComponentName comp = intent.getComponent();
2525 if (comp == null) {
2526 throw new IllegalArgumentException("Intent " + intent
2527 + " must specify explicit component");
2528 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 if (thumbnail.getWidth() != mThumbnailWidth
2530 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002531 throw new IllegalArgumentException("Bad thumbnail size: got "
2532 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002533 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 }
2535 if (intent.getSelector() != null) {
2536 intent.setSelector(null);
2537 }
2538 if (intent.getSourceBounds() != null) {
2539 intent.setSourceBounds(null);
2540 }
2541 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2542 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2543 // The caller has added this as an auto-remove task... that makes no
2544 // sense, so turn off auto-remove.
2545 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2546 }
2547 }
2548 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2549 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2550 if (ainfo.applicationInfo.uid != callingUid) {
2551 throw new SecurityException(
2552 "Can't add task for another application: target uid="
2553 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2554 }
2555
2556 final ActivityStack stack = r.getStack();
2557 final TaskRecord task = stack.createTaskRecord(
2558 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2559 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002560 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002561 // The app has too many tasks already and we can't add any more
2562 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2563 return INVALID_TASK_ID;
2564 }
2565 task.lastTaskDescription.copyFrom(description);
2566
2567 // TODO: Send the thumbnail to WM to store it.
2568
2569 return task.taskId;
2570 }
2571 } finally {
2572 Binder.restoreCallingIdentity(callingIdent);
2573 }
2574 }
2575
2576 @Override
2577 public Point getAppTaskThumbnailSize() {
2578 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002579 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002580 }
2581 }
2582
2583 @Override
2584 public void setTaskResizeable(int taskId, int resizeableMode) {
2585 synchronized (mGlobalLock) {
2586 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2587 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2588 if (task == null) {
2589 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2590 return;
2591 }
2592 task.setResizeMode(resizeableMode);
2593 }
2594 }
2595
2596 @Override
2597 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 long ident = Binder.clearCallingIdentity();
2600 try {
2601 synchronized (mGlobalLock) {
2602 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2603 if (task == null) {
2604 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2605 return;
2606 }
2607 // Place the task in the right stack if it isn't there already based on
2608 // the requested bounds.
2609 // The stack transition logic is:
2610 // - a null bounds on a freeform task moves that task to fullscreen
2611 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2612 // that task to freeform
2613 // - otherwise the task is not moved
2614 ActivityStack stack = task.getStack();
2615 if (!task.getWindowConfiguration().canResizeTask()) {
2616 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2617 }
2618 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2619 stack = stack.getDisplay().getOrCreateStack(
2620 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2621 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2622 stack = stack.getDisplay().getOrCreateStack(
2623 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2624 }
2625
2626 // Reparent the task to the right stack if necessary
2627 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2628 if (stack != task.getStack()) {
2629 // Defer resume until the task is resized below
2630 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2631 DEFER_RESUME, "resizeTask");
2632 preserveWindow = false;
2633 }
2634
2635 // After reparenting (which only resizes the task to the stack bounds), resize the
2636 // task to the actual bounds provided
2637 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2638 }
2639 } finally {
2640 Binder.restoreCallingIdentity(ident);
2641 }
2642 }
2643
2644 @Override
2645 public boolean releaseActivityInstance(IBinder token) {
2646 synchronized (mGlobalLock) {
2647 final long origId = Binder.clearCallingIdentity();
2648 try {
2649 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2650 if (r == null) {
2651 return false;
2652 }
2653 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2654 } finally {
2655 Binder.restoreCallingIdentity(origId);
2656 }
2657 }
2658 }
2659
2660 @Override
2661 public void releaseSomeActivities(IApplicationThread appInt) {
2662 synchronized (mGlobalLock) {
2663 final long origId = Binder.clearCallingIdentity();
2664 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002665 WindowProcessController app =
2666 mAm.getRecordForAppLocked(appInt).getWindowProcessController();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002667 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2668 } finally {
2669 Binder.restoreCallingIdentity(origId);
2670 }
2671 }
2672 }
2673
2674 @Override
2675 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
2676 int secondaryDisplayShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002677 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 != PackageManager.PERMISSION_GRANTED) {
2679 throw new SecurityException("Requires permission "
2680 + android.Manifest.permission.DEVICE_POWER);
2681 }
2682
2683 synchronized (mGlobalLock) {
2684 long ident = Binder.clearCallingIdentity();
2685 if (mKeyguardShown != keyguardShowing) {
2686 mKeyguardShown = keyguardShowing;
2687 reportCurKeyguardUsageEventLocked(keyguardShowing);
2688 }
2689 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002690 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002691 secondaryDisplayShowing);
2692 } finally {
2693 Binder.restoreCallingIdentity(ident);
2694 }
2695 }
2696
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002697 mH.post(() -> {
2698 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2699 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2700 }
2701 });
2702 }
2703
2704 void onScreenAwakeChanged(boolean isAwake) {
2705 mH.post(() -> {
2706 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2707 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2708 }
2709 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002710 }
2711
2712 @Override
2713 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2715 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002716
2717 final File passedIconFile = new File(filePath);
2718 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2719 passedIconFile.getName());
2720 if (!legitIconFile.getPath().equals(filePath)
2721 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2722 throw new IllegalArgumentException("Bad file path: " + filePath
2723 + " passed for userId " + userId);
2724 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002725 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002726 }
2727
2728 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002729 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002730 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2731 final ActivityOptions activityOptions = safeOptions != null
2732 ? safeOptions.getOptions(mStackSupervisor)
2733 : null;
2734 if (activityOptions == null
2735 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2736 || activityOptions.getCustomInPlaceResId() == 0) {
2737 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2738 "with valid animation");
2739 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2741 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002742 activityOptions.getCustomInPlaceResId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002743 mWindowManager.executeAppTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744 }
2745
2746 @Override
2747 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002748 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002749 synchronized (mGlobalLock) {
2750 final long ident = Binder.clearCallingIdentity();
2751 try {
2752 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2753 if (stack == null) {
2754 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2755 return;
2756 }
2757 if (!stack.isActivityTypeStandardOrUndefined()) {
2758 throw new IllegalArgumentException(
2759 "Removing non-standard stack is not allowed.");
2760 }
2761 mStackSupervisor.removeStack(stack);
2762 } finally {
2763 Binder.restoreCallingIdentity(ident);
2764 }
2765 }
2766 }
2767
2768 @Override
2769 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002770 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771
2772 synchronized (mGlobalLock) {
2773 final long ident = Binder.clearCallingIdentity();
2774 try {
2775 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
2776 + " to displayId=" + displayId);
2777 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
2778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782 }
2783
2784 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002785 public void exitFreeformMode(IBinder token) {
2786 synchronized (mGlobalLock) {
2787 long ident = Binder.clearCallingIdentity();
2788 try {
2789 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2790 if (r == null) {
2791 throw new IllegalArgumentException(
2792 "exitFreeformMode: No activity record matching token=" + token);
2793 }
2794
2795 final ActivityStack stack = r.getStack();
2796 if (stack == null || !stack.inFreeformWindowingMode()) {
2797 throw new IllegalStateException(
2798 "exitFreeformMode: You can only go fullscreen from freeform.");
2799 }
2800
2801 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
2802 } finally {
2803 Binder.restoreCallingIdentity(ident);
2804 }
2805 }
2806 }
2807
2808 /** Sets the task stack listener that gets callbacks when a task stack changes. */
2809 @Override
2810 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002811 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002813 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 }
2815
2816 /** Unregister a task stack listener so that it stops receiving callbacks. */
2817 @Override
2818 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002819 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002820 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002821 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 }
2823
2824 private void reportCurKeyguardUsageEventLocked(boolean keyguardShowing) {
2825 mAm.reportGlobalUsageEventLocked(keyguardShowing
2826 ? UsageEvents.Event.KEYGUARD_SHOWN
2827 : UsageEvents.Event.KEYGUARD_HIDDEN);
2828 }
2829
2830 @Override
2831 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
2832 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
2833 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
2834 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
2835 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
2836 }
2837
2838 @Override
2839 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
2840 IBinder activityToken, int flags) {
2841 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
2842 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
2843 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
2844 }
2845
2846 @Override
2847 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
2848 Bundle args) {
2849 return enqueueAssistContext(requestType, intent, hint, null, null, null,
2850 true /* focused */, true /* newSessionId */, userHandle, args,
2851 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
2852 }
2853
2854 @Override
2855 public Bundle getAssistContextExtras(int requestType) {
2856 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
2857 null, null, true /* focused */, true /* newSessionId */,
2858 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
2859 if (pae == null) {
2860 return null;
2861 }
2862 synchronized (pae) {
2863 while (!pae.haveResult) {
2864 try {
2865 pae.wait();
2866 } catch (InterruptedException e) {
2867 }
2868 }
2869 }
2870 synchronized (mGlobalLock) {
2871 buildAssistBundleLocked(pae, pae.result);
2872 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002873 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 }
2875 return pae.extras;
2876 }
2877
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002878 /**
2879 * Binder IPC calls go through the public entry point.
2880 * This can be called with or without the global lock held.
2881 */
2882 private static int checkCallingPermission(String permission) {
2883 return checkPermission(
2884 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
2885 }
2886
2887 /** This can be called with or without the global lock held. */
2888 void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
2889 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
2890 mAmInternal.enforceCallingPermission(permission, func);
2891 }
2892 }
2893
2894 @VisibleForTesting
2895 int checkGetTasksPermission(String permission, int pid, int uid) {
2896 return checkPermission(permission, pid, uid);
2897 }
2898
2899 static int checkPermission(String permission, int pid, int uid) {
2900 if (permission == null) {
2901 return PackageManager.PERMISSION_DENIED;
2902 }
2903 return checkComponentPermission(permission, pid, uid, -1, true);
2904 }
2905
2906 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
2907 if (getRecentTasks().isCallerRecents(callingUid)) {
2908 // Always allow the recents component to get tasks
2909 return true;
2910 }
2911
2912 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
2913 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2914 if (!allowed) {
2915 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
2916 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
2917 // Temporary compatibility: some existing apps on the system image may
2918 // still be requesting the old permission and not switched to the new
2919 // one; if so, we'll still allow them full access. This means we need
2920 // to see if they are holding the old permission and are a system app.
2921 try {
2922 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
2923 allowed = true;
2924 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2925 + " is using old GET_TASKS but privileged; allowing");
2926 }
2927 } catch (RemoteException e) {
2928 }
2929 }
2930 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2931 + " does not hold REAL_GET_TASKS; limiting output");
2932 }
2933 return allowed;
2934 }
2935
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
2937 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
2938 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
2939 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002940 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 "enqueueAssistContext()");
2942
2943 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002944 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 if (activity == null) {
2946 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
2947 return null;
2948 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002949 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
2951 return null;
2952 }
2953 if (focused) {
2954 if (activityToken != null) {
2955 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
2956 if (activity != caller) {
2957 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
2958 + " is not current top " + activity);
2959 return null;
2960 }
2961 }
2962 } else {
2963 activity = ActivityRecord.forTokenLocked(activityToken);
2964 if (activity == null) {
2965 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
2966 + " couldn't be found");
2967 return null;
2968 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002969 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
2971 return null;
2972 }
2973 }
2974
2975 PendingAssistExtras pae;
2976 Bundle extras = new Bundle();
2977 if (args != null) {
2978 extras.putAll(args);
2979 }
2980 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002981 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982
2983 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
2984 userHandle);
2985 pae.isHome = activity.isActivityTypeHome();
2986
2987 // Increment the sessionId if necessary
2988 if (newSessionId) {
2989 mViSessionId++;
2990 }
2991 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002992 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
2993 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002995 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 } catch (RemoteException e) {
2997 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
2998 return null;
2999 }
3000 return pae;
3001 }
3002 }
3003
3004 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3005 if (result != null) {
3006 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3007 }
3008 if (pae.hint != null) {
3009 pae.extras.putBoolean(pae.hint, true);
3010 }
3011 }
3012
3013 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3014 IAssistDataReceiver receiver;
3015 synchronized (mGlobalLock) {
3016 mPendingAssistExtras.remove(pae);
3017 receiver = pae.receiver;
3018 }
3019 if (receiver != null) {
3020 // Caller wants result sent back to them.
3021 Bundle sendBundle = new Bundle();
3022 // At least return the receiver extras
3023 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3024 try {
3025 pae.receiver.onHandleAssistData(sendBundle);
3026 } catch (RemoteException e) {
3027 }
3028 }
3029 }
3030
3031 public class PendingAssistExtras extends Binder implements Runnable {
3032 public final ActivityRecord activity;
3033 public boolean isHome;
3034 public final Bundle extras;
3035 public final Intent intent;
3036 public final String hint;
3037 public final IAssistDataReceiver receiver;
3038 public final int userHandle;
3039 public boolean haveResult = false;
3040 public Bundle result = null;
3041 public AssistStructure structure = null;
3042 public AssistContent content = null;
3043 public Bundle receiverExtras;
3044
3045 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3046 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3047 int _userHandle) {
3048 activity = _activity;
3049 extras = _extras;
3050 intent = _intent;
3051 hint = _hint;
3052 receiver = _receiver;
3053 receiverExtras = _receiverExtras;
3054 userHandle = _userHandle;
3055 }
3056
3057 @Override
3058 public void run() {
3059 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3060 synchronized (this) {
3061 haveResult = true;
3062 notifyAll();
3063 }
3064 pendingAssistExtrasTimedOut(this);
3065 }
3066 }
3067
3068 @Override
3069 public boolean isAssistDataAllowedOnCurrentActivity() {
3070 int userId;
3071 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003072 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3074 return false;
3075 }
3076
3077 final ActivityRecord activity = focusedStack.getTopActivity();
3078 if (activity == null) {
3079 return false;
3080 }
3081 userId = activity.userId;
3082 }
3083 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3084 }
3085
3086 @Override
3087 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3088 long ident = Binder.clearCallingIdentity();
3089 try {
3090 synchronized (mGlobalLock) {
3091 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003092 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093 if (top != caller) {
3094 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3095 + " is not current top " + top);
3096 return false;
3097 }
3098 if (!top.nowVisible) {
3099 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3100 + " is not visible");
3101 return false;
3102 }
3103 }
3104 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3105 token);
3106 } finally {
3107 Binder.restoreCallingIdentity(ident);
3108 }
3109 }
3110
3111 @Override
3112 public boolean isRootVoiceInteraction(IBinder token) {
3113 synchronized (mGlobalLock) {
3114 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3115 if (r == null) {
3116 return false;
3117 }
3118 return r.rootVoiceInteraction;
3119 }
3120 }
3121
Wale Ogunwalef6733932018-06-27 05:14:34 -07003122 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3123 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3124 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3125 if (activityToCallback == null) return;
3126 activityToCallback.setVoiceSessionLocked(voiceSession);
3127
3128 // Inform the activity
3129 try {
3130 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3131 voiceInteractor);
3132 long token = Binder.clearCallingIdentity();
3133 try {
3134 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3135 } finally {
3136 Binder.restoreCallingIdentity(token);
3137 }
3138 // TODO: VI Should we cache the activity so that it's easier to find later
3139 // rather than scan through all the stacks and activities?
3140 } catch (RemoteException re) {
3141 activityToCallback.clearVoiceSessionLocked();
3142 // TODO: VI Should this terminate the voice session?
3143 }
3144 }
3145
3146 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3147 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3148 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3149 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3150 boolean wasRunningVoice = mRunningVoice != null;
3151 mRunningVoice = session;
3152 if (!wasRunningVoice) {
3153 mVoiceWakeLock.acquire();
3154 updateSleepIfNeededLocked();
3155 }
3156 }
3157 }
3158
3159 void finishRunningVoiceLocked() {
3160 if (mRunningVoice != null) {
3161 mRunningVoice = null;
3162 mVoiceWakeLock.release();
3163 updateSleepIfNeededLocked();
3164 }
3165 }
3166
3167 @Override
3168 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3169 synchronized (mGlobalLock) {
3170 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3171 if (keepAwake) {
3172 mVoiceWakeLock.acquire();
3173 } else {
3174 mVoiceWakeLock.release();
3175 }
3176 }
3177 }
3178 }
3179
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 @Override
3181 public ComponentName getActivityClassForToken(IBinder token) {
3182 synchronized (mGlobalLock) {
3183 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3184 if (r == null) {
3185 return null;
3186 }
3187 return r.intent.getComponent();
3188 }
3189 }
3190
3191 @Override
3192 public String getPackageForToken(IBinder token) {
3193 synchronized (mGlobalLock) {
3194 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3195 if (r == null) {
3196 return null;
3197 }
3198 return r.packageName;
3199 }
3200 }
3201
3202 @Override
3203 public void showLockTaskEscapeMessage(IBinder token) {
3204 synchronized (mGlobalLock) {
3205 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3206 if (r == null) {
3207 return;
3208 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003209 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 }
3211 }
3212
3213 @Override
3214 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003215 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 final long token = Binder.clearCallingIdentity();
3217 try {
3218 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003219 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 }
3221 } finally {
3222 Binder.restoreCallingIdentity(token);
3223 }
3224 }
3225
3226 /**
3227 * Try to place task to provided position. The final position might be different depending on
3228 * current user and stacks state. The task will be moved to target stack if it's currently in
3229 * different stack.
3230 */
3231 @Override
3232 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003233 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 synchronized (mGlobalLock) {
3235 long ident = Binder.clearCallingIdentity();
3236 try {
3237 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3238 + taskId + " in stackId=" + stackId + " at position=" + position);
3239 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3240 if (task == null) {
3241 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3242 + taskId);
3243 }
3244
3245 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3246
3247 if (stack == null) {
3248 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3249 + stackId);
3250 }
3251 if (!stack.isActivityTypeStandardOrUndefined()) {
3252 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3253 + " the position of task " + taskId + " in/to non-standard stack");
3254 }
3255
3256 // TODO: Have the callers of this API call a separate reparent method if that is
3257 // what they intended to do vs. having this method also do reparenting.
3258 if (task.getStack() == stack) {
3259 // Change position in current stack.
3260 stack.positionChildAt(task, position);
3261 } else {
3262 // Reparent to new stack.
3263 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3264 !DEFER_RESUME, "positionTaskInStack");
3265 }
3266 } finally {
3267 Binder.restoreCallingIdentity(ident);
3268 }
3269 }
3270 }
3271
3272 @Override
3273 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3274 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3275 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3276 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3277 synchronized (mGlobalLock) {
3278 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3279 if (record == null) {
3280 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3281 + "found for: " + token);
3282 }
3283 record.setSizeConfigurations(horizontalSizeConfiguration,
3284 verticalSizeConfigurations, smallestSizeConfigurations);
3285 }
3286 }
3287
3288 /**
3289 * Dismisses split-screen multi-window mode.
3290 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3291 */
3292 @Override
3293 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003294 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3296 final long ident = Binder.clearCallingIdentity();
3297 try {
3298 synchronized (mGlobalLock) {
3299 final ActivityStack stack =
3300 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3301 if (stack == null) {
3302 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3303 return;
3304 }
3305
3306 if (toTop) {
3307 // Caller wants the current split-screen primary stack to be the top stack after
3308 // it goes fullscreen, so move it to the front.
3309 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003310 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311 // In this case the current split-screen primary stack shouldn't be the top
3312 // stack after it goes fullscreen, but it current has focus, so we move the
3313 // focus to the top-most split-screen secondary stack next to it.
3314 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3315 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3316 if (otherStack != null) {
3317 otherStack.moveToFront("dismissSplitScreenMode_other");
3318 }
3319 }
3320
3321 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3322 }
3323 } finally {
3324 Binder.restoreCallingIdentity(ident);
3325 }
3326 }
3327
3328 /**
3329 * Dismisses Pip
3330 * @param animate True if the dismissal should be animated.
3331 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3332 * default animation duration should be used.
3333 */
3334 @Override
3335 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003336 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 final long ident = Binder.clearCallingIdentity();
3338 try {
3339 synchronized (mGlobalLock) {
3340 final PinnedActivityStack stack =
3341 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3342 if (stack == null) {
3343 Slog.w(TAG, "dismissPip: pinned stack not found.");
3344 return;
3345 }
3346 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3347 throw new IllegalArgumentException("Stack: " + stack
3348 + " doesn't support animated resize.");
3349 }
3350 if (animate) {
3351 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3352 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3353 } else {
3354 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3355 }
3356 }
3357 } finally {
3358 Binder.restoreCallingIdentity(ident);
3359 }
3360 }
3361
3362 @Override
3363 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003364 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 synchronized (mGlobalLock) {
3366 mSuppressResizeConfigChanges = suppress;
3367 }
3368 }
3369
3370 /**
3371 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3372 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3373 * activity and clearing the task at the same time.
3374 */
3375 @Override
3376 // TODO: API should just be about changing windowing modes...
3377 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003378 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 "moveTasksToFullscreenStack()");
3380 synchronized (mGlobalLock) {
3381 final long origId = Binder.clearCallingIdentity();
3382 try {
3383 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3384 if (stack != null){
3385 if (!stack.isActivityTypeStandardOrUndefined()) {
3386 throw new IllegalArgumentException(
3387 "You can't move tasks from non-standard stacks.");
3388 }
3389 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3390 }
3391 } finally {
3392 Binder.restoreCallingIdentity(origId);
3393 }
3394 }
3395 }
3396
3397 /**
3398 * Moves the top activity in the input stackId to the pinned stack.
3399 *
3400 * @param stackId Id of stack to move the top activity to pinned stack.
3401 * @param bounds Bounds to use for pinned stack.
3402 *
3403 * @return True if the top activity of the input stack was successfully moved to the pinned
3404 * stack.
3405 */
3406 @Override
3407 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409 "moveTopActivityToPinnedStack()");
3410 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003411 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3413 + "Device doesn't support picture-in-picture mode");
3414 }
3415
3416 long ident = Binder.clearCallingIdentity();
3417 try {
3418 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3419 } finally {
3420 Binder.restoreCallingIdentity(ident);
3421 }
3422 }
3423 }
3424
3425 @Override
3426 public boolean isInMultiWindowMode(IBinder token) {
3427 final long origId = Binder.clearCallingIdentity();
3428 try {
3429 synchronized (mGlobalLock) {
3430 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3431 if (r == null) {
3432 return false;
3433 }
3434 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3435 return r.inMultiWindowMode();
3436 }
3437 } finally {
3438 Binder.restoreCallingIdentity(origId);
3439 }
3440 }
3441
3442 @Override
3443 public boolean isInPictureInPictureMode(IBinder token) {
3444 final long origId = Binder.clearCallingIdentity();
3445 try {
3446 synchronized (mGlobalLock) {
3447 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3448 }
3449 } finally {
3450 Binder.restoreCallingIdentity(origId);
3451 }
3452 }
3453
3454 private boolean isInPictureInPictureMode(ActivityRecord r) {
3455 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3456 || r.getStack().isInStackLocked(r) == null) {
3457 return false;
3458 }
3459
3460 // If we are animating to fullscreen then we have already dispatched the PIP mode
3461 // changed, so we should reflect that check here as well.
3462 final PinnedActivityStack stack = r.getStack();
3463 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3464 return !windowController.isAnimatingBoundsToFullscreen();
3465 }
3466
3467 @Override
3468 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3469 final long origId = Binder.clearCallingIdentity();
3470 try {
3471 synchronized (mGlobalLock) {
3472 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3473 "enterPictureInPictureMode", token, params);
3474
3475 // If the activity is already in picture in picture mode, then just return early
3476 if (isInPictureInPictureMode(r)) {
3477 return true;
3478 }
3479
3480 // Activity supports picture-in-picture, now check that we can enter PiP at this
3481 // point, if it is
3482 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3483 false /* beforeStopping */)) {
3484 return false;
3485 }
3486
3487 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003488 synchronized (mGlobalLock) {
3489 // Only update the saved args from the args that are set
3490 r.pictureInPictureArgs.copyOnlySet(params);
3491 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3492 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3493 // Adjust the source bounds by the insets for the transition down
3494 final Rect sourceBounds = new Rect(
3495 r.pictureInPictureArgs.getSourceRectHint());
3496 mStackSupervisor.moveActivityToPinnedStackLocked(
3497 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3498 final PinnedActivityStack stack = r.getStack();
3499 stack.setPictureInPictureAspectRatio(aspectRatio);
3500 stack.setPictureInPictureActions(actions);
3501 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3502 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3503 logPictureInPictureArgs(params);
3504 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 };
3506
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003507 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 // If the keyguard is showing or occluded, then try and dismiss it before
3509 // entering picture-in-picture (this will prompt the user to authenticate if the
3510 // device is currently locked).
3511 dismissKeyguard(token, new KeyguardDismissCallback() {
3512 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003513 public void onDismissSucceeded() {
3514 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 }
3516 }, null /* message */);
3517 } else {
3518 // Enter picture in picture immediately otherwise
3519 enterPipRunnable.run();
3520 }
3521 return true;
3522 }
3523 } finally {
3524 Binder.restoreCallingIdentity(origId);
3525 }
3526 }
3527
3528 @Override
3529 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3530 final long origId = Binder.clearCallingIdentity();
3531 try {
3532 synchronized (mGlobalLock) {
3533 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3534 "setPictureInPictureParams", token, params);
3535
3536 // Only update the saved args from the args that are set
3537 r.pictureInPictureArgs.copyOnlySet(params);
3538 if (r.inPinnedWindowingMode()) {
3539 // If the activity is already in picture-in-picture, update the pinned stack now
3540 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3541 // be used the next time the activity enters PiP
3542 final PinnedActivityStack stack = r.getStack();
3543 if (!stack.isAnimatingBoundsToFullscreen()) {
3544 stack.setPictureInPictureAspectRatio(
3545 r.pictureInPictureArgs.getAspectRatio());
3546 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3547 }
3548 }
3549 logPictureInPictureArgs(params);
3550 }
3551 } finally {
3552 Binder.restoreCallingIdentity(origId);
3553 }
3554 }
3555
3556 @Override
3557 public int getMaxNumPictureInPictureActions(IBinder token) {
3558 // Currently, this is a static constant, but later, we may change this to be dependent on
3559 // the context of the activity
3560 return 3;
3561 }
3562
3563 private void logPictureInPictureArgs(PictureInPictureParams params) {
3564 if (params.hasSetActions()) {
3565 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3566 params.getActions().size());
3567 }
3568 if (params.hasSetAspectRatio()) {
3569 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3570 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3571 MetricsLogger.action(lm);
3572 }
3573 }
3574
3575 /**
3576 * Checks the state of the system and the activity associated with the given {@param token} to
3577 * verify that picture-in-picture is supported for that activity.
3578 *
3579 * @return the activity record for the given {@param token} if all the checks pass.
3580 */
3581 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3582 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003583 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003584 throw new IllegalStateException(caller
3585 + ": Device doesn't support picture-in-picture mode.");
3586 }
3587
3588 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3589 if (r == null) {
3590 throw new IllegalStateException(caller
3591 + ": Can't find activity for token=" + token);
3592 }
3593
3594 if (!r.supportsPictureInPicture()) {
3595 throw new IllegalStateException(caller
3596 + ": Current activity does not support picture-in-picture.");
3597 }
3598
3599 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003600 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 params.getAspectRatio())) {
3602 final float minAspectRatio = mContext.getResources().getFloat(
3603 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3604 final float maxAspectRatio = mContext.getResources().getFloat(
3605 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3606 throw new IllegalArgumentException(String.format(caller
3607 + ": Aspect ratio is too extreme (must be between %f and %f).",
3608 minAspectRatio, maxAspectRatio));
3609 }
3610
3611 // Truncate the number of actions if necessary
3612 params.truncateActions(getMaxNumPictureInPictureActions(token));
3613
3614 return r;
3615 }
3616
3617 @Override
3618 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003619 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 synchronized (mGlobalLock) {
3621 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3622 if (r == null) {
3623 throw new IllegalArgumentException("Activity does not exist; token="
3624 + activityToken);
3625 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003626 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003627 }
3628 }
3629
3630 @Override
3631 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3632 Rect tempDockedTaskInsetBounds,
3633 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003634 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003635 long ident = Binder.clearCallingIdentity();
3636 try {
3637 synchronized (mGlobalLock) {
3638 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3639 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3640 PRESERVE_WINDOWS);
3641 }
3642 } finally {
3643 Binder.restoreCallingIdentity(ident);
3644 }
3645 }
3646
3647 @Override
3648 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003649 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 final long ident = Binder.clearCallingIdentity();
3651 try {
3652 synchronized (mGlobalLock) {
3653 mStackSupervisor.setSplitScreenResizing(resizing);
3654 }
3655 } finally {
3656 Binder.restoreCallingIdentity(ident);
3657 }
3658 }
3659
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003660 /**
3661 * Check that we have the features required for VR-related API calls, and throw an exception if
3662 * not.
3663 */
3664 void enforceSystemHasVrFeature() {
3665 if (!mContext.getPackageManager().hasSystemFeature(
3666 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3667 throw new UnsupportedOperationException("VR mode not supported on this device!");
3668 }
3669 }
3670
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 @Override
3672 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003673 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003674
3675 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3676
3677 ActivityRecord r;
3678 synchronized (mGlobalLock) {
3679 r = ActivityRecord.isInStackLocked(token);
3680 }
3681
3682 if (r == null) {
3683 throw new IllegalArgumentException();
3684 }
3685
3686 int err;
3687 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3688 VrManagerInternal.NO_ERROR) {
3689 return err;
3690 }
3691
3692 // Clear the binder calling uid since this path may call moveToTask().
3693 final long callingId = Binder.clearCallingIdentity();
3694 try {
3695 synchronized (mGlobalLock) {
3696 r.requestedVrComponent = (enabled) ? packageName : null;
3697
3698 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003699 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003700 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003701 }
3702 return 0;
3703 }
3704 } finally {
3705 Binder.restoreCallingIdentity(callingId);
3706 }
3707 }
3708
3709 @Override
3710 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3711 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3712 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003713 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003714 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3715 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3716 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003717 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718 || activity.voiceSession != null) {
3719 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3720 return;
3721 }
3722 if (activity.pendingVoiceInteractionStart) {
3723 Slog.w(TAG, "Pending start of voice interaction already.");
3724 return;
3725 }
3726 activity.pendingVoiceInteractionStart = true;
3727 }
3728 LocalServices.getService(VoiceInteractionManagerInternal.class)
3729 .startLocalVoiceInteraction(callingActivity, options);
3730 }
3731
3732 @Override
3733 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3734 LocalServices.getService(VoiceInteractionManagerInternal.class)
3735 .stopLocalVoiceInteraction(callingActivity);
3736 }
3737
3738 @Override
3739 public boolean supportsLocalVoiceInteraction() {
3740 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3741 .supportsLocalVoiceInteraction();
3742 }
3743
3744 /** Notifies all listeners when the pinned stack animation starts. */
3745 @Override
3746 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003747 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 }
3749
3750 /** Notifies all listeners when the pinned stack animation ends. */
3751 @Override
3752 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003753 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003754 }
3755
3756 @Override
3757 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003758 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003759 final long ident = Binder.clearCallingIdentity();
3760 try {
3761 synchronized (mGlobalLock) {
3762 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3763 }
3764 } finally {
3765 Binder.restoreCallingIdentity(ident);
3766 }
3767 }
3768
3769 @Override
3770 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003771 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003772
3773 synchronized (mGlobalLock) {
3774 // Check if display is initialized in AM.
3775 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3776 // Call might come when display is not yet added or has already been removed.
3777 if (DEBUG_CONFIGURATION) {
3778 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
3779 + displayId);
3780 }
3781 return false;
3782 }
3783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003784 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003786 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003787 }
3788
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003789 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003790 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003791 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 }
3793
3794 final long origId = Binder.clearCallingIdentity();
3795 try {
3796 if (values != null) {
3797 Settings.System.clearConfiguration(values);
3798 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003799 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003800 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
3801 return mTmpUpdateConfigurationResult.changes != 0;
3802 } finally {
3803 Binder.restoreCallingIdentity(origId);
3804 }
3805 }
3806 }
3807
3808 @Override
3809 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003810 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003811
3812 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003813 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003814 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003815 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 }
3817
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003818 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003819 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003820 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 }
3822
3823 final long origId = Binder.clearCallingIdentity();
3824 try {
3825 if (values != null) {
3826 Settings.System.clearConfiguration(values);
3827 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003828 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 UserHandle.USER_NULL, false /* deferResume */,
3830 mTmpUpdateConfigurationResult);
3831 return mTmpUpdateConfigurationResult.changes != 0;
3832 } finally {
3833 Binder.restoreCallingIdentity(origId);
3834 }
3835 }
3836 }
3837
3838 @Override
3839 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
3840 CharSequence message) {
3841 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003842 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
3844 }
3845 final long callingId = Binder.clearCallingIdentity();
3846 try {
3847 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003848 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003849 }
3850 } finally {
3851 Binder.restoreCallingIdentity(callingId);
3852 }
3853 }
3854
3855 @Override
3856 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003857 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 "cancelTaskWindowTransition()");
3859 final long ident = Binder.clearCallingIdentity();
3860 try {
3861 synchronized (mGlobalLock) {
3862 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
3863 MATCH_TASK_IN_STACKS_ONLY);
3864 if (task == null) {
3865 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
3866 return;
3867 }
3868 task.cancelWindowTransition();
3869 }
3870 } finally {
3871 Binder.restoreCallingIdentity(ident);
3872 }
3873 }
3874
3875 @Override
3876 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003877 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 final long ident = Binder.clearCallingIdentity();
3879 try {
3880 final TaskRecord task;
3881 synchronized (mGlobalLock) {
3882 task = mStackSupervisor.anyTaskForIdLocked(taskId,
3883 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3884 if (task == null) {
3885 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
3886 return null;
3887 }
3888 }
3889 // Don't call this while holding the lock as this operation might hit the disk.
3890 return task.getSnapshot(reducedResolution);
3891 } finally {
3892 Binder.restoreCallingIdentity(ident);
3893 }
3894 }
3895
3896 @Override
3897 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
3898 synchronized (mGlobalLock) {
3899 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3900 if (r == null) {
3901 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
3902 + token);
3903 return;
3904 }
3905 final long origId = Binder.clearCallingIdentity();
3906 try {
3907 r.setDisablePreviewScreenshots(disable);
3908 } finally {
3909 Binder.restoreCallingIdentity(origId);
3910 }
3911 }
3912 }
3913
3914 /** Return the user id of the last resumed activity. */
3915 @Override
3916 public @UserIdInt
3917 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003918 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
3920 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07003921 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003924 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 }
3926 }
3927
3928 @Override
3929 public void updateLockTaskFeatures(int userId, int flags) {
3930 final int callingUid = Binder.getCallingUid();
3931 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003932 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 "updateLockTaskFeatures()");
3934 }
3935 synchronized (mGlobalLock) {
3936 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
3937 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003938 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003939 }
3940 }
3941
3942 @Override
3943 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
3944 synchronized (mGlobalLock) {
3945 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3946 if (r == null) {
3947 return;
3948 }
3949 final long origId = Binder.clearCallingIdentity();
3950 try {
3951 r.setShowWhenLocked(showWhenLocked);
3952 } finally {
3953 Binder.restoreCallingIdentity(origId);
3954 }
3955 }
3956 }
3957
3958 @Override
3959 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
3960 synchronized (mGlobalLock) {
3961 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3962 if (r == null) {
3963 return;
3964 }
3965 final long origId = Binder.clearCallingIdentity();
3966 try {
3967 r.setTurnScreenOn(turnScreenOn);
3968 } finally {
3969 Binder.restoreCallingIdentity(origId);
3970 }
3971 }
3972 }
3973
3974 @Override
3975 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003976 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 "registerRemoteAnimations");
3978 definition.setCallingPid(Binder.getCallingPid());
3979 synchronized (mGlobalLock) {
3980 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3981 if (r == null) {
3982 return;
3983 }
3984 final long origId = Binder.clearCallingIdentity();
3985 try {
3986 r.registerRemoteAnimations(definition);
3987 } finally {
3988 Binder.restoreCallingIdentity(origId);
3989 }
3990 }
3991 }
3992
3993 @Override
3994 public void registerRemoteAnimationForNextActivityStart(String packageName,
3995 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003996 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 "registerRemoteAnimationForNextActivityStart");
3998 adapter.setCallingPid(Binder.getCallingPid());
3999 synchronized (mGlobalLock) {
4000 final long origId = Binder.clearCallingIdentity();
4001 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004002 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 packageName, adapter);
4004 } finally {
4005 Binder.restoreCallingIdentity(origId);
4006 }
4007 }
4008 }
4009
4010 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4011 @Override
4012 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4013 synchronized (mGlobalLock) {
4014 final long origId = Binder.clearCallingIdentity();
4015 try {
4016 mAm.mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4017 } finally {
4018 Binder.restoreCallingIdentity(origId);
4019 }
4020 }
4021 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004022
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004023 @Override
4024 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004025 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004026 synchronized (mGlobalLock) {
4027 synchronized (mAm.mPidsSelfLocked) {
4028 final int pid = Binder.getCallingPid();
4029 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004030 mVrController.setVrThreadLocked(tid, pid, proc.getWindowProcessController());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004031 }
4032 }
4033 }
4034
4035 @Override
4036 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004038 != PERMISSION_GRANTED) {
4039 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4040 + Binder.getCallingPid()
4041 + ", uid=" + Binder.getCallingUid()
4042 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4043 Slog.w(TAG, msg);
4044 throw new SecurityException(msg);
4045 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004047 synchronized (mGlobalLock) {
4048 synchronized (mAm.mPidsSelfLocked) {
4049 final int pid = Binder.getCallingPid();
4050 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
4051 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4052 }
4053 }
4054 }
4055
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004056 @Override
4057 public void stopAppSwitches() {
4058 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4059 synchronized (mGlobalLock) {
4060 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4061 mDidAppSwitch = false;
4062 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4063 }
4064 }
4065
4066 @Override
4067 public void resumeAppSwitches() {
4068 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4069 synchronized (mGlobalLock) {
4070 // Note that we don't execute any pending app switches... we will
4071 // let those wait until either the timeout, or the next start
4072 // activity request.
4073 mAppSwitchesAllowedTime = 0;
4074 }
4075 }
4076
4077 void onStartActivitySetDidAppSwitch() {
4078 if (mDidAppSwitch) {
4079 // This is the second allowed switch since we stopped switches, so now just generally
4080 // allow switches. Use case:
4081 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4082 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4083 // anyone to switch again).
4084 mAppSwitchesAllowedTime = 0;
4085 } else {
4086 mDidAppSwitch = true;
4087 }
4088 }
4089
4090 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004091 boolean shouldDisableNonVrUiLocked() {
4092 return mVrController.shouldDisableNonVrUiLocked();
4093 }
4094
4095 void applyUpdateVrModeLocked(ActivityRecord r) {
4096 // VR apps are expected to run in a main display. If an app is turning on VR for
4097 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4098 // fullscreen stack before enabling VR Mode.
4099 // TODO: The goal of this code is to keep the VR app on the main display. When the
4100 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4101 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4102 // option would be a better choice here.
4103 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4104 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4105 + " to main stack for VR");
4106 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4107 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4108 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4109 }
4110 mH.post(() -> {
4111 if (!mVrController.onVrModeChanged(r)) {
4112 return;
4113 }
4114 synchronized (mGlobalLock) {
4115 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4116 mWindowManager.disableNonVrUi(disableNonVrUi);
4117 if (disableNonVrUi) {
4118 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4119 // then remove the pinned stack.
4120 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4121 }
4122 }
4123 });
4124 }
4125
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004126 ActivityStack getTopDisplayFocusedStack() {
4127 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004128 }
4129
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004130 /** Pokes the task persister. */
4131 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4132 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4133 }
4134
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004135 void onTopProcChangedLocked(WindowProcessController proc) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004136 mVrController.onTopProcChangedLocked(proc);
4137 }
4138
4139 boolean isKeyguardLocked() {
4140 return mKeyguardController.isKeyguardLocked();
4141 }
4142
4143 boolean isNextTransitionForward() {
4144 int transit = mWindowManager.getPendingAppTransition();
4145 return transit == TRANSIT_ACTIVITY_OPEN
4146 || transit == TRANSIT_TASK_OPEN
4147 || transit == TRANSIT_TASK_TO_FRONT;
4148 }
4149
Wale Ogunwalef6733932018-06-27 05:14:34 -07004150 void dumpSleepStates(PrintWriter pw, boolean testPssMode) {
4151 synchronized (mGlobalLock) {
4152 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
4153 if (mRunningVoice != null) {
4154 pw.println(" mRunningVoice=" + mRunningVoice);
4155 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
4156 }
4157 pw.println(" mSleeping=" + mSleeping);
4158 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
4159 pw.println(" mVrController=" + mVrController);
4160 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004161 }
4162
Wale Ogunwalef6733932018-06-27 05:14:34 -07004163 void writeSleepStateToProto(ProtoOutputStream proto) {
4164 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4165 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4166 st.toString());
4167 }
4168
4169 if (mRunningVoice != null) {
4170 final long vrToken = proto.start(
4171 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4172 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4173 mRunningVoice.toString());
4174 mVoiceWakeLock.writeToProto(
4175 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4176 proto.end(vrToken);
4177 }
4178
4179 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4180 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4181 mShuttingDown);
4182 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004183 }
4184
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004185 int getCurrentUserId() {
4186 return mAmInternal.getCurrentUserId();
4187 }
4188
4189 private void enforceNotIsolatedCaller(String caller) {
4190 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4191 throw new SecurityException("Isolated process not allowed to call " + caller);
4192 }
4193 }
4194
Wale Ogunwalef6733932018-06-27 05:14:34 -07004195 public Configuration getConfiguration() {
4196 Configuration ci;
4197 synchronized(mGlobalLock) {
4198 ci = new Configuration(getGlobalConfiguration());
4199 ci.userSetLocale = false;
4200 }
4201 return ci;
4202 }
4203
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 /**
4205 * Current global configuration information. Contains general settings for the entire system,
4206 * also corresponds to the merged configuration of the default display.
4207 */
4208 Configuration getGlobalConfiguration() {
4209 return mStackSupervisor.getConfiguration();
4210 }
4211
4212 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4213 boolean initLocale) {
4214 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4215 }
4216
4217 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4218 boolean initLocale, boolean deferResume) {
4219 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4220 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4221 UserHandle.USER_NULL, deferResume);
4222 }
4223
4224 void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4225 final long origId = Binder.clearCallingIdentity();
4226 try {
4227 synchronized (mGlobalLock) {
4228 updateConfigurationLocked(values, null, false, true, userId,
4229 false /* deferResume */);
4230 }
4231 } finally {
4232 Binder.restoreCallingIdentity(origId);
4233 }
4234 }
4235
4236 void updateUserConfiguration() {
4237 synchronized (mGlobalLock) {
4238 final Configuration configuration = new Configuration(getGlobalConfiguration());
4239 final int currentUserId = mAmInternal.getCurrentUserId();
4240 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(), configuration,
4241 currentUserId, Settings.System.canWrite(mContext));
4242 updateConfigurationLocked(configuration, null /* starting */, false /* initLocale */,
4243 false /* persistent */, currentUserId, false /* deferResume */);
4244 }
4245 }
4246
4247 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4248 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4249 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4250 deferResume, null /* result */);
4251 }
4252
4253 /**
4254 * Do either or both things: (1) change the current configuration, and (2)
4255 * make sure the given activity is running with the (now) current
4256 * configuration. Returns true if the activity has been left running, or
4257 * false if <var>starting</var> is being destroyed to match the new
4258 * configuration.
4259 *
4260 * @param userId is only used when persistent parameter is set to true to persist configuration
4261 * for that particular user
4262 */
4263 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4264 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4265 ActivityTaskManagerService.UpdateConfigurationResult result) {
4266 int changes = 0;
4267 boolean kept = true;
4268
4269 if (mWindowManager != null) {
4270 mWindowManager.deferSurfaceLayout();
4271 }
4272 try {
4273 if (values != null) {
4274 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4275 deferResume);
4276 }
4277
4278 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4279 } finally {
4280 if (mWindowManager != null) {
4281 mWindowManager.continueSurfaceLayout();
4282 }
4283 }
4284
4285 if (result != null) {
4286 result.changes = changes;
4287 result.activityRelaunched = !kept;
4288 }
4289 return kept;
4290 }
4291
4292 /**
4293 * Returns true if this configuration change is interesting enough to send an
4294 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
4295 */
4296 private static boolean isSplitConfigurationChange(int configDiff) {
4297 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
4298 }
4299
4300 /** Update default (global) configuration and notify listeners about changes. */
4301 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4302 boolean persistent, int userId, boolean deferResume) {
4303 mTempConfig.setTo(getGlobalConfiguration());
4304 final int changes = mTempConfig.updateFrom(values);
4305 if (changes == 0) {
4306 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4307 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4308 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4309 // (even if there are no actual changes) to unfreeze the window.
4310 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4311 return 0;
4312 }
4313
4314 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4315 "Updating global configuration to: " + values);
4316
4317 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4318 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4319 values.colorMode,
4320 values.densityDpi,
4321 values.fontScale,
4322 values.hardKeyboardHidden,
4323 values.keyboard,
4324 values.keyboardHidden,
4325 values.mcc,
4326 values.mnc,
4327 values.navigation,
4328 values.navigationHidden,
4329 values.orientation,
4330 values.screenHeightDp,
4331 values.screenLayout,
4332 values.screenWidthDp,
4333 values.smallestScreenWidthDp,
4334 values.touchscreen,
4335 values.uiMode);
4336
4337
4338 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4339 final LocaleList locales = values.getLocales();
4340 int bestLocaleIndex = 0;
4341 if (locales.size() > 1) {
4342 if (mSupportedSystemLocales == null) {
4343 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4344 }
4345 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4346 }
4347 SystemProperties.set("persist.sys.locale",
4348 locales.get(bestLocaleIndex).toLanguageTag());
4349 LocaleList.setDefault(locales, bestLocaleIndex);
4350 mAm.mHandler.sendMessage(mAm.mHandler.obtainMessage(SEND_LOCALE_TO_MOUNT_DAEMON_MSG,
4351 locales.get(bestLocaleIndex)));
4352 }
4353
4354 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
4355 mTempConfig.seq = mConfigurationSeq;
4356
4357 // Update stored global config and notify everyone about the change.
4358 mStackSupervisor.onConfigurationChanged(mTempConfig);
4359
4360 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4361 // TODO(multi-display): Update UsageEvents#Event to include displayId.
4362 mAm.mUsageStatsService.reportConfigurationChange(
4363 mTempConfig, mAmInternal.getCurrentUserId());
4364
4365 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004366 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367
4368 AttributeCache ac = AttributeCache.instance();
4369 if (ac != null) {
4370 ac.updateConfiguration(mTempConfig);
4371 }
4372
4373 // Make sure all resources in our process are updated right now, so that anyone who is going
4374 // to retrieve resource values after we return will be sure to get the new ones. This is
4375 // especially important during boot, where the first config change needs to guarantee all
4376 // resources have that config before following boot code is executed.
4377 mAm.mSystemThread.applyConfigurationToResources(mTempConfig);
4378
4379 // We need another copy of global config because we're scheduling some calls instead of
4380 // running them in place. We need to be sure that object we send will be handled unchanged.
4381 final Configuration configCopy = new Configuration(mTempConfig);
4382 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
4383 Message msg = mAm.mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
4384 msg.obj = configCopy;
4385 msg.arg1 = userId;
4386 mAm.mHandler.sendMessage(msg);
4387 }
4388
4389 for (int i = mAm.mLruProcesses.size() - 1; i >= 0; i--) {
4390 ProcessRecord app = mAm.mLruProcesses.get(i);
4391 try {
4392 if (app.thread != null) {
4393 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Sending to proc "
4394 + app.processName + " new config " + configCopy);
4395 getLifecycleManager().scheduleTransaction(app.thread,
4396 ConfigurationChangeItem.obtain(configCopy));
4397 }
4398 } catch (Exception e) {
4399 Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change", e);
4400 }
4401 }
4402
4403 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
4404 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING
4405 | Intent.FLAG_RECEIVER_FOREGROUND
4406 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4407 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4408 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4409 UserHandle.USER_ALL);
4410 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
4411 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
4412 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
4413 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
4414 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4415 if (initLocale || !mAm.mProcessesReady) {
4416 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4417 }
4418 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4419 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4420 UserHandle.USER_ALL);
4421 }
4422
4423 // Send a broadcast to PackageInstallers if the configuration change is interesting
4424 // for the purposes of installing additional splits.
4425 if (!initLocale && isSplitConfigurationChange(changes)) {
4426 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
4427 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
4428 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4429
4430 // Typically only app stores will have this permission.
4431 String[] permissions = new String[] { android.Manifest.permission.INSTALL_PACKAGES };
4432 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, permissions,
4433 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
4434 }
4435
4436 // Override configuration of the default display duplicates global config, so we need to
4437 // update it also. This will also notify WindowManager about changes.
4438 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4439 DEFAULT_DISPLAY);
4440
4441 return changes;
4442 }
4443
4444 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4445 boolean deferResume, int displayId) {
4446 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4447 displayId, null /* result */);
4448 }
4449
4450 /**
4451 * Updates override configuration specific for the selected display. If no config is provided,
4452 * new one will be computed in WM based on current display info.
4453 */
4454 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4455 ActivityRecord starting, boolean deferResume, int displayId,
4456 ActivityTaskManagerService.UpdateConfigurationResult result) {
4457 int changes = 0;
4458 boolean kept = true;
4459
4460 if (mWindowManager != null) {
4461 mWindowManager.deferSurfaceLayout();
4462 }
4463 try {
4464 if (values != null) {
4465 if (displayId == DEFAULT_DISPLAY) {
4466 // Override configuration of the default display duplicates global config, so
4467 // we're calling global config update instead for default display. It will also
4468 // apply the correct override config.
4469 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4470 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4471 } else {
4472 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4473 }
4474 }
4475
4476 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4477 } finally {
4478 if (mWindowManager != null) {
4479 mWindowManager.continueSurfaceLayout();
4480 }
4481 }
4482
4483 if (result != null) {
4484 result.changes = changes;
4485 result.activityRelaunched = !kept;
4486 }
4487 return kept;
4488 }
4489
4490 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4491 int displayId) {
4492 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4493 final int changes = mTempConfig.updateFrom(values);
4494 if (changes != 0) {
4495 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4496 + mTempConfig + " for displayId=" + displayId);
4497 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4498
4499 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4500 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
4501 mAm.mAppWarnings.onDensityChanged();
4502
4503 mAm.killAllBackgroundProcessesExcept(N,
4504 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4505 }
4506 }
4507
4508 // Update the configuration with WM first and check if any of the stacks need to be resized
4509 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4510 // necessary. This way we don't need to relaunch again afterwards in
4511 // ensureActivityConfiguration().
4512 if (mWindowManager != null) {
4513 final int[] resizedStacks =
4514 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4515 if (resizedStacks != null) {
4516 for (int stackId : resizedStacks) {
4517 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4518 }
4519 }
4520 }
4521
4522 return changes;
4523 }
4524
Wale Ogunwalef6733932018-06-27 05:14:34 -07004525 private void updateEventDispatchingLocked(boolean booted) {
4526 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4527 }
4528
4529 void enableScreenAfterBoot(boolean booted) {
4530 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4531 SystemClock.uptimeMillis());
4532 mWindowManager.enableScreenAfterBoot();
4533
4534 synchronized (mGlobalLock) {
4535 updateEventDispatchingLocked(booted);
4536 }
4537 }
4538
4539 boolean canShowErrorDialogs() {
4540 return mShowDialogs && !mSleeping && !mShuttingDown
4541 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
4542 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
Wale Ogunwale86b74462018-07-02 08:42:43 -07004543 mAmInternal.getCurrentUserId())
Wale Ogunwalef6733932018-06-27 05:14:34 -07004544 && !(UserManager.isDeviceInDemoMode(mContext)
Wale Ogunwale86b74462018-07-02 08:42:43 -07004545 && mAmInternal.getCurrentUser().isDemo());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004546 }
4547
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004548 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
4549 if (r == null || !r.hasProcess()) {
4550 return KEY_DISPATCHING_TIMEOUT_MS;
4551 }
4552 return getInputDispatchingTimeoutLocked(r.app);
4553 }
4554
4555 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
4556 if (r != null && (r.isInstrumenting() || r.isUsingWrapper())) {
4557 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS;
4558 }
4559 return KEY_DISPATCHING_TIMEOUT_MS;
4560 }
4561
4562 long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
4563 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
4564 throw new SecurityException("Requires permission " + FILTER_EVENTS);
4565 }
4566 WindowProcessController proc;
4567 long timeout;
4568 synchronized (mGlobalLock) {
4569 proc = mPidMap.get(pid);
4570 timeout = getInputDispatchingTimeoutLocked(proc);
4571 }
4572
4573 if (inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) {
4574 return -1;
4575 }
4576
4577 return timeout;
4578 }
4579
4580 /**
4581 * Handle input dispatching timeouts.
4582 * Returns whether input dispatching should be aborted or not.
4583 */
4584 boolean inputDispatchingTimedOut(final WindowProcessController proc,
4585 final ActivityRecord activity, final ActivityRecord parent,
4586 final boolean aboveSystem, String reason) {
4587 if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
4588 throw new SecurityException("Requires permission " + FILTER_EVENTS);
4589 }
4590
4591 final String annotation;
4592 if (reason == null) {
4593 annotation = "Input dispatching timed out";
4594 } else {
4595 annotation = "Input dispatching timed out (" + reason + ")";
4596 }
4597
4598 if (proc != null) {
4599 synchronized (mGlobalLock) {
4600 if (proc.isDebugging()) {
4601 return false;
4602 }
4603
4604 if (proc.isInstrumenting()) {
4605 Bundle info = new Bundle();
4606 info.putString("shortMsg", "keyDispatchingTimedOut");
4607 info.putString("longMsg", annotation);
4608 mAm.finishInstrumentationLocked(
4609 (ProcessRecord) proc.mOwner, Activity.RESULT_CANCELED, info);
4610 return true;
4611 }
4612 }
4613 mH.post(() -> {
4614 mAm.mAppErrors.appNotResponding(
4615 (ProcessRecord) proc.mOwner, activity, parent, aboveSystem, annotation);
4616 });
4617 }
4618
4619 return true;
4620 }
4621
Wale Ogunwalef6733932018-06-27 05:14:34 -07004622 /**
4623 * Decide based on the configuration whether we should show the ANR,
4624 * crash, etc dialogs. The idea is that if there is no affordance to
4625 * press the on-screen buttons, or the user experience would be more
4626 * greatly impacted than the crash itself, we shouldn't show the dialog.
4627 *
4628 * A thought: SystemUI might also want to get told about this, the Power
4629 * dialog / global actions also might want different behaviors.
4630 */
4631 private void updateShouldShowDialogsLocked(Configuration config) {
4632 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4633 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4634 && config.navigation == Configuration.NAVIGATION_NONAV);
4635 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4636 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4637 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4638 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4639 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4640 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4641 HIDE_ERROR_DIALOGS, 0) != 0;
4642 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4643 }
4644
4645 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4646 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4647 FONT_SCALE, 1.0f, userId);
4648
4649 synchronized (this) {
4650 if (getGlobalConfiguration().fontScale == scaleFactor) {
4651 return;
4652 }
4653
4654 final Configuration configuration
4655 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4656 configuration.fontScale = scaleFactor;
4657 updatePersistentConfiguration(configuration, userId);
4658 }
4659 }
4660
4661 // Actually is sleeping or shutting down or whatever else in the future
4662 // is an inactive state.
4663 boolean isSleepingOrShuttingDownLocked() {
4664 return isSleepingLocked() || mShuttingDown;
4665 }
4666
4667 boolean isSleepingLocked() {
4668 return mSleeping;
4669 }
4670
4671 /**
4672 * Update AMS states when an activity is resumed. This should only be called by
4673 * {@link ActivityStack#onActivityStateChanged(
4674 * ActivityRecord, ActivityStack.ActivityState, String)} when an activity is resumed.
4675 */
4676 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4677 final TaskRecord task = r.getTask();
4678 if (task.isActivityTypeStandard()) {
4679 if (mCurAppTimeTracker != r.appTimeTracker) {
4680 // We are switching app tracking. Complete the current one.
4681 if (mCurAppTimeTracker != null) {
4682 mCurAppTimeTracker.stop();
4683 mH.obtainMessage(
4684 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4685 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4686 mCurAppTimeTracker = null;
4687 }
4688 if (r.appTimeTracker != null) {
4689 mCurAppTimeTracker = r.appTimeTracker;
4690 startTimeTrackingFocusedActivityLocked();
4691 }
4692 } else {
4693 startTimeTrackingFocusedActivityLocked();
4694 }
4695 } else {
4696 r.appTimeTracker = null;
4697 }
4698 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
4699 // TODO: Probably not, because we don't want to resume voice on switching
4700 // back to this activity
4701 if (task.voiceInteractor != null) {
4702 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
4703 } else {
4704 finishRunningVoiceLocked();
4705
4706 if (mLastResumedActivity != null) {
4707 final IVoiceInteractionSession session;
4708
4709 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
4710 if (lastResumedActivityTask != null
4711 && lastResumedActivityTask.voiceSession != null) {
4712 session = lastResumedActivityTask.voiceSession;
4713 } else {
4714 session = mLastResumedActivity.voiceSession;
4715 }
4716
4717 if (session != null) {
4718 // We had been in a voice interaction session, but now focused has
4719 // move to something different. Just finish the session, we can't
4720 // return to it and retain the proper state and synchronization with
4721 // the voice interaction service.
4722 finishVoiceTask(session);
4723 }
4724 }
4725 }
4726
4727 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
4728 mAmInternal.sendForegroundProfileChanged(r.userId);
4729 }
4730 updateResumedAppTrace(r);
4731 mLastResumedActivity = r;
4732
4733 mWindowManager.setFocusedApp(r.appToken, true);
4734
4735 applyUpdateLockStateLocked(r);
4736 applyUpdateVrModeLocked(r);
4737
4738 EventLogTags.writeAmSetResumedActivity(
4739 r == null ? -1 : r.userId,
4740 r == null ? "NULL" : r.shortComponentName,
4741 reason);
4742 }
4743
4744 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
4745 synchronized (mGlobalLock) {
4746 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
4747 updateSleepIfNeededLocked();
4748 return token;
4749 }
4750 }
4751
4752 void updateSleepIfNeededLocked() {
4753 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
4754 final boolean wasSleeping = mSleeping;
4755 boolean updateOomAdj = false;
4756
4757 if (!shouldSleep) {
4758 // If wasSleeping is true, we need to wake up activity manager state from when
4759 // we started sleeping. In either case, we need to apply the sleep tokens, which
4760 // will wake up stacks or put them to sleep as appropriate.
4761 if (wasSleeping) {
4762 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07004763 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
4764 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004765 startTimeTrackingFocusedActivityLocked();
4766 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
4767 mStackSupervisor.comeOutOfSleepIfNeededLocked();
4768 }
4769 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
4770 if (wasSleeping) {
4771 updateOomAdj = true;
4772 }
4773 } else if (!mSleeping && shouldSleep) {
4774 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07004775 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
4776 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004777 if (mCurAppTimeTracker != null) {
4778 mCurAppTimeTracker.stop();
4779 }
4780 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
4781 mStackSupervisor.goingToSleepLocked();
4782 updateResumedAppTrace(null /* resumed */);
4783 updateOomAdj = true;
4784 }
4785 if (updateOomAdj) {
4786 mH.post(mAmInternal::updateOomAdj);
4787 }
4788 }
4789
4790 void updateOomAdj() {
4791 mH.post(mAmInternal::updateOomAdj);
4792 }
4793
Andrii Kulian52d255c2018-07-13 11:32:19 -07004794 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07004795 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07004796 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07004797 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
4798 mCurAppTimeTracker.start(resumedActivity.packageName);
4799 }
4800 }
4801
4802 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
4803 if (mTracedResumedActivity != null) {
4804 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
4805 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
4806 }
4807 if (resumed != null) {
4808 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
4809 constructResumedTraceName(resumed.packageName), 0);
4810 }
4811 mTracedResumedActivity = resumed;
4812 }
4813
4814 private String constructResumedTraceName(String packageName) {
4815 return "focused app: " + packageName;
4816 }
4817
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004818 /** Helper method that requests bounds from WM and applies them to stack. */
4819 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
4820 final Rect newStackBounds = new Rect();
4821 final ActivityStack stack = mStackSupervisor.getStack(stackId);
4822
4823 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
4824 if (stack == null) {
4825 final StringWriter writer = new StringWriter();
4826 final PrintWriter printWriter = new PrintWriter(writer);
4827 mStackSupervisor.dumpDisplays(printWriter);
4828 printWriter.flush();
4829
4830 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
4831 }
4832
4833 stack.getBoundsForNewConfiguration(newStackBounds);
4834 mStackSupervisor.resizeStackLocked(
4835 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
4836 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
4837 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
4838 }
4839
4840 /** Applies latest configuration and/or visibility updates if needed. */
4841 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
4842 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004843 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004844 // mainStack is null during startup.
4845 if (mainStack != null) {
4846 if (changes != 0 && starting == null) {
4847 // If the configuration changed, and the caller is not already
4848 // in the process of starting an activity, then find the top
4849 // activity to check if its configuration needs to change.
4850 starting = mainStack.topRunningActivityLocked();
4851 }
4852
4853 if (starting != null) {
4854 kept = starting.ensureActivityConfiguration(changes,
4855 false /* preserveWindow */);
4856 // And we need to make sure at this point that all other activities
4857 // are made visible with the correct configuration.
4858 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
4859 !PRESERVE_WINDOWS);
4860 }
4861 }
4862
4863 return kept;
4864 }
4865
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004866 void scheduleAppGcsLocked() {
4867 mH.post(() -> mAmInternal.scheduleAppGcs());
4868 }
4869
4870 /**
4871 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
4872 * PackageManager could be unavailable at construction time and therefore needs to be accessed
4873 * on demand.
4874 */
4875 IPackageManager getPackageManager() {
4876 return AppGlobals.getPackageManager();
4877 }
4878
4879 PackageManagerInternal getPackageManagerInternalLocked() {
4880 if (mPmInternal == null) {
4881 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
4882 }
4883 return mPmInternal;
4884 }
4885
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004886 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
4887 if (true || Build.IS_USER) {
4888 return;
4889 }
4890
4891 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4892 StrictMode.allowThreadDiskWrites();
4893 try {
4894 File tracesDir = new File("/data/anr");
4895 File tracesFile = null;
4896 try {
4897 tracesFile = File.createTempFile("app_slow", null, tracesDir);
4898
4899 StringBuilder sb = new StringBuilder();
4900 Time tobj = new Time();
4901 tobj.set(System.currentTimeMillis());
4902 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4903 sb.append(": ");
4904 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4905 sb.append(" since ");
4906 sb.append(msg);
4907 FileOutputStream fos = new FileOutputStream(tracesFile);
4908 fos.write(sb.toString().getBytes());
4909 if (app == null) {
4910 fos.write("\n*** No application process!".getBytes());
4911 }
4912 fos.close();
4913 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4914 } catch (IOException e) {
4915 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
4916 return;
4917 }
4918
4919 if (app != null && app.getPid() > 0) {
4920 ArrayList<Integer> firstPids = new ArrayList<Integer>();
4921 firstPids.add(app.getPid());
4922 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
4923 }
4924
4925 File lastTracesFile = null;
4926 File curTracesFile = null;
4927 for (int i=9; i>=0; i--) {
4928 String name = String.format(Locale.US, "slow%02d.txt", i);
4929 curTracesFile = new File(tracesDir, name);
4930 if (curTracesFile.exists()) {
4931 if (lastTracesFile != null) {
4932 curTracesFile.renameTo(lastTracesFile);
4933 } else {
4934 curTracesFile.delete();
4935 }
4936 }
4937 lastTracesFile = curTracesFile;
4938 }
4939 tracesFile.renameTo(curTracesFile);
4940 } finally {
4941 StrictMode.setThreadPolicy(oldPolicy);
4942 }
4943 }
4944
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004945 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004946 static final int REPORT_TIME_TRACKER_MSG = 1;
4947
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004948 public H(Looper looper) {
4949 super(looper, null, true);
4950 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004951
4952 @Override
4953 public void handleMessage(Message msg) {
4954 switch (msg.what) {
4955 case REPORT_TIME_TRACKER_MSG: {
4956 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
4957 tracker.deliverResult(mContext);
4958 } break;
4959 }
4960 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004961 }
4962
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004963 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004964 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004965
4966 public UiHandler() {
4967 super(com.android.server.UiThread.get().getLooper(), null, true);
4968 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004969
4970 @Override
4971 public void handleMessage(Message msg) {
4972 switch (msg.what) {
4973 case DISMISS_DIALOG_UI_MSG: {
4974 final Dialog d = (Dialog) msg.obj;
4975 d.dismiss();
4976 break;
4977 }
4978 }
4979 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004980 }
4981
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004982 final class LocalService extends ActivityTaskManagerInternal {
4983 @Override
4984 public SleepToken acquireSleepToken(String tag, int displayId) {
4985 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004986 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004987 }
4988
4989 @Override
4990 public ComponentName getHomeActivityForUser(int userId) {
4991 synchronized (mGlobalLock) {
4992 ActivityRecord homeActivity = mStackSupervisor.getHomeActivityForUser(userId);
4993 return homeActivity == null ? null : homeActivity.realActivity;
4994 }
4995 }
4996
4997 @Override
4998 public void onLocalVoiceInteractionStarted(IBinder activity,
4999 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5000 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005002 }
5003 }
5004
5005 @Override
5006 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5007 synchronized (mGlobalLock) {
5008 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5009 reasons, timestamp);
5010 }
5011 }
5012
5013 @Override
5014 public void notifyAppTransitionFinished() {
5015 synchronized (mGlobalLock) {
5016 mStackSupervisor.notifyAppTransitionDone();
5017 }
5018 }
5019
5020 @Override
5021 public void notifyAppTransitionCancelled() {
5022 synchronized (mGlobalLock) {
5023 mStackSupervisor.notifyAppTransitionDone();
5024 }
5025 }
5026
5027 @Override
5028 public List<IBinder> getTopVisibleActivities() {
5029 synchronized (mGlobalLock) {
5030 return mStackSupervisor.getTopVisibleActivities();
5031 }
5032 }
5033
5034 @Override
5035 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5036 synchronized (mGlobalLock) {
5037 mStackSupervisor.setDockedStackMinimized(minimized);
5038 }
5039 }
5040
5041 @Override
5042 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5043 Bundle bOptions) {
5044 Preconditions.checkNotNull(intents, "intents");
5045 final String[] resolvedTypes = new String[intents.length];
5046
5047 // UID of the package on user userId.
5048 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5049 // packageUid may not be initialized.
5050 int packageUid = 0;
5051 final long ident = Binder.clearCallingIdentity();
5052
5053 try {
5054 for (int i = 0; i < intents.length; i++) {
5055 resolvedTypes[i] =
5056 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5057 }
5058
5059 packageUid = AppGlobals.getPackageManager().getPackageUid(
5060 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5061 } catch (RemoteException e) {
5062 // Shouldn't happen.
5063 } finally {
5064 Binder.restoreCallingIdentity(ident);
5065 }
5066
5067 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005068 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005069 packageUid, packageName,
5070 intents, resolvedTypes, null /* resultTo */,
5071 SafeActivityOptions.fromBundle(bOptions), userId,
5072 false /* validateIncomingUser */);
5073 }
5074 }
5075
5076 @Override
5077 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5078 Intent intent, Bundle options, int userId) {
5079 return ActivityTaskManagerService.this.startActivityAsUser(
5080 caller, callerPacakge, intent,
5081 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5082 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5083 false /*validateIncomingUser*/);
5084 }
5085
5086 @Override
5087 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback) {
5088 synchronized (mGlobalLock) {
5089
5090 // We might change the visibilities here, so prepare an empty app transition which
5091 // might be overridden later if we actually change visibilities.
5092 final boolean wasTransitionSet =
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005093 mWindowManager.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005094 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005095 mWindowManager.prepareAppTransition(TRANSIT_NONE,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005096 false /* alwaysKeepCurrent */);
5097 }
5098 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5099
5100 // If there was a transition set already we don't want to interfere with it as we
5101 // might be starting it too early.
5102 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005103 mWindowManager.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005104 }
5105 }
5106 if (callback != null) {
5107 callback.run();
5108 }
5109 }
5110
5111 @Override
5112 public void notifyKeyguardTrustedChanged() {
5113 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005114 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005115 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5116 }
5117 }
5118 }
5119
5120 /**
5121 * Called after virtual display Id is updated by
5122 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5123 * {@param vrVr2dDisplayId}.
5124 */
5125 @Override
5126 public void setVr2dDisplayId(int vr2dDisplayId) {
5127 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5128 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005130 }
5131 }
5132
5133 @Override
5134 public void setFocusedActivity(IBinder token) {
5135 synchronized (mGlobalLock) {
5136 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5137 if (r == null) {
5138 throw new IllegalArgumentException(
5139 "setFocusedActivity: No activity record matching token=" + token);
5140 }
5141 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
5142 r, "setFocusedActivity")) {
5143 mStackSupervisor.resumeFocusedStackTopActivityLocked();
5144 }
5145 }
5146 }
5147
5148 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005149 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005150 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005151 }
5152
5153 @Override
5154 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005155 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005156 }
5157
5158 @Override
5159 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005160 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005161 }
5162
5163 @Override
5164 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5165 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5166 }
5167
5168 @Override
5169 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005170 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005171 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005172
5173 @Override
5174 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5175 synchronized (mGlobalLock) {
5176 mActiveVoiceInteractionServiceComponent = component;
5177 }
5178 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179
5180 @Override
5181 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5182 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5183 return;
5184 }
5185 synchronized (mGlobalLock) {
5186 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5187 if (types == null) {
5188 if (uid < 0) {
5189 return;
5190 }
5191 types = new ArrayMap<>();
5192 mAllowAppSwitchUids.put(userId, types);
5193 }
5194 if (uid < 0) {
5195 types.remove(type);
5196 } else {
5197 types.put(type, uid);
5198 }
5199 }
5200 }
5201
5202 @Override
5203 public void onUserStopped(int userId) {
5204 synchronized (mGlobalLock) {
5205 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5206 mAllowAppSwitchUids.remove(userId);
5207 }
5208 }
5209
5210 @Override
5211 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5212 synchronized (mGlobalLock) {
5213 return ActivityTaskManagerService.this.isGetTasksAllowed(
5214 caller, callingPid, callingUid);
5215 }
5216 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005217
5218 @Override
5219 public void onProcessAdded(WindowProcessController proc) {
5220 synchronized (mGlobalLock) {
5221 mProcessNames.put(proc.mName, proc.mUid, proc);
5222 }
5223 }
5224
5225 @Override
5226 public void onProcessRemoved(String name, int uid) {
5227 synchronized (mGlobalLock) {
5228 mProcessNames.remove(name, uid);
5229 }
5230 }
5231
5232 @Override
5233 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5234 synchronized (mGlobalLock) {
5235 if (proc == mHomeProcess) {
5236 mHomeProcess = null;
5237 }
5238 if (proc == mPreviousProcess) {
5239 mPreviousProcess = null;
5240 }
5241 }
5242 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005243
5244 @Override
5245 public int getTopProcessState() {
5246 synchronized (mGlobalLock) {
5247 return mTopProcessState;
5248 }
5249 }
5250
5251 @Override
5252 public boolean isSleeping() {
5253 synchronized (mGlobalLock) {
5254 return isSleepingLocked();
5255 }
5256 }
5257
5258 @Override
5259 public boolean isShuttingDown() {
5260 synchronized (mGlobalLock) {
5261 return mShuttingDown;
5262 }
5263 }
5264
5265 @Override
5266 public boolean shuttingDown(boolean booted, int timeout) {
5267 synchronized (mGlobalLock) {
5268 mShuttingDown = true;
5269 mStackSupervisor.prepareForShutdownLocked();
5270 updateEventDispatchingLocked(booted);
5271 return mStackSupervisor.shutdownLocked(timeout);
5272 }
5273 }
5274
5275 @Override
5276 public void enableScreenAfterBoot(boolean booted) {
5277 synchronized (mGlobalLock) {
5278 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5279 SystemClock.uptimeMillis());
5280 mWindowManager.enableScreenAfterBoot();
5281 updateEventDispatchingLocked(booted);
5282 }
5283 }
5284
5285 @Override
5286 public boolean showStrictModeViolationDialog() {
5287 synchronized (mGlobalLock) {
5288 return mShowDialogs && !mSleeping && !mShuttingDown;
5289 }
5290 }
5291
5292 @Override
5293 public void showSystemReadyErrorDialogsIfNeeded() {
5294 synchronized (mGlobalLock) {
5295 try {
5296 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5297 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5298 + " data partition or your device will be unstable.");
5299 mUiHandler.post(() -> {
5300 if (mShowDialogs) {
5301 AlertDialog d = new BaseErrorDialog(mUiContext);
5302 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5303 d.setCancelable(false);
5304 d.setTitle(mUiContext.getText(R.string.android_system_label));
5305 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5306 d.setButton(DialogInterface.BUTTON_POSITIVE,
5307 mUiContext.getText(R.string.ok),
5308 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5309 d.show();
5310 }
5311 });
5312 }
5313 } catch (RemoteException e) {
5314 }
5315
5316 if (!Build.isBuildConsistent()) {
5317 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5318 mUiHandler.post(() -> {
5319 if (mShowDialogs) {
5320 AlertDialog d = new BaseErrorDialog(mUiContext);
5321 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5322 d.setCancelable(false);
5323 d.setTitle(mUiContext.getText(R.string.android_system_label));
5324 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5325 d.setButton(DialogInterface.BUTTON_POSITIVE,
5326 mUiContext.getText(R.string.ok),
5327 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5328 d.show();
5329 }
5330 });
5331 }
5332 }
5333 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005334
5335 @Override
5336 public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) {
5337 synchronized (mGlobalLock) {
5338 return ActivityTaskManagerService.this.inputDispatchingTimedOut(
5339 pid, aboveSystem, reason);
5340 }
5341 }
5342
5343 @Override
5344 public void onProcessMapped(int pid, WindowProcessController proc) {
5345 synchronized (mGlobalLock) {
5346 mPidMap.put(pid, proc);
5347 }
5348 }
5349
5350 @Override
5351 public void onProcessUnMapped(int pid) {
5352 synchronized (mGlobalLock) {
5353 mPidMap.remove(pid);
5354 }
5355 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005356 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07005357}