blob: 3211afbe717747d6b2840e8a6e4a9535b8f849a7 [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;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalef6733932018-06-27 05:14:34 -070029import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
30import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
31import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070032import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef6733932018-06-27 05:14:34 -070033import static com.android.server.am.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
34import static com.android.server.am.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070035import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
36import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
37import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
38import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.ActivityTaskManager.INVALID_STACK_ID;
40import 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 Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070044import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070045import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
46import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
47import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070048import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
49import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070050import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070051import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070052import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070053import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
54import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070056import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
58import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070059import static android.os.Process.SYSTEM_UID;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070060import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
62import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
63import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
65import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070067import static android.view.WindowManager.TRANSIT_ACTIVITY_OPEN;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070070import static android.view.WindowManager.TRANSIT_TASK_OPEN;
71import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070072import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070073import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
74import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
75import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IMMERSIVE;
76import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070077import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070078import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070079import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070080import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070081import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070082import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070083import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
84import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IMMERSIVE;
85import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070086import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070087import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
88import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070089import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
90import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070091import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070092import static com.android.server.am.ActivityManagerService.ANIMATE;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070093import static com.android.server.am.ActivityManagerService.MY_PID;
94import static com.android.server.am.ActivityManagerService.SEND_LOCALE_TO_MOUNT_DAEMON_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070095import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070096import static com.android.server.am.ActivityManagerService.UPDATE_CONFIGURATION_MSG;
97import static com.android.server.am.ActivityManagerService.checkComponentPermission;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070098import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070099import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700100import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
101import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
102import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
103import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
104import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
105import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
106import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700107import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700108import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
109import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
110import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700111
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700112import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700113import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700114import android.annotation.Nullable;
115import android.annotation.UserIdInt;
116import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700117import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700118import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700119import android.app.ActivityOptions;
120import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700121import android.app.ActivityThread;
122import android.app.AlertDialog;
123import android.app.Dialog;
124import android.content.DialogInterface;
125import android.database.ContentObserver;
126import android.os.IUserManager;
127import android.os.PowerManager;
128import android.os.ServiceManager;
129import android.os.Trace;
130import android.os.UserManager;
131import android.os.WorkSource;
132import android.view.WindowManager;
133import com.android.internal.R;
134import com.android.internal.annotations.GuardedBy;
135import com.android.internal.app.IAppOpsService;
136import com.android.server.AppOpsService;
137import com.android.server.pm.UserManagerService;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700138import com.android.server.wm.ActivityTaskManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700139import android.app.AppGlobals;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
144import android.app.ITaskStackListener;
145import android.app.PictureInPictureParams;
146import android.app.ProfilerInfo;
147import android.app.RemoteAction;
148import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700149import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.admin.DevicePolicyCache;
151import android.app.assist.AssistContent;
152import android.app.assist.AssistStructure;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700153import android.app.servertransaction.ConfigurationChangeItem;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.usage.UsageEvents;
155import android.content.ActivityNotFoundException;
156import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700157import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700158import android.content.Context;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.IIntentSender;
160import android.content.Intent;
161import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.pm.ApplicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.pm.PackageManager;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.ResolveInfo;
166import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.res.Resources;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.graphics.Bitmap;
169import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700170import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.metrics.LogMaker;
172import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700173import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700174import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.os.Bundle;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700176import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700177import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.os.IBinder;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700179import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700180import android.os.Looper;
181import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.PersistableBundle;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700183import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.RemoteException;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700186import android.os.SystemClock;
187import android.os.SystemProperties;
188import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.UserHandle;
190import android.provider.Settings;
191import android.service.voice.IVoiceInteractionSession;
192import android.service.voice.VoiceInteractionManagerInternal;
193import android.telecom.TelecomManager;
194import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700195import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700196import android.util.ArrayMap;
197import android.util.EventLog;
198import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700199import android.util.Slog;
200
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700202import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700205import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.view.IRecentsAnimationRunner;
207import android.view.RemoteAnimationAdapter;
208import android.view.RemoteAnimationDefinition;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700209
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700210import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import com.android.internal.app.AssistUtils;
212import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import com.android.internal.logging.MetricsLogger;
215import com.android.internal.os.logging.MetricsLoggerWrapper;
216import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
217import com.android.internal.policy.IKeyguardDismissCallback;
218import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import com.android.internal.util.Preconditions;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700221import com.android.server.LocalServices;
222import com.android.server.SystemService;
223import com.android.server.Watchdog;
224import com.android.server.vr.VrManagerInternal;
225import com.android.server.wm.PinnedStackWindowController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import com.android.server.wm.WindowManagerService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227
228import java.io.File;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700229import java.io.FileOutputStream;
230import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700231import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import java.io.StringWriter;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233import java.util.ArrayList;
234import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import java.util.Locale;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700236
237/**
238 * System service for managing activities and their containers (task, stacks, displays,... ).
239 *
240 * {@hide}
241 */
242public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
243 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_AM;
244 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
246 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
247 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
248 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
249 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700251
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700252 Context mContext;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700253 /**
254 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
255 * change at runtime. Use mContext for non-UI purposes.
256 */
257 final Context mUiContext;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700258 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700259 UiHandler mUiHandler;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700260 ActivityManagerService mAm;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700261 ActivityManagerInternal mAmInternal;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700262 /* Global service lock used by the package the owns this service. */
263 Object mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700264 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700265 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700266 private UserManagerService mUserManager;
267 private AppOpsService mAppOpsService;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700268 /** All processes currently running that might have a window organized by name. */
269 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
270 /** This is the process holding what we currently consider to be the "home" activity. */
271 WindowProcessController mHomeProcess;
272 /**
273 * This is the process holding the activity the user last visited that is in a different process
274 * from the one they are currently in.
275 */
276 WindowProcessController mPreviousProcess;
277 /** The time at which the previous process was last visible. */
278 long mPreviousProcessVisibleTime;
279
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700280 /** List of intents that were used to start the most recent tasks. */
281 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700282 /** State of external calls telling us if the device is awake or asleep. */
283 private boolean mKeyguardShown = false;
284
285 // Wrapper around VoiceInteractionServiceManager
286 private AssistUtils mAssistUtils;
287
288 // VoiceInteraction session ID that changes for each new request except when
289 // being called for multi-window assist in a single session.
290 private int mViSessionId = 1000;
291
292 // How long to wait in getAssistContextExtras for the activity and foreground services
293 // to respond with the result.
294 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
295
296 // How long top wait when going through the modern assist (which doesn't need to block
297 // on getting this result before starting to launch its UI).
298 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
299
300 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
301 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
302
303 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
304
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700305 // Keeps track of the active voice interaction service component, notified from
306 // VoiceInteractionManagerService
307 ComponentName mActiveVoiceInteractionServiceComponent;
308
309 private VrController mVrController;
310 KeyguardController mKeyguardController;
311 private final ClientLifecycleManager mLifecycleManager;
312 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700313 /** The controller for all operations related to locktask. */
314 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700315 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700316
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700317 boolean mSuppressResizeConfigChanges;
318
319 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
320 new UpdateConfigurationResult();
321
322 static final class UpdateConfigurationResult {
323 // Configuration changes that were updated.
324 int changes;
325 // If the activity was relaunched to match the new configuration.
326 boolean activityRelaunched;
327
328 void reset() {
329 changes = 0;
330 activityRelaunched = false;
331 }
332 }
333
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700334 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700335 private int mConfigurationSeq;
336 // To cache the list of supported system locales
337 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700338
339 /**
340 * Temp object used when global and/or display override configuration is updated. It is also
341 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
342 * anyone...
343 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700344 private Configuration mTempConfig = new Configuration();
345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /** Temporary to avoid allocations. */
347 final StringBuilder mStringBuilder = new StringBuilder(256);
348
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 // Amount of time after a call to stopAppSwitches() during which we will
350 // prevent further untrusted switches from happening.
351 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
352
353 /**
354 * The time at which we will allow normal application switches again,
355 * after a call to {@link #stopAppSwitches()}.
356 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700357 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700358 /**
359 * This is set to true after the first switch after mAppSwitchesAllowedTime
360 * is set; any switches after that will clear the time.
361 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700362 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700363
364 IActivityController mController = null;
365 boolean mControllerIsAMonkey = false;
366
367 /**
368 * Used to retain an update lock when the foreground activity is in
369 * immersive mode.
370 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700371 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700372
373 /**
374 * Packages that are being allowed to perform unrestricted app switches. Mapping is
375 * User -> Type -> uid.
376 */
377 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
378
379 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private int mThumbnailWidth;
381 private int mThumbnailHeight;
382 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700383
384 /**
385 * Flag that indicates if multi-window is enabled.
386 *
387 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
388 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
389 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
390 * At least one of the forms of multi-window must be enabled in order for this flag to be
391 * initialized to 'true'.
392 *
393 * @see #mSupportsSplitScreenMultiWindow
394 * @see #mSupportsFreeformWindowManagement
395 * @see #mSupportsPictureInPicture
396 * @see #mSupportsMultiDisplay
397 */
398 boolean mSupportsMultiWindow;
399 boolean mSupportsSplitScreenMultiWindow;
400 boolean mSupportsFreeformWindowManagement;
401 boolean mSupportsPictureInPicture;
402 boolean mSupportsMultiDisplay;
403 boolean mForceResizableActivities;
404
405 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
406
407 // VR Vr2d Display Id.
408 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700409
Wale Ogunwalef6733932018-06-27 05:14:34 -0700410 /**
411 * Set while we are wanting to sleep, to prevent any
412 * activities from being started/resumed.
413 *
414 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
415 *
416 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
417 * while in the sleep state until there is a pending transition out of sleep, in which case
418 * mSleeping is set to false, and remains false while awake.
419 *
420 * Whether mSleeping can quickly toggled between true/false without the device actually
421 * display changing states is undefined.
422 */
423 private boolean mSleeping = false;
424
425 /**
426 * The process state used for processes that are running the top activities.
427 * This changes between TOP and TOP_SLEEPING to following mSleeping.
428 */
429 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
430
431 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
432 // automatically. Important for devices without direct input devices.
433 private boolean mShowDialogs = true;
434
435 /** Set if we are shutting down the system, similar to sleeping. */
436 boolean mShuttingDown = false;
437
438 /**
439 * We want to hold a wake lock while running a voice interaction session, since
440 * this may happen with the screen off and we need to keep the CPU running to
441 * be able to continue to interact with the user.
442 */
443 PowerManager.WakeLock mVoiceWakeLock;
444
445 /**
446 * Set while we are running a voice interaction. This overrides sleeping while it is active.
447 */
448 IVoiceInteractionSession mRunningVoice;
449
450 /**
451 * The last resumed activity. This is identical to the current resumed activity most
452 * of the time but could be different when we're pausing one activity before we resume
453 * another activity.
454 */
455 ActivityRecord mLastResumedActivity;
456
457 /**
458 * The activity that is currently being traced as the active resumed activity.
459 *
460 * @see #updateResumedAppTrace
461 */
462 private @Nullable ActivityRecord mTracedResumedActivity;
463
464 /** If non-null, we are tracking the time the user spends in the currently focused app. */
465 AppTimeTracker mCurAppTimeTracker;
466
467 private FontScaleSettingObserver mFontScaleSettingObserver;
468
469 private final class FontScaleSettingObserver extends ContentObserver {
470 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
471 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
472
473 public FontScaleSettingObserver() {
474 super(mH);
475 final ContentResolver resolver = mContext.getContentResolver();
476 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
477 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
478 UserHandle.USER_ALL);
479 }
480
481 @Override
482 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
483 if (mFontScaleUri.equals(uri)) {
484 updateFontScaleIfNeeded(userId);
485 } else if (mHideErrorDialogsUri.equals(uri)) {
486 synchronized (mGlobalLock) {
487 updateShouldShowDialogsLocked(getGlobalConfiguration());
488 }
489 }
490 }
491 }
492
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700493 ActivityTaskManagerService(Context context) {
494 mContext = context;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 mUiContext = ActivityThread.currentActivityThread().getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700496 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700497 }
498
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700499 void onSystemReady() {
500 mAssistUtils = new AssistUtils(mContext);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700501 mVrController.onSystemReady();
502 mRecentTasks.onSystemReadyLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700503 }
504
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 void onInitPowerManagement() {
506 mStackSupervisor.initPowerManagement();
507 final PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
508 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
509 mVoiceWakeLock.setReferenceCounted(false);
510 }
511
512 void installSystemProviders() {
513 mFontScaleSettingObserver = new FontScaleSettingObserver();
514 }
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 void retrieveSettings(ContentResolver resolver) {
517 final boolean freeformWindowManagement =
518 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
519 || Settings.Global.getInt(
520 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
521
522 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
523 final boolean supportsPictureInPicture = supportsMultiWindow &&
524 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
525 final boolean supportsSplitScreenMultiWindow =
526 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
527 final boolean supportsMultiDisplay = mContext.getPackageManager()
528 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
529 final boolean alwaysFinishActivities =
530 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
531 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
532 final boolean forceResizable = Settings.Global.getInt(
533 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
534
535 // Transfer any global setting for forcing RTL layout, into a System Property
536 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
537
538 final Configuration configuration = new Configuration();
539 Settings.System.getConfiguration(resolver, configuration);
540 if (forceRtl) {
541 // This will take care of setting the correct layout direction flags
542 configuration.setLayoutDirection(configuration.locale);
543 }
544
545 synchronized (mGlobalLock) {
546 mForceResizableActivities = forceResizable;
547 final boolean multiWindowFormEnabled = freeformWindowManagement
548 || supportsSplitScreenMultiWindow
549 || supportsPictureInPicture
550 || supportsMultiDisplay;
551 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
552 mSupportsMultiWindow = true;
553 mSupportsFreeformWindowManagement = freeformWindowManagement;
554 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
555 mSupportsPictureInPicture = supportsPictureInPicture;
556 mSupportsMultiDisplay = supportsMultiDisplay;
557 } else {
558 mSupportsMultiWindow = false;
559 mSupportsFreeformWindowManagement = false;
560 mSupportsSplitScreenMultiWindow = false;
561 mSupportsPictureInPicture = false;
562 mSupportsMultiDisplay = false;
563 }
564 mWindowManager.setForceResizableTasks(mForceResizableActivities);
565 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
566 // This happens before any activities are started, so we can change global configuration
567 // in-place.
568 updateConfigurationLocked(configuration, null, true);
569 final Configuration globalConfig = getGlobalConfiguration();
570 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
571
572 // Load resources only after the current configuration has been set.
573 final Resources res = mContext.getResources();
574 mThumbnailWidth = res.getDimensionPixelSize(
575 com.android.internal.R.dimen.thumbnail_width);
576 mThumbnailHeight = res.getDimensionPixelSize(
577 com.android.internal.R.dimen.thumbnail_height);
578
579 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
580 mFullscreenThumbnailScale = (float) res
581 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
582 (float) globalConfig.screenWidthDp;
583 } else {
584 mFullscreenThumbnailScale = res.getFraction(
585 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
586 }
587 }
588 }
589
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700590 // TODO: Will be converted to WM lock once transition is complete.
591 void setActivityManagerService(ActivityManagerService am) {
592 mAm = am;
593 mGlobalLock = mAm;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700594 mH = new H(mAm.mHandlerThread.getLooper());
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700595 mUiHandler = new UiHandler();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700596
597 mTempConfig.setToDefaults();
598 mTempConfig.setLocales(LocaleList.getDefault());
599 mConfigurationSeq = mTempConfig.seq = 1;
600 mStackSupervisor = createStackSupervisor();
601 mStackSupervisor.onConfigurationChanged(mTempConfig);
602
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700603 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700604 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700605 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700606 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700607 mRecentTasks = createRecentTasks();
608 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700609 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700610 mKeyguardController = mStackSupervisor.getKeyguardController();
611 }
612
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700613 void onActivityManagerInternalAdded() {
614 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
615 }
616
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700617 protected ActivityStackSupervisor createStackSupervisor() {
618 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
619 supervisor.initialize();
620 return supervisor;
621 }
622
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700623 void setWindowManager(WindowManagerService wm) {
624 mWindowManager = wm;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700625 mLockTaskController.setWindowManager(wm);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700626 }
627
Wale Ogunwalef6733932018-06-27 05:14:34 -0700628 UserManagerService getUserManager() {
629 if (mUserManager == null) {
630 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
631 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
632 }
633 return mUserManager;
634 }
635
636 AppOpsService getAppOpsService() {
637 if (mAppOpsService == null) {
638 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
639 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
640 }
641 return mAppOpsService;
642 }
643
644 boolean hasUserRestriction(String restriction, int userId) {
645 return getUserManager().hasUserRestriction(restriction, userId);
646 }
647
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700648 protected RecentTasks createRecentTasks() {
649 return new RecentTasks(this, mStackSupervisor);
650 }
651
652 RecentTasks getRecentTasks() {
653 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700654 }
655
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 ClientLifecycleManager getLifecycleManager() {
657 return mLifecycleManager;
658 }
659
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700660 ActivityStartController getActivityStartController() {
661 return mActivityStartController;
662 }
663
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700664 TaskChangeNotificationController getTaskChangeNotificationController() {
665 return mTaskChangeNotificationController;
666 }
667
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700668 LockTaskController getLockTaskController() {
669 return mLockTaskController;
670 }
671
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700672 private void start() {
673 LocalServices.addService(ActivityTaskManagerInternal.class, new LocalService());
674 }
675
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700676 public static final class Lifecycle extends SystemService {
677 private final ActivityTaskManagerService mService;
678
679 public Lifecycle(Context context) {
680 super(context);
681 mService = new ActivityTaskManagerService(context);
682 }
683
684 @Override
685 public void onStart() {
686 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700687 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700688 }
689
690 public ActivityTaskManagerService getService() {
691 return mService;
692 }
693 }
694
695 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700696 public final int startActivity(IApplicationThread caller, String callingPackage,
697 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
698 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
699 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
700 resultWho, requestCode, startFlags, profilerInfo, bOptions,
701 UserHandle.getCallingUserId());
702 }
703
704 @Override
705 public final int startActivities(IApplicationThread caller, String callingPackage,
706 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
707 int userId) {
708 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700709 enforceNotIsolatedCaller(reason);
710 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700711 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700712 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700713 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason);
714 }
715
716 @Override
717 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
718 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
719 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
720 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
721 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
722 true /*validateIncomingUser*/);
723 }
724
725 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 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700730
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700731 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
733
734 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700735 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700736 .setCaller(caller)
737 .setCallingPackage(callingPackage)
738 .setResolvedType(resolvedType)
739 .setResultTo(resultTo)
740 .setResultWho(resultWho)
741 .setRequestCode(requestCode)
742 .setStartFlags(startFlags)
743 .setProfilerInfo(profilerInfo)
744 .setActivityOptions(bOptions)
745 .setMayWait(userId)
746 .execute();
747
748 }
749
750 @Override
751 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
752 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
754 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700755 // Refuse possible leaked file descriptors
756 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
757 throw new IllegalArgumentException("File descriptors passed in Intent");
758 }
759
760 if (!(target instanceof PendingIntentRecord)) {
761 throw new IllegalArgumentException("Bad PendingIntent object");
762 }
763
764 PendingIntentRecord pir = (PendingIntentRecord)target;
765
766 synchronized (mGlobalLock) {
767 // If this is coming from the currently resumed activity, it is
768 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700769 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700770 if (stack.mResumedActivity != null &&
771 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700773 }
774 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700776 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700777 }
778
779 @Override
780 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
781 Bundle bOptions) {
782 // Refuse possible leaked file descriptors
783 if (intent != null && intent.hasFileDescriptors()) {
784 throw new IllegalArgumentException("File descriptors passed in Intent");
785 }
786 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
787
788 synchronized (mGlobalLock) {
789 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
790 if (r == null) {
791 SafeActivityOptions.abort(options);
792 return false;
793 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700794 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700795 // The caller is not running... d'oh!
796 SafeActivityOptions.abort(options);
797 return false;
798 }
799 intent = new Intent(intent);
800 // The caller is not allowed to change the data.
801 intent.setDataAndType(r.intent.getData(), r.intent.getType());
802 // And we are resetting to find the next component...
803 intent.setComponent(null);
804
805 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
806
807 ActivityInfo aInfo = null;
808 try {
809 List<ResolveInfo> resolves =
810 AppGlobals.getPackageManager().queryIntentActivities(
811 intent, r.resolvedType,
812 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
813 UserHandle.getCallingUserId()).getList();
814
815 // Look for the original activity in the list...
816 final int N = resolves != null ? resolves.size() : 0;
817 for (int i=0; i<N; i++) {
818 ResolveInfo rInfo = resolves.get(i);
819 if (rInfo.activityInfo.packageName.equals(r.packageName)
820 && rInfo.activityInfo.name.equals(r.info.name)) {
821 // We found the current one... the next matching is
822 // after it.
823 i++;
824 if (i<N) {
825 aInfo = resolves.get(i).activityInfo;
826 }
827 if (debug) {
828 Slog.v(TAG, "Next matching activity: found current " + r.packageName
829 + "/" + r.info.name);
830 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
831 ? "null" : aInfo.packageName + "/" + aInfo.name));
832 }
833 break;
834 }
835 }
836 } catch (RemoteException e) {
837 }
838
839 if (aInfo == null) {
840 // Nobody who is next!
841 SafeActivityOptions.abort(options);
842 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
843 return false;
844 }
845
846 intent.setComponent(new ComponentName(
847 aInfo.applicationInfo.packageName, aInfo.name));
848 intent.setFlags(intent.getFlags()&~(
849 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
850 Intent.FLAG_ACTIVITY_CLEAR_TOP|
851 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
852 FLAG_ACTIVITY_NEW_TASK));
853
854 // Okay now we need to start the new activity, replacing the currently running activity.
855 // This is a little tricky because we want to start the new one as if the current one is
856 // finished, but not finish the current one first so that there is no flicker.
857 // And thus...
858 final boolean wasFinishing = r.finishing;
859 r.finishing = true;
860
861 // Propagate reply information over to the new activity.
862 final ActivityRecord resultTo = r.resultTo;
863 final String resultWho = r.resultWho;
864 final int requestCode = r.requestCode;
865 r.resultTo = null;
866 if (resultTo != null) {
867 resultTo.removeResultsLocked(r, resultWho, requestCode);
868 }
869
870 final long origId = Binder.clearCallingIdentity();
871 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700872 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700873 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700874 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700875 .setResolvedType(r.resolvedType)
876 .setActivityInfo(aInfo)
877 .setResultTo(resultTo != null ? resultTo.appToken : null)
878 .setResultWho(resultWho)
879 .setRequestCode(requestCode)
880 .setCallingPid(-1)
881 .setCallingUid(r.launchedFromUid)
882 .setCallingPackage(r.launchedFromPackage)
883 .setRealCallingPid(-1)
884 .setRealCallingUid(r.launchedFromUid)
885 .setActivityOptions(options)
886 .execute();
887 Binder.restoreCallingIdentity(origId);
888
889 r.finishing = wasFinishing;
890 if (res != ActivityManager.START_SUCCESS) {
891 return false;
892 }
893 return true;
894 }
895 }
896
897 @Override
898 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
899 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
900 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
901 final WaitResult res = new WaitResult();
902 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700903 enforceNotIsolatedCaller("startActivityAndWait");
904 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
905 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700906 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700907 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700908 .setCaller(caller)
909 .setCallingPackage(callingPackage)
910 .setResolvedType(resolvedType)
911 .setResultTo(resultTo)
912 .setResultWho(resultWho)
913 .setRequestCode(requestCode)
914 .setStartFlags(startFlags)
915 .setActivityOptions(bOptions)
916 .setMayWait(userId)
917 .setProfilerInfo(profilerInfo)
918 .setWaitResult(res)
919 .execute();
920 }
921 return res;
922 }
923
924 @Override
925 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
926 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
927 int startFlags, Configuration config, Bundle bOptions, int userId) {
928 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700929 enforceNotIsolatedCaller("startActivityWithConfig");
930 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
931 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700932 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700933 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700934 .setCaller(caller)
935 .setCallingPackage(callingPackage)
936 .setResolvedType(resolvedType)
937 .setResultTo(resultTo)
938 .setResultWho(resultWho)
939 .setRequestCode(requestCode)
940 .setStartFlags(startFlags)
941 .setGlobalConfiguration(config)
942 .setActivityOptions(bOptions)
943 .setMayWait(userId)
944 .execute();
945 }
946 }
947
948 @Override
949 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
950 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
951 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
952 int userId) {
953
954 // This is very dangerous -- it allows you to perform a start activity (including
955 // permission grants) as any app that may launch one of your own activities. So
956 // we will only allow this to be done from activities that are part of the core framework,
957 // and then only when they are running as the system.
958 final ActivityRecord sourceRecord;
959 final int targetUid;
960 final String targetPackage;
961 final boolean isResolver;
962 synchronized (mGlobalLock) {
963 if (resultTo == null) {
964 throw new SecurityException("Must be called from an activity");
965 }
966 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
967 if (sourceRecord == null) {
968 throw new SecurityException("Called with bad activity token: " + resultTo);
969 }
970 if (!sourceRecord.info.packageName.equals("android")) {
971 throw new SecurityException(
972 "Must be called from an activity that is declared in the android package");
973 }
974 if (sourceRecord.app == null) {
975 throw new SecurityException("Called without a process attached to activity");
976 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700977 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700978 // This is still okay, as long as this activity is running under the
979 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700980 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700981 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700982 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700983 + " must be system uid or original calling uid "
984 + sourceRecord.launchedFromUid);
985 }
986 }
987 if (ignoreTargetSecurity) {
988 if (intent.getComponent() == null) {
989 throw new SecurityException(
990 "Component must be specified with ignoreTargetSecurity");
991 }
992 if (intent.getSelector() != null) {
993 throw new SecurityException(
994 "Selector not allowed with ignoreTargetSecurity");
995 }
996 }
997 targetUid = sourceRecord.launchedFromUid;
998 targetPackage = sourceRecord.launchedFromPackage;
999 isResolver = sourceRecord.isResolverOrChildActivity();
1000 }
1001
1002 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001003 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 }
1005
1006 // TODO: Switch to user app stacks here.
1007 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001008 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001009 .setCallingUid(targetUid)
1010 .setCallingPackage(targetPackage)
1011 .setResolvedType(resolvedType)
1012 .setResultTo(resultTo)
1013 .setResultWho(resultWho)
1014 .setRequestCode(requestCode)
1015 .setStartFlags(startFlags)
1016 .setActivityOptions(bOptions)
1017 .setMayWait(userId)
1018 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1019 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1020 .execute();
1021 } catch (SecurityException e) {
1022 // XXX need to figure out how to propagate to original app.
1023 // A SecurityException here is generally actually a fault of the original
1024 // calling activity (such as a fairly granting permissions), so propagate it
1025 // back to them.
1026 /*
1027 StringBuilder msg = new StringBuilder();
1028 msg.append("While launching");
1029 msg.append(intent.toString());
1030 msg.append(": ");
1031 msg.append(e.getMessage());
1032 */
1033 throw e;
1034 }
1035 }
1036
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1038 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1039 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1040 }
1041
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 @Override
1043 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1044 Intent intent, String resolvedType, IVoiceInteractionSession session,
1045 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1046 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001047 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 if (session == null || interactor == null) {
1049 throw new NullPointerException("null session or interactor");
1050 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001051 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001053 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001054 .setCallingUid(callingUid)
1055 .setCallingPackage(callingPackage)
1056 .setResolvedType(resolvedType)
1057 .setVoiceSession(session)
1058 .setVoiceInteractor(interactor)
1059 .setStartFlags(startFlags)
1060 .setProfilerInfo(profilerInfo)
1061 .setActivityOptions(bOptions)
1062 .setMayWait(userId)
1063 .execute();
1064 }
1065
1066 @Override
1067 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1068 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001069 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1070 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001072 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 .setCallingUid(callingUid)
1074 .setCallingPackage(callingPackage)
1075 .setResolvedType(resolvedType)
1076 .setActivityOptions(bOptions)
1077 .setMayWait(userId)
1078 .execute();
1079 }
1080
1081 @Override
1082 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1083 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001084 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 final int callingPid = Binder.getCallingPid();
1086 final long origId = Binder.clearCallingIdentity();
1087 try {
1088 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001089 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1090 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091
1092 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1094 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001095 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1096 recentsUid, assistDataReceiver);
1097 }
1098 } finally {
1099 Binder.restoreCallingIdentity(origId);
1100 }
1101 }
1102
1103 @Override
1104 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001105 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 "startActivityFromRecents()");
1107
1108 final int callingPid = Binder.getCallingPid();
1109 final int callingUid = Binder.getCallingUid();
1110 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1111 final long origId = Binder.clearCallingIdentity();
1112 try {
1113 synchronized (mGlobalLock) {
1114 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1115 safeOptions);
1116 }
1117 } finally {
1118 Binder.restoreCallingIdentity(origId);
1119 }
1120 }
1121
1122 /**
1123 * This is the internal entry point for handling Activity.finish().
1124 *
1125 * @param token The Binder token referencing the Activity we want to finish.
1126 * @param resultCode Result code, if any, from this Activity.
1127 * @param resultData Result data (Intent), if any, from this Activity.
1128 * @param finishTask Whether to finish the task associated with this Activity.
1129 *
1130 * @return Returns true if the activity successfully finished, or false if it is still running.
1131 */
1132 @Override
1133 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1134 int finishTask) {
1135 // Refuse possible leaked file descriptors
1136 if (resultData != null && resultData.hasFileDescriptors()) {
1137 throw new IllegalArgumentException("File descriptors passed in Intent");
1138 }
1139
1140 synchronized (mGlobalLock) {
1141 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1142 if (r == null) {
1143 return true;
1144 }
1145 // Keep track of the root activity of the task before we finish it
1146 TaskRecord tr = r.getTask();
1147 ActivityRecord rootR = tr.getRootActivity();
1148 if (rootR == null) {
1149 Slog.w(TAG, "Finishing task with all activities already finished");
1150 }
1151 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1152 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001153 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001154 return false;
1155 }
1156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001157 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1158 // We should consolidate.
1159 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001160 // Find the first activity that is not finishing.
1161 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1162 if (next != null) {
1163 // ask watcher if this is allowed
1164 boolean resumeOK = true;
1165 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001166 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001167 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001168 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001169 Watchdog.getInstance().setActivityController(null);
1170 }
1171
1172 if (!resumeOK) {
1173 Slog.i(TAG, "Not finishing activity because controller resumed");
1174 return false;
1175 }
1176 }
1177 }
1178 final long origId = Binder.clearCallingIdentity();
1179 try {
1180 boolean res;
1181 final boolean finishWithRootActivity =
1182 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1183 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1184 || (finishWithRootActivity && r == rootR)) {
1185 // If requested, remove the task that is associated to this activity only if it
1186 // was the root activity in the task. The result code and data is ignored
1187 // because we don't support returning them across task boundaries. Also, to
1188 // keep backwards compatibility we remove the task from recents when finishing
1189 // task with root activity.
1190 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1191 finishWithRootActivity, "finish-activity");
1192 if (!res) {
1193 Slog.i(TAG, "Removing task failed to finish activity");
1194 }
1195 } else {
1196 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1197 resultData, "app-request", true);
1198 if (!res) {
1199 Slog.i(TAG, "Failed to finish by app-request");
1200 }
1201 }
1202 return res;
1203 } finally {
1204 Binder.restoreCallingIdentity(origId);
1205 }
1206 }
1207 }
1208
1209 @Override
1210 public boolean finishActivityAffinity(IBinder token) {
1211 synchronized (mGlobalLock) {
1212 final long origId = Binder.clearCallingIdentity();
1213 try {
1214 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1215 if (r == null) {
1216 return false;
1217 }
1218
1219 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1220 // can finish.
1221 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001222 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001223 return false;
1224 }
1225 return task.getStack().finishActivityAffinityLocked(r);
1226 } finally {
1227 Binder.restoreCallingIdentity(origId);
1228 }
1229 }
1230 }
1231
1232 @Override
1233 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1234 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001235 try {
1236 WindowProcessController proc = null;
1237 synchronized (mGlobalLock) {
1238 ActivityStack stack = ActivityRecord.getStackLocked(token);
1239 if (stack == null) {
1240 return;
1241 }
1242 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1243 false /* fromTimeout */, false /* processPausingActivities */, config);
1244 if (r != null) {
1245 proc = r.app;
1246 }
1247 if (stopProfiling && proc != null) {
1248 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001249 }
1250 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001251 } finally {
1252 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001253 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001254 }
1255
1256 @Override
1257 public final void activityResumed(IBinder token) {
1258 final long origId = Binder.clearCallingIdentity();
1259 synchronized (mGlobalLock) {
1260 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001261 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001262 }
1263 Binder.restoreCallingIdentity(origId);
1264 }
1265
1266 @Override
1267 public final void activityPaused(IBinder token) {
1268 final long origId = Binder.clearCallingIdentity();
1269 synchronized (mGlobalLock) {
1270 ActivityStack stack = ActivityRecord.getStackLocked(token);
1271 if (stack != null) {
1272 stack.activityPausedLocked(token, false);
1273 }
1274 }
1275 Binder.restoreCallingIdentity(origId);
1276 }
1277
1278 @Override
1279 public final void activityStopped(IBinder token, Bundle icicle,
1280 PersistableBundle persistentState, CharSequence description) {
1281 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1282
1283 // Refuse possible leaked file descriptors
1284 if (icicle != null && icicle.hasFileDescriptors()) {
1285 throw new IllegalArgumentException("File descriptors passed in Bundle");
1286 }
1287
1288 final long origId = Binder.clearCallingIdentity();
1289
1290 synchronized (mGlobalLock) {
1291 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1292 if (r != null) {
1293 r.activityStoppedLocked(icicle, persistentState, description);
1294 }
1295 }
1296
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001297 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298
1299 Binder.restoreCallingIdentity(origId);
1300 }
1301
1302 @Override
1303 public final void activityDestroyed(IBinder token) {
1304 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1305 synchronized (mGlobalLock) {
1306 ActivityStack stack = ActivityRecord.getStackLocked(token);
1307 if (stack != null) {
1308 stack.activityDestroyedLocked(token, "activityDestroyed");
1309 }
1310 }
1311 }
1312
1313 @Override
1314 public final void activityRelaunched(IBinder token) {
1315 final long origId = Binder.clearCallingIdentity();
1316 synchronized (mGlobalLock) {
1317 mStackSupervisor.activityRelaunchedLocked(token);
1318 }
1319 Binder.restoreCallingIdentity(origId);
1320 }
1321
1322 public final void activitySlept(IBinder token) {
1323 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1324
1325 final long origId = Binder.clearCallingIdentity();
1326
1327 synchronized (mGlobalLock) {
1328 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1329 if (r != null) {
1330 mStackSupervisor.activitySleptLocked(r);
1331 }
1332 }
1333
1334 Binder.restoreCallingIdentity(origId);
1335 }
1336
1337 @Override
1338 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1339 synchronized (mGlobalLock) {
1340 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1341 if (r == null) {
1342 return;
1343 }
1344 final long origId = Binder.clearCallingIdentity();
1345 try {
1346 r.setRequestedOrientation(requestedOrientation);
1347 } finally {
1348 Binder.restoreCallingIdentity(origId);
1349 }
1350 }
1351 }
1352
1353 @Override
1354 public int getRequestedOrientation(IBinder token) {
1355 synchronized (mGlobalLock) {
1356 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1357 if (r == null) {
1358 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1359 }
1360 return r.getRequestedOrientation();
1361 }
1362 }
1363
1364 @Override
1365 public void setImmersive(IBinder token, boolean immersive) {
1366 synchronized (mGlobalLock) {
1367 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1368 if (r == null) {
1369 throw new IllegalArgumentException();
1370 }
1371 r.immersive = immersive;
1372
1373 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001374 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001376 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 }
1378 }
1379 }
1380
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001381 void applyUpdateLockStateLocked(ActivityRecord r) {
1382 // Modifications to the UpdateLock state are done on our handler, outside
1383 // the activity manager's locks. The new state is determined based on the
1384 // state *now* of the relevant activity record. The object is passed to
1385 // the handler solely for logging detail, not to be consulted/modified.
1386 final boolean nextState = r != null && r.immersive;
1387 mH.post(() -> {
1388 if (mUpdateLock.isHeld() != nextState) {
1389 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1390 "Applying new update lock state '" + nextState + "' for " + r);
1391 if (nextState) {
1392 mUpdateLock.acquire();
1393 } else {
1394 mUpdateLock.release();
1395 }
1396 }
1397 });
1398 }
1399
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 @Override
1401 public boolean isImmersive(IBinder token) {
1402 synchronized (mGlobalLock) {
1403 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1404 if (r == null) {
1405 throw new IllegalArgumentException();
1406 }
1407 return r.immersive;
1408 }
1409 }
1410
1411 @Override
1412 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001413 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001415 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 return (r != null) ? r.immersive : false;
1417 }
1418 }
1419
1420 @Override
1421 public void overridePendingTransition(IBinder token, String packageName,
1422 int enterAnim, int exitAnim) {
1423 synchronized (mGlobalLock) {
1424 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1425 if (self == null) {
1426 return;
1427 }
1428
1429 final long origId = Binder.clearCallingIdentity();
1430
1431 if (self.isState(
1432 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001433 mWindowManager.overridePendingAppTransition(packageName,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 enterAnim, exitAnim, null);
1435 }
1436
1437 Binder.restoreCallingIdentity(origId);
1438 }
1439 }
1440
1441 @Override
1442 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
1444 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001446 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001447 if (r == null) {
1448 return ActivityManager.COMPAT_MODE_UNKNOWN;
1449 }
1450 ai = r.info.applicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001452
1453 return mAmInternal.getPackageScreenCompatMode(ai);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 }
1455
1456 @Override
1457 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001458 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001460 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001461 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001462 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 if (r == null) {
1464 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1465 return;
1466 }
1467 ai = r.info.applicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001469
1470 mAmInternal.setPackageScreenCompatMode(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 }
1472
1473 @Override
1474 public int getLaunchedFromUid(IBinder activityToken) {
1475 ActivityRecord srec;
1476 synchronized (mGlobalLock) {
1477 srec = ActivityRecord.forTokenLocked(activityToken);
1478 }
1479 if (srec == null) {
1480 return -1;
1481 }
1482 return srec.launchedFromUid;
1483 }
1484
1485 @Override
1486 public String getLaunchedFromPackage(IBinder activityToken) {
1487 ActivityRecord srec;
1488 synchronized (mGlobalLock) {
1489 srec = ActivityRecord.forTokenLocked(activityToken);
1490 }
1491 if (srec == null) {
1492 return null;
1493 }
1494 return srec.launchedFromPackage;
1495 }
1496
1497 @Override
1498 public boolean convertFromTranslucent(IBinder token) {
1499 final long origId = Binder.clearCallingIdentity();
1500 try {
1501 synchronized (mGlobalLock) {
1502 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1503 if (r == null) {
1504 return false;
1505 }
1506 final boolean translucentChanged = r.changeWindowTranslucency(true);
1507 if (translucentChanged) {
1508 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1509 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 return translucentChanged;
1512 }
1513 } finally {
1514 Binder.restoreCallingIdentity(origId);
1515 }
1516 }
1517
1518 @Override
1519 public boolean convertToTranslucent(IBinder token, Bundle options) {
1520 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1521 final long origId = Binder.clearCallingIdentity();
1522 try {
1523 synchronized (mGlobalLock) {
1524 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1525 if (r == null) {
1526 return false;
1527 }
1528 final TaskRecord task = r.getTask();
1529 int index = task.mActivities.lastIndexOf(r);
1530 if (index > 0) {
1531 ActivityRecord under = task.mActivities.get(index - 1);
1532 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1533 }
1534 final boolean translucentChanged = r.changeWindowTranslucency(false);
1535 if (translucentChanged) {
1536 r.getStack().convertActivityToTranslucent(r);
1537 }
1538 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001539 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001540 return translucentChanged;
1541 }
1542 } finally {
1543 Binder.restoreCallingIdentity(origId);
1544 }
1545 }
1546
1547 @Override
1548 public void notifyActivityDrawn(IBinder token) {
1549 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1550 synchronized (mGlobalLock) {
1551 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1552 if (r != null) {
1553 r.getStack().notifyActivityDrawnLocked(r);
1554 }
1555 }
1556 }
1557
1558 @Override
1559 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1560 synchronized (mGlobalLock) {
1561 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1562 if (r == null) {
1563 return;
1564 }
1565 r.reportFullyDrawnLocked(restoredFromBundle);
1566 }
1567 }
1568
1569 @Override
1570 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1571 synchronized (mGlobalLock) {
1572 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1573 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1574 return stack.mDisplayId;
1575 }
1576 return DEFAULT_DISPLAY;
1577 }
1578 }
1579
1580 @Override
1581 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001582 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 long ident = Binder.clearCallingIdentity();
1584 try {
1585 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001586 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001587 if (focusedStack != null) {
1588 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1589 }
1590 return null;
1591 }
1592 } finally {
1593 Binder.restoreCallingIdentity(ident);
1594 }
1595 }
1596
1597 @Override
1598 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001599 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001600 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1601 final long callingId = Binder.clearCallingIdentity();
1602 try {
1603 synchronized (mGlobalLock) {
1604 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1605 if (stack == null) {
1606 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1607 return;
1608 }
1609 final ActivityRecord r = stack.topRunningActivityLocked();
1610 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
1611 r, "setFocusedStack")) {
1612 mStackSupervisor.resumeFocusedStackTopActivityLocked();
1613 }
1614 }
1615 } finally {
1616 Binder.restoreCallingIdentity(callingId);
1617 }
1618 }
1619
1620 @Override
1621 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001622 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1624 final long callingId = Binder.clearCallingIdentity();
1625 try {
1626 synchronized (mGlobalLock) {
1627 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1628 if (task == null) {
1629 return;
1630 }
1631 final ActivityRecord r = task.topRunningActivityLocked();
1632 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedTask")) {
1633 mStackSupervisor.resumeFocusedStackTopActivityLocked();
1634 }
1635 }
1636 } finally {
1637 Binder.restoreCallingIdentity(callingId);
1638 }
1639 }
1640
1641 @Override
1642 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001643 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 synchronized (mGlobalLock) {
1645 final long ident = Binder.clearCallingIdentity();
1646 try {
1647 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1648 "remove-task");
1649 } finally {
1650 Binder.restoreCallingIdentity(ident);
1651 }
1652 }
1653 }
1654
1655 @Override
1656 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1657 synchronized (mGlobalLock) {
1658 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1659 if (srec != null) {
1660 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1661 }
1662 }
1663 return false;
1664 }
1665
1666 @Override
1667 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1668 Intent resultData) {
1669
1670 synchronized (mGlobalLock) {
1671 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1672 if (r != null) {
1673 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1674 }
1675 return false;
1676 }
1677 }
1678
1679 /**
1680 * Attempts to move a task backwards in z-order (the order of activities within the task is
1681 * unchanged).
1682 *
1683 * There are several possible results of this call:
1684 * - if the task is locked, then we will show the lock toast
1685 * - if there is a task behind the provided task, then that task is made visible and resumed as
1686 * this task is moved to the back
1687 * - otherwise, if there are no other tasks in the stack:
1688 * - if this task is in the pinned stack, then we remove the stack completely, which will
1689 * have the effect of moving the task to the top or bottom of the fullscreen stack
1690 * (depending on whether it is visible)
1691 * - otherwise, we simply return home and hide this task
1692 *
1693 * @param token A reference to the activity we wish to move
1694 * @param nonRoot If false then this only works if the activity is the root
1695 * of a task; if true it will work for any activity in a task.
1696 * @return Returns true if the move completed, false if not.
1697 */
1698 @Override
1699 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001700 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 synchronized (mGlobalLock) {
1702 final long origId = Binder.clearCallingIdentity();
1703 try {
1704 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1705 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1706 if (task != null) {
1707 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
1708 }
1709 } finally {
1710 Binder.restoreCallingIdentity(origId);
1711 }
1712 }
1713 return false;
1714 }
1715
1716 @Override
1717 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001718 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 long ident = Binder.clearCallingIdentity();
1720 Rect rect = new Rect();
1721 try {
1722 synchronized (mGlobalLock) {
1723 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1724 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1725 if (task == null) {
1726 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
1727 return rect;
1728 }
1729 if (task.getStack() != null) {
1730 // Return the bounds from window manager since it will be adjusted for various
1731 // things like the presense of a docked stack for tasks that aren't resizeable.
1732 task.getWindowContainerBounds(rect);
1733 } else {
1734 // Task isn't in window manager yet since it isn't associated with a stack.
1735 // Return the persist value from activity manager
1736 if (!task.matchParentBounds()) {
1737 rect.set(task.getBounds());
1738 } else if (task.mLastNonFullscreenBounds != null) {
1739 rect.set(task.mLastNonFullscreenBounds);
1740 }
1741 }
1742 }
1743 } finally {
1744 Binder.restoreCallingIdentity(ident);
1745 }
1746 return rect;
1747 }
1748
1749 @Override
1750 public ActivityManager.TaskDescription getTaskDescription(int id) {
1751 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
1754 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
1755 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1756 if (tr != null) {
1757 return tr.lastTaskDescription;
1758 }
1759 }
1760 return null;
1761 }
1762
1763 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001764 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
1765 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1766 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
1767 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
1768 return;
1769 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001770 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001771 synchronized (mGlobalLock) {
1772 final long ident = Binder.clearCallingIdentity();
1773 try {
1774 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1775 if (task == null) {
1776 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
1777 return;
1778 }
1779
1780 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
1781 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
1782
1783 if (!task.isActivityTypeStandardOrUndefined()) {
1784 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
1785 + " non-standard task " + taskId + " to windowing mode="
1786 + windowingMode);
1787 }
1788
1789 final ActivityStack stack = task.getStack();
1790 if (toTop) {
1791 stack.moveToFront("setTaskWindowingMode", task);
1792 }
1793 stack.setWindowingMode(windowingMode);
1794 } finally {
1795 Binder.restoreCallingIdentity(ident);
1796 }
1797 }
1798 }
1799
1800 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 ActivityRecord r = getCallingRecordLocked(token);
1804 return r != null ? r.info.packageName : null;
1805 }
1806 }
1807
1808 @Override
1809 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001810 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 ActivityRecord r = getCallingRecordLocked(token);
1812 return r != null ? r.intent.getComponent() : null;
1813 }
1814 }
1815
1816 private ActivityRecord getCallingRecordLocked(IBinder token) {
1817 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1818 if (r == null) {
1819 return null;
1820 }
1821 return r.resultTo;
1822 }
1823
1824 @Override
1825 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001826 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001827
1828 synchronized (mGlobalLock) {
1829 final long origId = Binder.clearCallingIdentity();
1830 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001831 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 } finally {
1833 Binder.restoreCallingIdentity(origId);
1834 }
1835 }
1836 }
1837
1838 /**
1839 * TODO: Add mController hook
1840 */
1841 @Override
1842 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001843 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844
1845 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
1846 synchronized (mGlobalLock) {
1847 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
1848 false /* fromRecents */);
1849 }
1850 }
1851
1852 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
1853 boolean fromRecents) {
1854
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 Binder.getCallingUid(), -1, -1, "Task to front")) {
1857 SafeActivityOptions.abort(options);
1858 return;
1859 }
1860 final long origId = Binder.clearCallingIdentity();
1861 try {
1862 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1863 if (task == null) {
1864 Slog.d(TAG, "Could not find task for id: "+ taskId);
1865 return;
1866 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001867 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
1869 return;
1870 }
1871 ActivityOptions realOptions = options != null
1872 ? options.getOptions(mStackSupervisor)
1873 : null;
1874 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
1875 false /* forceNonResizable */);
1876
1877 final ActivityRecord topActivity = task.getTopActivity();
1878 if (topActivity != null) {
1879
1880 // We are reshowing a task, use a starting window to hide the initial draw delay
1881 // so the transition can start earlier.
1882 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
1883 true /* taskSwitch */, fromRecents);
1884 }
1885 } finally {
1886 Binder.restoreCallingIdentity(origId);
1887 }
1888 SafeActivityOptions.abort(options);
1889 }
1890
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
1892 int callingPid, int callingUid, String name) {
1893 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
1894 return true;
1895 }
1896
1897 if (getRecentTasks().isCallerRecents(sourceUid)) {
1898 return true;
1899 }
1900
1901 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
1902 if (perm == PackageManager.PERMISSION_GRANTED) {
1903 return true;
1904 }
1905 if (checkAllowAppSwitchUid(sourceUid)) {
1906 return true;
1907 }
1908
1909 // If the actual IPC caller is different from the logical source, then
1910 // also see if they are allowed to control app switches.
1911 if (callingUid != -1 && callingUid != sourceUid) {
1912 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
1913 if (perm == PackageManager.PERMISSION_GRANTED) {
1914 return true;
1915 }
1916 if (checkAllowAppSwitchUid(callingUid)) {
1917 return true;
1918 }
1919 }
1920
1921 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
1922 return false;
1923 }
1924
1925 private boolean checkAllowAppSwitchUid(int uid) {
1926 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
1927 if (types != null) {
1928 for (int i = types.size() - 1; i >= 0; i--) {
1929 if (types.valueAt(i).intValue() == uid) {
1930 return true;
1931 }
1932 }
1933 }
1934 return false;
1935 }
1936
1937 @Override
1938 public void setActivityController(IActivityController controller, boolean imAMonkey) {
1939 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
1940 "setActivityController()");
1941 synchronized (mGlobalLock) {
1942 mController = controller;
1943 mControllerIsAMonkey = imAMonkey;
1944 Watchdog.getInstance().setActivityController(controller);
1945 }
1946 }
1947
1948 boolean isControllerAMonkey() {
1949 synchronized (mGlobalLock) {
1950 return mController != null && mControllerIsAMonkey;
1951 }
1952 }
1953
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 @Override
1955 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
1956 synchronized (mGlobalLock) {
1957 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
1958 }
1959 }
1960
1961 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001962 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
1963 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
1964 }
1965
1966 @Override
1967 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
1968 @WindowConfiguration.ActivityType int ignoreActivityType,
1969 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
1970 final int callingUid = Binder.getCallingUid();
1971 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
1972
1973 synchronized (mGlobalLock) {
1974 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
1975
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001976 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001977 callingUid);
1978 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
1979 ignoreWindowingMode, callingUid, allowed);
1980 }
1981
1982 return list;
1983 }
1984
1985 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
1987 synchronized (mGlobalLock) {
1988 final long origId = Binder.clearCallingIdentity();
1989 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1990 if (r != null) {
1991 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
1992 }
1993 Binder.restoreCallingIdentity(origId);
1994 }
1995 }
1996
1997 @Override
1998 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001999 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 ActivityStack stack = ActivityRecord.getStackLocked(token);
2001 if (stack != null) {
2002 return stack.willActivityBeVisibleLocked(token);
2003 }
2004 return false;
2005 }
2006 }
2007
2008 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002009 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002010 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002011 synchronized (mGlobalLock) {
2012 final long ident = Binder.clearCallingIdentity();
2013 try {
2014 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2015 if (task == null) {
2016 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2017 return;
2018 }
2019
2020 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2021 + " to stackId=" + stackId + " toTop=" + toTop);
2022
2023 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2024 if (stack == null) {
2025 throw new IllegalStateException(
2026 "moveTaskToStack: No stack for stackId=" + stackId);
2027 }
2028 if (!stack.isActivityTypeStandardOrUndefined()) {
2029 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2030 + taskId + " to stack " + stackId);
2031 }
2032 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002034 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2035 }
2036 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2037 "moveTaskToStack");
2038 } finally {
2039 Binder.restoreCallingIdentity(ident);
2040 }
2041 }
2042 }
2043
2044 @Override
2045 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2046 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002047 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002048
2049 final long ident = Binder.clearCallingIdentity();
2050 try {
2051 synchronized (mGlobalLock) {
2052 if (animate) {
2053 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2054 if (stack == null) {
2055 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2056 return;
2057 }
2058 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2059 throw new IllegalArgumentException("Stack: " + stackId
2060 + " doesn't support animated resize.");
2061 }
2062 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2063 animationDuration, false /* fromFullscreen */);
2064 } else {
2065 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2066 if (stack == null) {
2067 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2068 return;
2069 }
2070 mStackSupervisor.resizeStackLocked(stack, destBounds,
2071 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2072 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2073 }
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(ident);
2077 }
2078 }
2079
2080 /**
2081 * Moves the specified task to the primary-split-screen stack.
2082 *
2083 * @param taskId Id of task to move.
2084 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2085 * exist already. See
2086 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2087 * and
2088 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2089 * @param toTop If the task and stack should be moved to the top.
2090 * @param animate Whether we should play an animation for the moving the task.
2091 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2092 * stack. Pass {@code null} to use default bounds.
2093 * @param showRecents If the recents activity should be shown on the other side of the task
2094 * going into split-screen mode.
2095 */
2096 @Override
2097 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2098 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002099 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002100 "setTaskWindowingModeSplitScreenPrimary()");
2101 synchronized (mGlobalLock) {
2102 final long ident = Binder.clearCallingIdentity();
2103 try {
2104 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2105 if (task == null) {
2106 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2107 return false;
2108 }
2109 if (DEBUG_STACK) Slog.d(TAG_STACK,
2110 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2111 + " to createMode=" + createMode + " toTop=" + toTop);
2112 if (!task.isActivityTypeStandardOrUndefined()) {
2113 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2114 + " non-standard task " + taskId + " to split-screen windowing mode");
2115 }
2116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002117 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002118 final int windowingMode = task.getWindowingMode();
2119 final ActivityStack stack = task.getStack();
2120 if (toTop) {
2121 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2122 }
2123 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2124 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2125 return windowingMode != task.getWindowingMode();
2126 } finally {
2127 Binder.restoreCallingIdentity(ident);
2128 }
2129 }
2130 }
2131
2132 /**
2133 * Removes stacks in the input windowing modes from the system if they are of activity type
2134 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2135 */
2136 @Override
2137 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002138 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002139 "removeStacksInWindowingModes()");
2140
2141 synchronized (mGlobalLock) {
2142 final long ident = Binder.clearCallingIdentity();
2143 try {
2144 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2145 } finally {
2146 Binder.restoreCallingIdentity(ident);
2147 }
2148 }
2149 }
2150
2151 @Override
2152 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002153 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002154 "removeStacksWithActivityTypes()");
2155
2156 synchronized (mGlobalLock) {
2157 final long ident = Binder.clearCallingIdentity();
2158 try {
2159 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2160 } finally {
2161 Binder.restoreCallingIdentity(ident);
2162 }
2163 }
2164 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165
2166 @Override
2167 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2168 int userId) {
2169 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002170 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2171 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002173 final boolean detailed = checkGetTasksPermission(
2174 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2175 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 == PackageManager.PERMISSION_GRANTED;
2177
2178 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002179 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 callingUid);
2181 }
2182 }
2183
2184 @Override
2185 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002186 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002187 long ident = Binder.clearCallingIdentity();
2188 try {
2189 synchronized (mGlobalLock) {
2190 return mStackSupervisor.getAllStackInfosLocked();
2191 }
2192 } finally {
2193 Binder.restoreCallingIdentity(ident);
2194 }
2195 }
2196
2197 @Override
2198 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002199 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 long ident = Binder.clearCallingIdentity();
2201 try {
2202 synchronized (mGlobalLock) {
2203 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2204 }
2205 } finally {
2206 Binder.restoreCallingIdentity(ident);
2207 }
2208 }
2209
2210 @Override
2211 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 final long callingUid = Binder.getCallingUid();
2214 final long origId = Binder.clearCallingIdentity();
2215 try {
2216 synchronized (mGlobalLock) {
2217 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002218 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2220 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2221 }
2222 } finally {
2223 Binder.restoreCallingIdentity(origId);
2224 }
2225 }
2226
2227 @Override
2228 public void startLockTaskModeByToken(IBinder token) {
2229 synchronized (mGlobalLock) {
2230 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2231 if (r == null) {
2232 return;
2233 }
2234 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2235 }
2236 }
2237
2238 @Override
2239 public void startSystemLockTaskMode(int taskId) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002240 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 // This makes inner call to look as if it was initiated by system.
2242 long ident = Binder.clearCallingIdentity();
2243 try {
2244 synchronized (mGlobalLock) {
2245 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2246
2247 // When starting lock task mode the stack must be in front and focused
2248 task.getStack().moveToFront("startSystemLockTaskMode");
2249 startLockTaskModeLocked(task, true /* isSystemCaller */);
2250 }
2251 } finally {
2252 Binder.restoreCallingIdentity(ident);
2253 }
2254 }
2255
2256 @Override
2257 public void stopLockTaskModeByToken(IBinder token) {
2258 synchronized (mGlobalLock) {
2259 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2260 if (r == null) {
2261 return;
2262 }
2263 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2264 }
2265 }
2266
2267 /**
2268 * This API should be called by SystemUI only when user perform certain action to dismiss
2269 * lock task mode. We should only dismiss pinned lock task mode in this case.
2270 */
2271 @Override
2272 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002273 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002274 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2275 }
2276
2277 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2278 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2279 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2280 return;
2281 }
2282
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002283 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002284 if (stack == null || task != stack.topTask()) {
2285 throw new IllegalArgumentException("Invalid task, not in foreground");
2286 }
2287
2288 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2289 // system or a specific app.
2290 // * System-initiated requests will only start the pinned mode (screen pinning)
2291 // * App-initiated requests
2292 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2293 // - will start the pinned mode, otherwise
2294 final int callingUid = Binder.getCallingUid();
2295 long ident = Binder.clearCallingIdentity();
2296 try {
2297 // When a task is locked, dismiss the pinned stack if it exists
2298 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2299
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002300 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301 } finally {
2302 Binder.restoreCallingIdentity(ident);
2303 }
2304 }
2305
2306 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2307 final int callingUid = Binder.getCallingUid();
2308 long ident = Binder.clearCallingIdentity();
2309 try {
2310 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002311 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 }
2313 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2314 // task and jumping straight into a call in the case of emergency call back.
2315 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2316 if (tm != null) {
2317 tm.showInCallScreen(false);
2318 }
2319 } finally {
2320 Binder.restoreCallingIdentity(ident);
2321 }
2322 }
2323
2324 @Override
2325 public boolean isInLockTaskMode() {
2326 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2327 }
2328
2329 @Override
2330 public int getLockTaskModeState() {
2331 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002332 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002333 }
2334 }
2335
2336 @Override
2337 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2338 synchronized (mGlobalLock) {
2339 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2340 if (r != null) {
2341 r.setTaskDescription(td);
2342 final TaskRecord task = r.getTask();
2343 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002344 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345 }
2346 }
2347 }
2348
2349 @Override
2350 public Bundle getActivityOptions(IBinder token) {
2351 final long origId = Binder.clearCallingIdentity();
2352 try {
2353 synchronized (mGlobalLock) {
2354 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2355 if (r != null) {
2356 final ActivityOptions activityOptions = r.takeOptionsLocked();
2357 return activityOptions == null ? null : activityOptions.toBundle();
2358 }
2359 return null;
2360 }
2361 } finally {
2362 Binder.restoreCallingIdentity(origId);
2363 }
2364 }
2365
2366 @Override
2367 public List<IBinder> getAppTasks(String callingPackage) {
2368 int callingUid = Binder.getCallingUid();
2369 long ident = Binder.clearCallingIdentity();
2370 try {
2371 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002372 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 }
2374 } finally {
2375 Binder.restoreCallingIdentity(ident);
2376 }
2377 }
2378
2379 @Override
2380 public void finishVoiceTask(IVoiceInteractionSession session) {
2381 synchronized (mGlobalLock) {
2382 final long origId = Binder.clearCallingIdentity();
2383 try {
2384 // TODO: VI Consider treating local voice interactions and voice tasks
2385 // differently here
2386 mStackSupervisor.finishVoiceTask(session);
2387 } finally {
2388 Binder.restoreCallingIdentity(origId);
2389 }
2390 }
2391
2392 }
2393
2394 @Override
2395 public boolean isTopOfTask(IBinder token) {
2396 synchronized (mGlobalLock) {
2397 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002398 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 }
2400 }
2401
2402 @Override
2403 public void notifyLaunchTaskBehindComplete(IBinder token) {
2404 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2405 }
2406
2407 @Override
2408 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002409 mH.post(() -> {
2410 synchronized (mGlobalLock) {
2411 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002412 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002413 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002414 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002415 } catch (RemoteException e) {
2416 }
2417 }
2418 }
2419
2420 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002421 }
2422
2423 /** Called from an app when assist data is ready. */
2424 @Override
2425 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2426 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002427 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002428 synchronized (pae) {
2429 pae.result = extras;
2430 pae.structure = structure;
2431 pae.content = content;
2432 if (referrer != null) {
2433 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2434 }
2435 if (structure != null) {
2436 structure.setHomeActivity(pae.isHome);
2437 }
2438 pae.haveResult = true;
2439 pae.notifyAll();
2440 if (pae.intent == null && pae.receiver == null) {
2441 // Caller is just waiting for the result.
2442 return;
2443 }
2444 }
2445 // We are now ready to launch the assist activity.
2446 IAssistDataReceiver sendReceiver = null;
2447 Bundle sendBundle = null;
2448 synchronized (mGlobalLock) {
2449 buildAssistBundleLocked(pae, extras);
2450 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002451 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002452 if (!exists) {
2453 // Timed out.
2454 return;
2455 }
2456
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002457 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002458 // Caller wants result sent back to them.
2459 sendBundle = new Bundle();
2460 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2461 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2462 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2463 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2464 }
2465 }
2466 if (sendReceiver != null) {
2467 try {
2468 sendReceiver.onHandleAssistData(sendBundle);
2469 } catch (RemoteException e) {
2470 }
2471 return;
2472 }
2473
2474 final long ident = Binder.clearCallingIdentity();
2475 try {
2476 if (TextUtils.equals(pae.intent.getAction(),
2477 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2478 pae.intent.putExtras(pae.extras);
2479 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2480 } else {
2481 pae.intent.replaceExtras(pae.extras);
2482 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2483 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2484 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002485 mAmInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486
2487 try {
2488 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2489 } catch (ActivityNotFoundException e) {
2490 Slog.w(TAG, "No activity to handle assist action.", e);
2491 }
2492 }
2493 } finally {
2494 Binder.restoreCallingIdentity(ident);
2495 }
2496 }
2497
2498 @Override
2499 public int addAppTask(IBinder activityToken, Intent intent,
2500 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2501 final int callingUid = Binder.getCallingUid();
2502 final long callingIdent = Binder.clearCallingIdentity();
2503
2504 try {
2505 synchronized (mGlobalLock) {
2506 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2507 if (r == null) {
2508 throw new IllegalArgumentException("Activity does not exist; token="
2509 + activityToken);
2510 }
2511 ComponentName comp = intent.getComponent();
2512 if (comp == null) {
2513 throw new IllegalArgumentException("Intent " + intent
2514 + " must specify explicit component");
2515 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002516 if (thumbnail.getWidth() != mThumbnailWidth
2517 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 throw new IllegalArgumentException("Bad thumbnail size: got "
2519 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002520 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002521 }
2522 if (intent.getSelector() != null) {
2523 intent.setSelector(null);
2524 }
2525 if (intent.getSourceBounds() != null) {
2526 intent.setSourceBounds(null);
2527 }
2528 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2529 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2530 // The caller has added this as an auto-remove task... that makes no
2531 // sense, so turn off auto-remove.
2532 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2533 }
2534 }
2535 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2536 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2537 if (ainfo.applicationInfo.uid != callingUid) {
2538 throw new SecurityException(
2539 "Can't add task for another application: target uid="
2540 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2541 }
2542
2543 final ActivityStack stack = r.getStack();
2544 final TaskRecord task = stack.createTaskRecord(
2545 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2546 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002547 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 // The app has too many tasks already and we can't add any more
2549 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2550 return INVALID_TASK_ID;
2551 }
2552 task.lastTaskDescription.copyFrom(description);
2553
2554 // TODO: Send the thumbnail to WM to store it.
2555
2556 return task.taskId;
2557 }
2558 } finally {
2559 Binder.restoreCallingIdentity(callingIdent);
2560 }
2561 }
2562
2563 @Override
2564 public Point getAppTaskThumbnailSize() {
2565 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002566 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002567 }
2568 }
2569
2570 @Override
2571 public void setTaskResizeable(int taskId, int resizeableMode) {
2572 synchronized (mGlobalLock) {
2573 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2574 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2575 if (task == null) {
2576 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2577 return;
2578 }
2579 task.setResizeMode(resizeableMode);
2580 }
2581 }
2582
2583 @Override
2584 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002585 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 long ident = Binder.clearCallingIdentity();
2587 try {
2588 synchronized (mGlobalLock) {
2589 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2590 if (task == null) {
2591 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2592 return;
2593 }
2594 // Place the task in the right stack if it isn't there already based on
2595 // the requested bounds.
2596 // The stack transition logic is:
2597 // - a null bounds on a freeform task moves that task to fullscreen
2598 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2599 // that task to freeform
2600 // - otherwise the task is not moved
2601 ActivityStack stack = task.getStack();
2602 if (!task.getWindowConfiguration().canResizeTask()) {
2603 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2604 }
2605 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2606 stack = stack.getDisplay().getOrCreateStack(
2607 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2608 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2609 stack = stack.getDisplay().getOrCreateStack(
2610 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2611 }
2612
2613 // Reparent the task to the right stack if necessary
2614 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2615 if (stack != task.getStack()) {
2616 // Defer resume until the task is resized below
2617 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2618 DEFER_RESUME, "resizeTask");
2619 preserveWindow = false;
2620 }
2621
2622 // After reparenting (which only resizes the task to the stack bounds), resize the
2623 // task to the actual bounds provided
2624 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(ident);
2628 }
2629 }
2630
2631 @Override
2632 public boolean releaseActivityInstance(IBinder token) {
2633 synchronized (mGlobalLock) {
2634 final long origId = Binder.clearCallingIdentity();
2635 try {
2636 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2637 if (r == null) {
2638 return false;
2639 }
2640 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2641 } finally {
2642 Binder.restoreCallingIdentity(origId);
2643 }
2644 }
2645 }
2646
2647 @Override
2648 public void releaseSomeActivities(IApplicationThread appInt) {
2649 synchronized (mGlobalLock) {
2650 final long origId = Binder.clearCallingIdentity();
2651 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002652 WindowProcessController app =
2653 mAm.getRecordForAppLocked(appInt).getWindowProcessController();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2655 } finally {
2656 Binder.restoreCallingIdentity(origId);
2657 }
2658 }
2659 }
2660
2661 @Override
2662 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
2663 int secondaryDisplayShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002664 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 != PackageManager.PERMISSION_GRANTED) {
2666 throw new SecurityException("Requires permission "
2667 + android.Manifest.permission.DEVICE_POWER);
2668 }
2669
2670 synchronized (mGlobalLock) {
2671 long ident = Binder.clearCallingIdentity();
2672 if (mKeyguardShown != keyguardShowing) {
2673 mKeyguardShown = keyguardShowing;
2674 reportCurKeyguardUsageEventLocked(keyguardShowing);
2675 }
2676 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002677 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 secondaryDisplayShowing);
2679 } finally {
2680 Binder.restoreCallingIdentity(ident);
2681 }
2682 }
2683
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002684 mH.post(() -> {
2685 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2686 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2687 }
2688 });
2689 }
2690
2691 void onScreenAwakeChanged(boolean isAwake) {
2692 mH.post(() -> {
2693 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2694 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2695 }
2696 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002697 }
2698
2699 @Override
2700 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002701 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2702 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002703
2704 final File passedIconFile = new File(filePath);
2705 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2706 passedIconFile.getName());
2707 if (!legitIconFile.getPath().equals(filePath)
2708 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2709 throw new IllegalArgumentException("Bad file path: " + filePath
2710 + " passed for userId " + userId);
2711 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002712 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713 }
2714
2715 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002716 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002717 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2718 final ActivityOptions activityOptions = safeOptions != null
2719 ? safeOptions.getOptions(mStackSupervisor)
2720 : null;
2721 if (activityOptions == null
2722 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2723 || activityOptions.getCustomInPlaceResId() == 0) {
2724 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2725 "with valid animation");
2726 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002727 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2728 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729 activityOptions.getCustomInPlaceResId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002730 mWindowManager.executeAppTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002731 }
2732
2733 @Override
2734 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002735 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 synchronized (mGlobalLock) {
2737 final long ident = Binder.clearCallingIdentity();
2738 try {
2739 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2740 if (stack == null) {
2741 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2742 return;
2743 }
2744 if (!stack.isActivityTypeStandardOrUndefined()) {
2745 throw new IllegalArgumentException(
2746 "Removing non-standard stack is not allowed.");
2747 }
2748 mStackSupervisor.removeStack(stack);
2749 } finally {
2750 Binder.restoreCallingIdentity(ident);
2751 }
2752 }
2753 }
2754
2755 @Override
2756 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002757 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758
2759 synchronized (mGlobalLock) {
2760 final long ident = Binder.clearCallingIdentity();
2761 try {
2762 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
2763 + " to displayId=" + displayId);
2764 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
2765 } finally {
2766 Binder.restoreCallingIdentity(ident);
2767 }
2768 }
2769 }
2770
2771 @Override
2772 public int createStackOnDisplay(int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createStackOnDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 synchronized (mGlobalLock) {
2775 final ActivityDisplay display =
2776 mStackSupervisor.getActivityDisplayOrCreateLocked(displayId);
2777 if (display == null) {
2778 return INVALID_STACK_ID;
2779 }
2780 // TODO(multi-display): Have the caller pass in the windowing mode and activity type.
2781 final ActivityStack stack = display.createStack(
2782 WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD,
2783 ON_TOP);
2784 return (stack != null) ? stack.mStackId : INVALID_STACK_ID;
2785 }
2786 }
2787
2788 @Override
2789 public void exitFreeformMode(IBinder token) {
2790 synchronized (mGlobalLock) {
2791 long ident = Binder.clearCallingIdentity();
2792 try {
2793 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2794 if (r == null) {
2795 throw new IllegalArgumentException(
2796 "exitFreeformMode: No activity record matching token=" + token);
2797 }
2798
2799 final ActivityStack stack = r.getStack();
2800 if (stack == null || !stack.inFreeformWindowingMode()) {
2801 throw new IllegalStateException(
2802 "exitFreeformMode: You can only go fullscreen from freeform.");
2803 }
2804
2805 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
2806 } finally {
2807 Binder.restoreCallingIdentity(ident);
2808 }
2809 }
2810 }
2811
2812 /** Sets the task stack listener that gets callbacks when a task stack changes. */
2813 @Override
2814 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002815 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002817 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 }
2819
2820 /** Unregister a task stack listener so that it stops receiving callbacks. */
2821 @Override
2822 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002823 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002825 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827
2828 private void reportCurKeyguardUsageEventLocked(boolean keyguardShowing) {
2829 mAm.reportGlobalUsageEventLocked(keyguardShowing
2830 ? UsageEvents.Event.KEYGUARD_SHOWN
2831 : UsageEvents.Event.KEYGUARD_HIDDEN);
2832 }
2833
2834 @Override
2835 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
2836 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
2837 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
2838 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
2839 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
2840 }
2841
2842 @Override
2843 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
2844 IBinder activityToken, int flags) {
2845 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
2846 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
2847 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
2848 }
2849
2850 @Override
2851 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
2852 Bundle args) {
2853 return enqueueAssistContext(requestType, intent, hint, null, null, null,
2854 true /* focused */, true /* newSessionId */, userHandle, args,
2855 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
2856 }
2857
2858 @Override
2859 public Bundle getAssistContextExtras(int requestType) {
2860 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
2861 null, null, true /* focused */, true /* newSessionId */,
2862 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
2863 if (pae == null) {
2864 return null;
2865 }
2866 synchronized (pae) {
2867 while (!pae.haveResult) {
2868 try {
2869 pae.wait();
2870 } catch (InterruptedException e) {
2871 }
2872 }
2873 }
2874 synchronized (mGlobalLock) {
2875 buildAssistBundleLocked(pae, pae.result);
2876 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002877 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002878 }
2879 return pae.extras;
2880 }
2881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002882 /**
2883 * Binder IPC calls go through the public entry point.
2884 * This can be called with or without the global lock held.
2885 */
2886 private static int checkCallingPermission(String permission) {
2887 return checkPermission(
2888 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
2889 }
2890
2891 /** This can be called with or without the global lock held. */
2892 void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
2893 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
2894 mAmInternal.enforceCallingPermission(permission, func);
2895 }
2896 }
2897
2898 @VisibleForTesting
2899 int checkGetTasksPermission(String permission, int pid, int uid) {
2900 return checkPermission(permission, pid, uid);
2901 }
2902
2903 static int checkPermission(String permission, int pid, int uid) {
2904 if (permission == null) {
2905 return PackageManager.PERMISSION_DENIED;
2906 }
2907 return checkComponentPermission(permission, pid, uid, -1, true);
2908 }
2909
2910 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
2911 if (getRecentTasks().isCallerRecents(callingUid)) {
2912 // Always allow the recents component to get tasks
2913 return true;
2914 }
2915
2916 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
2917 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2918 if (!allowed) {
2919 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
2920 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
2921 // Temporary compatibility: some existing apps on the system image may
2922 // still be requesting the old permission and not switched to the new
2923 // one; if so, we'll still allow them full access. This means we need
2924 // to see if they are holding the old permission and are a system app.
2925 try {
2926 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
2927 allowed = true;
2928 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2929 + " is using old GET_TASKS but privileged; allowing");
2930 }
2931 } catch (RemoteException e) {
2932 }
2933 }
2934 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2935 + " does not hold REAL_GET_TASKS; limiting output");
2936 }
2937 return allowed;
2938 }
2939
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
2941 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
2942 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
2943 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002944 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 "enqueueAssistContext()");
2946
2947 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002948 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 if (activity == null) {
2950 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
2951 return null;
2952 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002953 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
2955 return null;
2956 }
2957 if (focused) {
2958 if (activityToken != null) {
2959 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
2960 if (activity != caller) {
2961 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
2962 + " is not current top " + activity);
2963 return null;
2964 }
2965 }
2966 } else {
2967 activity = ActivityRecord.forTokenLocked(activityToken);
2968 if (activity == null) {
2969 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
2970 + " couldn't be found");
2971 return null;
2972 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002973 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
2975 return null;
2976 }
2977 }
2978
2979 PendingAssistExtras pae;
2980 Bundle extras = new Bundle();
2981 if (args != null) {
2982 extras.putAll(args);
2983 }
2984 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002985 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986
2987 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
2988 userHandle);
2989 pae.isHome = activity.isActivityTypeHome();
2990
2991 // Increment the sessionId if necessary
2992 if (newSessionId) {
2993 mViSessionId++;
2994 }
2995 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002996 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
2997 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002998 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002999 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 } catch (RemoteException e) {
3001 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3002 return null;
3003 }
3004 return pae;
3005 }
3006 }
3007
3008 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3009 if (result != null) {
3010 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3011 }
3012 if (pae.hint != null) {
3013 pae.extras.putBoolean(pae.hint, true);
3014 }
3015 }
3016
3017 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3018 IAssistDataReceiver receiver;
3019 synchronized (mGlobalLock) {
3020 mPendingAssistExtras.remove(pae);
3021 receiver = pae.receiver;
3022 }
3023 if (receiver != null) {
3024 // Caller wants result sent back to them.
3025 Bundle sendBundle = new Bundle();
3026 // At least return the receiver extras
3027 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3028 try {
3029 pae.receiver.onHandleAssistData(sendBundle);
3030 } catch (RemoteException e) {
3031 }
3032 }
3033 }
3034
3035 public class PendingAssistExtras extends Binder implements Runnable {
3036 public final ActivityRecord activity;
3037 public boolean isHome;
3038 public final Bundle extras;
3039 public final Intent intent;
3040 public final String hint;
3041 public final IAssistDataReceiver receiver;
3042 public final int userHandle;
3043 public boolean haveResult = false;
3044 public Bundle result = null;
3045 public AssistStructure structure = null;
3046 public AssistContent content = null;
3047 public Bundle receiverExtras;
3048
3049 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3050 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3051 int _userHandle) {
3052 activity = _activity;
3053 extras = _extras;
3054 intent = _intent;
3055 hint = _hint;
3056 receiver = _receiver;
3057 receiverExtras = _receiverExtras;
3058 userHandle = _userHandle;
3059 }
3060
3061 @Override
3062 public void run() {
3063 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3064 synchronized (this) {
3065 haveResult = true;
3066 notifyAll();
3067 }
3068 pendingAssistExtrasTimedOut(this);
3069 }
3070 }
3071
3072 @Override
3073 public boolean isAssistDataAllowedOnCurrentActivity() {
3074 int userId;
3075 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003076 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3078 return false;
3079 }
3080
3081 final ActivityRecord activity = focusedStack.getTopActivity();
3082 if (activity == null) {
3083 return false;
3084 }
3085 userId = activity.userId;
3086 }
3087 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3088 }
3089
3090 @Override
3091 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3092 long ident = Binder.clearCallingIdentity();
3093 try {
3094 synchronized (mGlobalLock) {
3095 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003096 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 if (top != caller) {
3098 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3099 + " is not current top " + top);
3100 return false;
3101 }
3102 if (!top.nowVisible) {
3103 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3104 + " is not visible");
3105 return false;
3106 }
3107 }
3108 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3109 token);
3110 } finally {
3111 Binder.restoreCallingIdentity(ident);
3112 }
3113 }
3114
3115 @Override
3116 public boolean isRootVoiceInteraction(IBinder token) {
3117 synchronized (mGlobalLock) {
3118 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3119 if (r == null) {
3120 return false;
3121 }
3122 return r.rootVoiceInteraction;
3123 }
3124 }
3125
Wale Ogunwalef6733932018-06-27 05:14:34 -07003126 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3127 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3128 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3129 if (activityToCallback == null) return;
3130 activityToCallback.setVoiceSessionLocked(voiceSession);
3131
3132 // Inform the activity
3133 try {
3134 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3135 voiceInteractor);
3136 long token = Binder.clearCallingIdentity();
3137 try {
3138 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3139 } finally {
3140 Binder.restoreCallingIdentity(token);
3141 }
3142 // TODO: VI Should we cache the activity so that it's easier to find later
3143 // rather than scan through all the stacks and activities?
3144 } catch (RemoteException re) {
3145 activityToCallback.clearVoiceSessionLocked();
3146 // TODO: VI Should this terminate the voice session?
3147 }
3148 }
3149
3150 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3151 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3152 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3153 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3154 boolean wasRunningVoice = mRunningVoice != null;
3155 mRunningVoice = session;
3156 if (!wasRunningVoice) {
3157 mVoiceWakeLock.acquire();
3158 updateSleepIfNeededLocked();
3159 }
3160 }
3161 }
3162
3163 void finishRunningVoiceLocked() {
3164 if (mRunningVoice != null) {
3165 mRunningVoice = null;
3166 mVoiceWakeLock.release();
3167 updateSleepIfNeededLocked();
3168 }
3169 }
3170
3171 @Override
3172 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3173 synchronized (mGlobalLock) {
3174 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3175 if (keepAwake) {
3176 mVoiceWakeLock.acquire();
3177 } else {
3178 mVoiceWakeLock.release();
3179 }
3180 }
3181 }
3182 }
3183
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 @Override
3185 public ComponentName getActivityClassForToken(IBinder token) {
3186 synchronized (mGlobalLock) {
3187 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3188 if (r == null) {
3189 return null;
3190 }
3191 return r.intent.getComponent();
3192 }
3193 }
3194
3195 @Override
3196 public String getPackageForToken(IBinder token) {
3197 synchronized (mGlobalLock) {
3198 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3199 if (r == null) {
3200 return null;
3201 }
3202 return r.packageName;
3203 }
3204 }
3205
3206 @Override
3207 public void showLockTaskEscapeMessage(IBinder token) {
3208 synchronized (mGlobalLock) {
3209 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3210 if (r == null) {
3211 return;
3212 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003213 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 }
3215 }
3216
3217 @Override
3218 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003219 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 final long token = Binder.clearCallingIdentity();
3221 try {
3222 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003223 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 }
3225 } finally {
3226 Binder.restoreCallingIdentity(token);
3227 }
3228 }
3229
3230 /**
3231 * Try to place task to provided position. The final position might be different depending on
3232 * current user and stacks state. The task will be moved to target stack if it's currently in
3233 * different stack.
3234 */
3235 @Override
3236 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003237 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 synchronized (mGlobalLock) {
3239 long ident = Binder.clearCallingIdentity();
3240 try {
3241 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3242 + taskId + " in stackId=" + stackId + " at position=" + position);
3243 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3244 if (task == null) {
3245 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3246 + taskId);
3247 }
3248
3249 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3250
3251 if (stack == null) {
3252 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3253 + stackId);
3254 }
3255 if (!stack.isActivityTypeStandardOrUndefined()) {
3256 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3257 + " the position of task " + taskId + " in/to non-standard stack");
3258 }
3259
3260 // TODO: Have the callers of this API call a separate reparent method if that is
3261 // what they intended to do vs. having this method also do reparenting.
3262 if (task.getStack() == stack) {
3263 // Change position in current stack.
3264 stack.positionChildAt(task, position);
3265 } else {
3266 // Reparent to new stack.
3267 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3268 !DEFER_RESUME, "positionTaskInStack");
3269 }
3270 } finally {
3271 Binder.restoreCallingIdentity(ident);
3272 }
3273 }
3274 }
3275
3276 @Override
3277 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3278 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3279 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3280 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3281 synchronized (mGlobalLock) {
3282 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3283 if (record == null) {
3284 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3285 + "found for: " + token);
3286 }
3287 record.setSizeConfigurations(horizontalSizeConfiguration,
3288 verticalSizeConfigurations, smallestSizeConfigurations);
3289 }
3290 }
3291
3292 /**
3293 * Dismisses split-screen multi-window mode.
3294 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3295 */
3296 @Override
3297 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003298 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3300 final long ident = Binder.clearCallingIdentity();
3301 try {
3302 synchronized (mGlobalLock) {
3303 final ActivityStack stack =
3304 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3305 if (stack == null) {
3306 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3307 return;
3308 }
3309
3310 if (toTop) {
3311 // Caller wants the current split-screen primary stack to be the top stack after
3312 // it goes fullscreen, so move it to the front.
3313 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003314 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 // In this case the current split-screen primary stack shouldn't be the top
3316 // stack after it goes fullscreen, but it current has focus, so we move the
3317 // focus to the top-most split-screen secondary stack next to it.
3318 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3319 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3320 if (otherStack != null) {
3321 otherStack.moveToFront("dismissSplitScreenMode_other");
3322 }
3323 }
3324
3325 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3326 }
3327 } finally {
3328 Binder.restoreCallingIdentity(ident);
3329 }
3330 }
3331
3332 /**
3333 * Dismisses Pip
3334 * @param animate True if the dismissal should be animated.
3335 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3336 * default animation duration should be used.
3337 */
3338 @Override
3339 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003340 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 final long ident = Binder.clearCallingIdentity();
3342 try {
3343 synchronized (mGlobalLock) {
3344 final PinnedActivityStack stack =
3345 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3346 if (stack == null) {
3347 Slog.w(TAG, "dismissPip: pinned stack not found.");
3348 return;
3349 }
3350 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3351 throw new IllegalArgumentException("Stack: " + stack
3352 + " doesn't support animated resize.");
3353 }
3354 if (animate) {
3355 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3356 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3357 } else {
3358 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3359 }
3360 }
3361 } finally {
3362 Binder.restoreCallingIdentity(ident);
3363 }
3364 }
3365
3366 @Override
3367 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003368 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 synchronized (mGlobalLock) {
3370 mSuppressResizeConfigChanges = suppress;
3371 }
3372 }
3373
3374 /**
3375 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3376 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3377 * activity and clearing the task at the same time.
3378 */
3379 @Override
3380 // TODO: API should just be about changing windowing modes...
3381 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 "moveTasksToFullscreenStack()");
3384 synchronized (mGlobalLock) {
3385 final long origId = Binder.clearCallingIdentity();
3386 try {
3387 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3388 if (stack != null){
3389 if (!stack.isActivityTypeStandardOrUndefined()) {
3390 throw new IllegalArgumentException(
3391 "You can't move tasks from non-standard stacks.");
3392 }
3393 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3394 }
3395 } finally {
3396 Binder.restoreCallingIdentity(origId);
3397 }
3398 }
3399 }
3400
3401 /**
3402 * Moves the top activity in the input stackId to the pinned stack.
3403 *
3404 * @param stackId Id of stack to move the top activity to pinned stack.
3405 * @param bounds Bounds to use for pinned stack.
3406 *
3407 * @return True if the top activity of the input stack was successfully moved to the pinned
3408 * stack.
3409 */
3410 @Override
3411 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 "moveTopActivityToPinnedStack()");
3414 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003415 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3417 + "Device doesn't support picture-in-picture mode");
3418 }
3419
3420 long ident = Binder.clearCallingIdentity();
3421 try {
3422 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3423 } finally {
3424 Binder.restoreCallingIdentity(ident);
3425 }
3426 }
3427 }
3428
3429 @Override
3430 public boolean isInMultiWindowMode(IBinder token) {
3431 final long origId = Binder.clearCallingIdentity();
3432 try {
3433 synchronized (mGlobalLock) {
3434 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3435 if (r == null) {
3436 return false;
3437 }
3438 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3439 return r.inMultiWindowMode();
3440 }
3441 } finally {
3442 Binder.restoreCallingIdentity(origId);
3443 }
3444 }
3445
3446 @Override
3447 public boolean isInPictureInPictureMode(IBinder token) {
3448 final long origId = Binder.clearCallingIdentity();
3449 try {
3450 synchronized (mGlobalLock) {
3451 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3452 }
3453 } finally {
3454 Binder.restoreCallingIdentity(origId);
3455 }
3456 }
3457
3458 private boolean isInPictureInPictureMode(ActivityRecord r) {
3459 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3460 || r.getStack().isInStackLocked(r) == null) {
3461 return false;
3462 }
3463
3464 // If we are animating to fullscreen then we have already dispatched the PIP mode
3465 // changed, so we should reflect that check here as well.
3466 final PinnedActivityStack stack = r.getStack();
3467 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3468 return !windowController.isAnimatingBoundsToFullscreen();
3469 }
3470
3471 @Override
3472 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3473 final long origId = Binder.clearCallingIdentity();
3474 try {
3475 synchronized (mGlobalLock) {
3476 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3477 "enterPictureInPictureMode", token, params);
3478
3479 // If the activity is already in picture in picture mode, then just return early
3480 if (isInPictureInPictureMode(r)) {
3481 return true;
3482 }
3483
3484 // Activity supports picture-in-picture, now check that we can enter PiP at this
3485 // point, if it is
3486 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3487 false /* beforeStopping */)) {
3488 return false;
3489 }
3490
3491 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003492 synchronized (mGlobalLock) {
3493 // Only update the saved args from the args that are set
3494 r.pictureInPictureArgs.copyOnlySet(params);
3495 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3496 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3497 // Adjust the source bounds by the insets for the transition down
3498 final Rect sourceBounds = new Rect(
3499 r.pictureInPictureArgs.getSourceRectHint());
3500 mStackSupervisor.moveActivityToPinnedStackLocked(
3501 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3502 final PinnedActivityStack stack = r.getStack();
3503 stack.setPictureInPictureAspectRatio(aspectRatio);
3504 stack.setPictureInPictureActions(actions);
3505 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3506 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3507 logPictureInPictureArgs(params);
3508 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 };
3510
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003511 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 // If the keyguard is showing or occluded, then try and dismiss it before
3513 // entering picture-in-picture (this will prompt the user to authenticate if the
3514 // device is currently locked).
3515 dismissKeyguard(token, new KeyguardDismissCallback() {
3516 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003517 public void onDismissSucceeded() {
3518 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 }
3520 }, null /* message */);
3521 } else {
3522 // Enter picture in picture immediately otherwise
3523 enterPipRunnable.run();
3524 }
3525 return true;
3526 }
3527 } finally {
3528 Binder.restoreCallingIdentity(origId);
3529 }
3530 }
3531
3532 @Override
3533 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3534 final long origId = Binder.clearCallingIdentity();
3535 try {
3536 synchronized (mGlobalLock) {
3537 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3538 "setPictureInPictureParams", token, params);
3539
3540 // Only update the saved args from the args that are set
3541 r.pictureInPictureArgs.copyOnlySet(params);
3542 if (r.inPinnedWindowingMode()) {
3543 // If the activity is already in picture-in-picture, update the pinned stack now
3544 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3545 // be used the next time the activity enters PiP
3546 final PinnedActivityStack stack = r.getStack();
3547 if (!stack.isAnimatingBoundsToFullscreen()) {
3548 stack.setPictureInPictureAspectRatio(
3549 r.pictureInPictureArgs.getAspectRatio());
3550 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3551 }
3552 }
3553 logPictureInPictureArgs(params);
3554 }
3555 } finally {
3556 Binder.restoreCallingIdentity(origId);
3557 }
3558 }
3559
3560 @Override
3561 public int getMaxNumPictureInPictureActions(IBinder token) {
3562 // Currently, this is a static constant, but later, we may change this to be dependent on
3563 // the context of the activity
3564 return 3;
3565 }
3566
3567 private void logPictureInPictureArgs(PictureInPictureParams params) {
3568 if (params.hasSetActions()) {
3569 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3570 params.getActions().size());
3571 }
3572 if (params.hasSetAspectRatio()) {
3573 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3574 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3575 MetricsLogger.action(lm);
3576 }
3577 }
3578
3579 /**
3580 * Checks the state of the system and the activity associated with the given {@param token} to
3581 * verify that picture-in-picture is supported for that activity.
3582 *
3583 * @return the activity record for the given {@param token} if all the checks pass.
3584 */
3585 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3586 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003587 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 throw new IllegalStateException(caller
3589 + ": Device doesn't support picture-in-picture mode.");
3590 }
3591
3592 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3593 if (r == null) {
3594 throw new IllegalStateException(caller
3595 + ": Can't find activity for token=" + token);
3596 }
3597
3598 if (!r.supportsPictureInPicture()) {
3599 throw new IllegalStateException(caller
3600 + ": Current activity does not support picture-in-picture.");
3601 }
3602
3603 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003604 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 params.getAspectRatio())) {
3606 final float minAspectRatio = mContext.getResources().getFloat(
3607 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3608 final float maxAspectRatio = mContext.getResources().getFloat(
3609 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3610 throw new IllegalArgumentException(String.format(caller
3611 + ": Aspect ratio is too extreme (must be between %f and %f).",
3612 minAspectRatio, maxAspectRatio));
3613 }
3614
3615 // Truncate the number of actions if necessary
3616 params.truncateActions(getMaxNumPictureInPictureActions(token));
3617
3618 return r;
3619 }
3620
3621 @Override
3622 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003623 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 synchronized (mGlobalLock) {
3625 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3626 if (r == null) {
3627 throw new IllegalArgumentException("Activity does not exist; token="
3628 + activityToken);
3629 }
3630 return r.getUriPermissionsLocked().getExternalTokenLocked();
3631 }
3632 }
3633
3634 @Override
3635 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3636 Rect tempDockedTaskInsetBounds,
3637 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003638 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639 long ident = Binder.clearCallingIdentity();
3640 try {
3641 synchronized (mGlobalLock) {
3642 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3643 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3644 PRESERVE_WINDOWS);
3645 }
3646 } finally {
3647 Binder.restoreCallingIdentity(ident);
3648 }
3649 }
3650
3651 @Override
3652 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003653 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 final long ident = Binder.clearCallingIdentity();
3655 try {
3656 synchronized (mGlobalLock) {
3657 mStackSupervisor.setSplitScreenResizing(resizing);
3658 }
3659 } finally {
3660 Binder.restoreCallingIdentity(ident);
3661 }
3662 }
3663
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003664 /**
3665 * Check that we have the features required for VR-related API calls, and throw an exception if
3666 * not.
3667 */
3668 void enforceSystemHasVrFeature() {
3669 if (!mContext.getPackageManager().hasSystemFeature(
3670 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3671 throw new UnsupportedOperationException("VR mode not supported on this device!");
3672 }
3673 }
3674
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675 @Override
3676 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003677 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003678
3679 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3680
3681 ActivityRecord r;
3682 synchronized (mGlobalLock) {
3683 r = ActivityRecord.isInStackLocked(token);
3684 }
3685
3686 if (r == null) {
3687 throw new IllegalArgumentException();
3688 }
3689
3690 int err;
3691 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3692 VrManagerInternal.NO_ERROR) {
3693 return err;
3694 }
3695
3696 // Clear the binder calling uid since this path may call moveToTask().
3697 final long callingId = Binder.clearCallingIdentity();
3698 try {
3699 synchronized (mGlobalLock) {
3700 r.requestedVrComponent = (enabled) ? packageName : null;
3701
3702 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003703 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003704 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 }
3706 return 0;
3707 }
3708 } finally {
3709 Binder.restoreCallingIdentity(callingId);
3710 }
3711 }
3712
3713 @Override
3714 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3715 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3716 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003717 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3719 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3720 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003721 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722 || activity.voiceSession != null) {
3723 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3724 return;
3725 }
3726 if (activity.pendingVoiceInteractionStart) {
3727 Slog.w(TAG, "Pending start of voice interaction already.");
3728 return;
3729 }
3730 activity.pendingVoiceInteractionStart = true;
3731 }
3732 LocalServices.getService(VoiceInteractionManagerInternal.class)
3733 .startLocalVoiceInteraction(callingActivity, options);
3734 }
3735
3736 @Override
3737 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3738 LocalServices.getService(VoiceInteractionManagerInternal.class)
3739 .stopLocalVoiceInteraction(callingActivity);
3740 }
3741
3742 @Override
3743 public boolean supportsLocalVoiceInteraction() {
3744 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3745 .supportsLocalVoiceInteraction();
3746 }
3747
3748 /** Notifies all listeners when the pinned stack animation starts. */
3749 @Override
3750 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003751 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003752 }
3753
3754 /** Notifies all listeners when the pinned stack animation ends. */
3755 @Override
3756 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003757 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003758 }
3759
3760 @Override
3761 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003762 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003763 final long ident = Binder.clearCallingIdentity();
3764 try {
3765 synchronized (mGlobalLock) {
3766 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3767 }
3768 } finally {
3769 Binder.restoreCallingIdentity(ident);
3770 }
3771 }
3772
3773 @Override
3774 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003775 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003776
3777 synchronized (mGlobalLock) {
3778 // Check if display is initialized in AM.
3779 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3780 // Call might come when display is not yet added or has already been removed.
3781 if (DEBUG_CONFIGURATION) {
3782 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
3783 + displayId);
3784 }
3785 return false;
3786 }
3787
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003788 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003789 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003790 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 }
3792
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003793 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003795 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 }
3797
3798 final long origId = Binder.clearCallingIdentity();
3799 try {
3800 if (values != null) {
3801 Settings.System.clearConfiguration(values);
3802 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003803 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
3805 return mTmpUpdateConfigurationResult.changes != 0;
3806 } finally {
3807 Binder.restoreCallingIdentity(origId);
3808 }
3809 }
3810 }
3811
3812 @Override
3813 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003814 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003815
3816 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003817 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003819 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003820 }
3821
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003822 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003824 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003825 }
3826
3827 final long origId = Binder.clearCallingIdentity();
3828 try {
3829 if (values != null) {
3830 Settings.System.clearConfiguration(values);
3831 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003832 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 UserHandle.USER_NULL, false /* deferResume */,
3834 mTmpUpdateConfigurationResult);
3835 return mTmpUpdateConfigurationResult.changes != 0;
3836 } finally {
3837 Binder.restoreCallingIdentity(origId);
3838 }
3839 }
3840 }
3841
3842 @Override
3843 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
3844 CharSequence message) {
3845 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003846 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
3848 }
3849 final long callingId = Binder.clearCallingIdentity();
3850 try {
3851 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003852 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853 }
3854 } finally {
3855 Binder.restoreCallingIdentity(callingId);
3856 }
3857 }
3858
3859 @Override
3860 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003861 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 "cancelTaskWindowTransition()");
3863 final long ident = Binder.clearCallingIdentity();
3864 try {
3865 synchronized (mGlobalLock) {
3866 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
3867 MATCH_TASK_IN_STACKS_ONLY);
3868 if (task == null) {
3869 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
3870 return;
3871 }
3872 task.cancelWindowTransition();
3873 }
3874 } finally {
3875 Binder.restoreCallingIdentity(ident);
3876 }
3877 }
3878
3879 @Override
3880 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003881 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 final long ident = Binder.clearCallingIdentity();
3883 try {
3884 final TaskRecord task;
3885 synchronized (mGlobalLock) {
3886 task = mStackSupervisor.anyTaskForIdLocked(taskId,
3887 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3888 if (task == null) {
3889 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
3890 return null;
3891 }
3892 }
3893 // Don't call this while holding the lock as this operation might hit the disk.
3894 return task.getSnapshot(reducedResolution);
3895 } finally {
3896 Binder.restoreCallingIdentity(ident);
3897 }
3898 }
3899
3900 @Override
3901 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
3902 synchronized (mGlobalLock) {
3903 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3904 if (r == null) {
3905 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
3906 + token);
3907 return;
3908 }
3909 final long origId = Binder.clearCallingIdentity();
3910 try {
3911 r.setDisablePreviewScreenshots(disable);
3912 } finally {
3913 Binder.restoreCallingIdentity(origId);
3914 }
3915 }
3916 }
3917
3918 /** Return the user id of the last resumed activity. */
3919 @Override
3920 public @UserIdInt
3921 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
3924 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07003925 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003926 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003928 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 }
3930 }
3931
3932 @Override
3933 public void updateLockTaskFeatures(int userId, int flags) {
3934 final int callingUid = Binder.getCallingUid();
3935 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003936 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003937 "updateLockTaskFeatures()");
3938 }
3939 synchronized (mGlobalLock) {
3940 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
3941 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003942 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003943 }
3944 }
3945
3946 @Override
3947 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
3948 synchronized (mGlobalLock) {
3949 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3950 if (r == null) {
3951 return;
3952 }
3953 final long origId = Binder.clearCallingIdentity();
3954 try {
3955 r.setShowWhenLocked(showWhenLocked);
3956 } finally {
3957 Binder.restoreCallingIdentity(origId);
3958 }
3959 }
3960 }
3961
3962 @Override
3963 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
3964 synchronized (mGlobalLock) {
3965 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3966 if (r == null) {
3967 return;
3968 }
3969 final long origId = Binder.clearCallingIdentity();
3970 try {
3971 r.setTurnScreenOn(turnScreenOn);
3972 } finally {
3973 Binder.restoreCallingIdentity(origId);
3974 }
3975 }
3976 }
3977
3978 @Override
3979 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003980 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 "registerRemoteAnimations");
3982 definition.setCallingPid(Binder.getCallingPid());
3983 synchronized (mGlobalLock) {
3984 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3985 if (r == null) {
3986 return;
3987 }
3988 final long origId = Binder.clearCallingIdentity();
3989 try {
3990 r.registerRemoteAnimations(definition);
3991 } finally {
3992 Binder.restoreCallingIdentity(origId);
3993 }
3994 }
3995 }
3996
3997 @Override
3998 public void registerRemoteAnimationForNextActivityStart(String packageName,
3999 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 "registerRemoteAnimationForNextActivityStart");
4002 adapter.setCallingPid(Binder.getCallingPid());
4003 synchronized (mGlobalLock) {
4004 final long origId = Binder.clearCallingIdentity();
4005 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004006 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 packageName, adapter);
4008 } finally {
4009 Binder.restoreCallingIdentity(origId);
4010 }
4011 }
4012 }
4013
4014 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4015 @Override
4016 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4017 synchronized (mGlobalLock) {
4018 final long origId = Binder.clearCallingIdentity();
4019 try {
4020 mAm.mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4021 } finally {
4022 Binder.restoreCallingIdentity(origId);
4023 }
4024 }
4025 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004026
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004027 @Override
4028 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004029 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004030 synchronized (mGlobalLock) {
4031 synchronized (mAm.mPidsSelfLocked) {
4032 final int pid = Binder.getCallingPid();
4033 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004034 mVrController.setVrThreadLocked(tid, pid, proc.getWindowProcessController());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004035 }
4036 }
4037 }
4038
4039 @Override
4040 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004042 != PERMISSION_GRANTED) {
4043 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4044 + Binder.getCallingPid()
4045 + ", uid=" + Binder.getCallingUid()
4046 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4047 Slog.w(TAG, msg);
4048 throw new SecurityException(msg);
4049 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004051 synchronized (mGlobalLock) {
4052 synchronized (mAm.mPidsSelfLocked) {
4053 final int pid = Binder.getCallingPid();
4054 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
4055 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4056 }
4057 }
4058 }
4059
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004060 @Override
4061 public void stopAppSwitches() {
4062 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4063 synchronized (mGlobalLock) {
4064 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4065 mDidAppSwitch = false;
4066 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4067 }
4068 }
4069
4070 @Override
4071 public void resumeAppSwitches() {
4072 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4073 synchronized (mGlobalLock) {
4074 // Note that we don't execute any pending app switches... we will
4075 // let those wait until either the timeout, or the next start
4076 // activity request.
4077 mAppSwitchesAllowedTime = 0;
4078 }
4079 }
4080
4081 void onStartActivitySetDidAppSwitch() {
4082 if (mDidAppSwitch) {
4083 // This is the second allowed switch since we stopped switches, so now just generally
4084 // allow switches. Use case:
4085 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4086 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4087 // anyone to switch again).
4088 mAppSwitchesAllowedTime = 0;
4089 } else {
4090 mDidAppSwitch = true;
4091 }
4092 }
4093
4094 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004095 boolean shouldDisableNonVrUiLocked() {
4096 return mVrController.shouldDisableNonVrUiLocked();
4097 }
4098
4099 void applyUpdateVrModeLocked(ActivityRecord r) {
4100 // VR apps are expected to run in a main display. If an app is turning on VR for
4101 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4102 // fullscreen stack before enabling VR Mode.
4103 // TODO: The goal of this code is to keep the VR app on the main display. When the
4104 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4105 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4106 // option would be a better choice here.
4107 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4108 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4109 + " to main stack for VR");
4110 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4111 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4112 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4113 }
4114 mH.post(() -> {
4115 if (!mVrController.onVrModeChanged(r)) {
4116 return;
4117 }
4118 synchronized (mGlobalLock) {
4119 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4120 mWindowManager.disableNonVrUi(disableNonVrUi);
4121 if (disableNonVrUi) {
4122 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4123 // then remove the pinned stack.
4124 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4125 }
4126 }
4127 });
4128 }
4129
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004130 ActivityStack getTopDisplayFocusedStack() {
4131 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004132 }
4133
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004134 /** Pokes the task persister. */
4135 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4136 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4137 }
4138
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004139 void onTopProcChangedLocked(WindowProcessController proc) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004140 mVrController.onTopProcChangedLocked(proc);
4141 }
4142
4143 boolean isKeyguardLocked() {
4144 return mKeyguardController.isKeyguardLocked();
4145 }
4146
4147 boolean isNextTransitionForward() {
4148 int transit = mWindowManager.getPendingAppTransition();
4149 return transit == TRANSIT_ACTIVITY_OPEN
4150 || transit == TRANSIT_TASK_OPEN
4151 || transit == TRANSIT_TASK_TO_FRONT;
4152 }
4153
Wale Ogunwalef6733932018-06-27 05:14:34 -07004154 void dumpSleepStates(PrintWriter pw, boolean testPssMode) {
4155 synchronized (mGlobalLock) {
4156 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
4157 if (mRunningVoice != null) {
4158 pw.println(" mRunningVoice=" + mRunningVoice);
4159 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
4160 }
4161 pw.println(" mSleeping=" + mSleeping);
4162 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
4163 pw.println(" mVrController=" + mVrController);
4164 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004165 }
4166
Wale Ogunwalef6733932018-06-27 05:14:34 -07004167 void writeSleepStateToProto(ProtoOutputStream proto) {
4168 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4169 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4170 st.toString());
4171 }
4172
4173 if (mRunningVoice != null) {
4174 final long vrToken = proto.start(
4175 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4176 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4177 mRunningVoice.toString());
4178 mVoiceWakeLock.writeToProto(
4179 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4180 proto.end(vrToken);
4181 }
4182
4183 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4184 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4185 mShuttingDown);
4186 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004187 }
4188
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004189 int getCurrentUserId() {
4190 return mAmInternal.getCurrentUserId();
4191 }
4192
4193 private void enforceNotIsolatedCaller(String caller) {
4194 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4195 throw new SecurityException("Isolated process not allowed to call " + caller);
4196 }
4197 }
4198
Wale Ogunwalef6733932018-06-27 05:14:34 -07004199 public Configuration getConfiguration() {
4200 Configuration ci;
4201 synchronized(mGlobalLock) {
4202 ci = new Configuration(getGlobalConfiguration());
4203 ci.userSetLocale = false;
4204 }
4205 return ci;
4206 }
4207
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 /**
4209 * Current global configuration information. Contains general settings for the entire system,
4210 * also corresponds to the merged configuration of the default display.
4211 */
4212 Configuration getGlobalConfiguration() {
4213 return mStackSupervisor.getConfiguration();
4214 }
4215
4216 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4217 boolean initLocale) {
4218 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4219 }
4220
4221 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4222 boolean initLocale, boolean deferResume) {
4223 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4224 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4225 UserHandle.USER_NULL, deferResume);
4226 }
4227
4228 void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4229 final long origId = Binder.clearCallingIdentity();
4230 try {
4231 synchronized (mGlobalLock) {
4232 updateConfigurationLocked(values, null, false, true, userId,
4233 false /* deferResume */);
4234 }
4235 } finally {
4236 Binder.restoreCallingIdentity(origId);
4237 }
4238 }
4239
4240 void updateUserConfiguration() {
4241 synchronized (mGlobalLock) {
4242 final Configuration configuration = new Configuration(getGlobalConfiguration());
4243 final int currentUserId = mAmInternal.getCurrentUserId();
4244 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(), configuration,
4245 currentUserId, Settings.System.canWrite(mContext));
4246 updateConfigurationLocked(configuration, null /* starting */, false /* initLocale */,
4247 false /* persistent */, currentUserId, false /* deferResume */);
4248 }
4249 }
4250
4251 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4252 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4253 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4254 deferResume, null /* result */);
4255 }
4256
4257 /**
4258 * Do either or both things: (1) change the current configuration, and (2)
4259 * make sure the given activity is running with the (now) current
4260 * configuration. Returns true if the activity has been left running, or
4261 * false if <var>starting</var> is being destroyed to match the new
4262 * configuration.
4263 *
4264 * @param userId is only used when persistent parameter is set to true to persist configuration
4265 * for that particular user
4266 */
4267 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4268 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4269 ActivityTaskManagerService.UpdateConfigurationResult result) {
4270 int changes = 0;
4271 boolean kept = true;
4272
4273 if (mWindowManager != null) {
4274 mWindowManager.deferSurfaceLayout();
4275 }
4276 try {
4277 if (values != null) {
4278 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4279 deferResume);
4280 }
4281
4282 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4283 } finally {
4284 if (mWindowManager != null) {
4285 mWindowManager.continueSurfaceLayout();
4286 }
4287 }
4288
4289 if (result != null) {
4290 result.changes = changes;
4291 result.activityRelaunched = !kept;
4292 }
4293 return kept;
4294 }
4295
4296 /**
4297 * Returns true if this configuration change is interesting enough to send an
4298 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
4299 */
4300 private static boolean isSplitConfigurationChange(int configDiff) {
4301 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
4302 }
4303
4304 /** Update default (global) configuration and notify listeners about changes. */
4305 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4306 boolean persistent, int userId, boolean deferResume) {
4307 mTempConfig.setTo(getGlobalConfiguration());
4308 final int changes = mTempConfig.updateFrom(values);
4309 if (changes == 0) {
4310 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4311 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4312 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4313 // (even if there are no actual changes) to unfreeze the window.
4314 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4315 return 0;
4316 }
4317
4318 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4319 "Updating global configuration to: " + values);
4320
4321 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4322 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4323 values.colorMode,
4324 values.densityDpi,
4325 values.fontScale,
4326 values.hardKeyboardHidden,
4327 values.keyboard,
4328 values.keyboardHidden,
4329 values.mcc,
4330 values.mnc,
4331 values.navigation,
4332 values.navigationHidden,
4333 values.orientation,
4334 values.screenHeightDp,
4335 values.screenLayout,
4336 values.screenWidthDp,
4337 values.smallestScreenWidthDp,
4338 values.touchscreen,
4339 values.uiMode);
4340
4341
4342 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4343 final LocaleList locales = values.getLocales();
4344 int bestLocaleIndex = 0;
4345 if (locales.size() > 1) {
4346 if (mSupportedSystemLocales == null) {
4347 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4348 }
4349 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4350 }
4351 SystemProperties.set("persist.sys.locale",
4352 locales.get(bestLocaleIndex).toLanguageTag());
4353 LocaleList.setDefault(locales, bestLocaleIndex);
4354 mAm.mHandler.sendMessage(mAm.mHandler.obtainMessage(SEND_LOCALE_TO_MOUNT_DAEMON_MSG,
4355 locales.get(bestLocaleIndex)));
4356 }
4357
4358 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
4359 mTempConfig.seq = mConfigurationSeq;
4360
4361 // Update stored global config and notify everyone about the change.
4362 mStackSupervisor.onConfigurationChanged(mTempConfig);
4363
4364 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4365 // TODO(multi-display): Update UsageEvents#Event to include displayId.
4366 mAm.mUsageStatsService.reportConfigurationChange(
4367 mTempConfig, mAmInternal.getCurrentUserId());
4368
4369 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004370 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004371
4372 AttributeCache ac = AttributeCache.instance();
4373 if (ac != null) {
4374 ac.updateConfiguration(mTempConfig);
4375 }
4376
4377 // Make sure all resources in our process are updated right now, so that anyone who is going
4378 // to retrieve resource values after we return will be sure to get the new ones. This is
4379 // especially important during boot, where the first config change needs to guarantee all
4380 // resources have that config before following boot code is executed.
4381 mAm.mSystemThread.applyConfigurationToResources(mTempConfig);
4382
4383 // We need another copy of global config because we're scheduling some calls instead of
4384 // running them in place. We need to be sure that object we send will be handled unchanged.
4385 final Configuration configCopy = new Configuration(mTempConfig);
4386 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
4387 Message msg = mAm.mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
4388 msg.obj = configCopy;
4389 msg.arg1 = userId;
4390 mAm.mHandler.sendMessage(msg);
4391 }
4392
4393 for (int i = mAm.mLruProcesses.size() - 1; i >= 0; i--) {
4394 ProcessRecord app = mAm.mLruProcesses.get(i);
4395 try {
4396 if (app.thread != null) {
4397 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Sending to proc "
4398 + app.processName + " new config " + configCopy);
4399 getLifecycleManager().scheduleTransaction(app.thread,
4400 ConfigurationChangeItem.obtain(configCopy));
4401 }
4402 } catch (Exception e) {
4403 Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change", e);
4404 }
4405 }
4406
4407 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
4408 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING
4409 | Intent.FLAG_RECEIVER_FOREGROUND
4410 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4411 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4412 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4413 UserHandle.USER_ALL);
4414 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
4415 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
4416 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
4417 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
4418 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4419 if (initLocale || !mAm.mProcessesReady) {
4420 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4421 }
4422 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4423 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4424 UserHandle.USER_ALL);
4425 }
4426
4427 // Send a broadcast to PackageInstallers if the configuration change is interesting
4428 // for the purposes of installing additional splits.
4429 if (!initLocale && isSplitConfigurationChange(changes)) {
4430 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
4431 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
4432 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4433
4434 // Typically only app stores will have this permission.
4435 String[] permissions = new String[] { android.Manifest.permission.INSTALL_PACKAGES };
4436 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, permissions,
4437 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
4438 }
4439
4440 // Override configuration of the default display duplicates global config, so we need to
4441 // update it also. This will also notify WindowManager about changes.
4442 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4443 DEFAULT_DISPLAY);
4444
4445 return changes;
4446 }
4447
4448 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4449 boolean deferResume, int displayId) {
4450 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4451 displayId, null /* result */);
4452 }
4453
4454 /**
4455 * Updates override configuration specific for the selected display. If no config is provided,
4456 * new one will be computed in WM based on current display info.
4457 */
4458 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4459 ActivityRecord starting, boolean deferResume, int displayId,
4460 ActivityTaskManagerService.UpdateConfigurationResult result) {
4461 int changes = 0;
4462 boolean kept = true;
4463
4464 if (mWindowManager != null) {
4465 mWindowManager.deferSurfaceLayout();
4466 }
4467 try {
4468 if (values != null) {
4469 if (displayId == DEFAULT_DISPLAY) {
4470 // Override configuration of the default display duplicates global config, so
4471 // we're calling global config update instead for default display. It will also
4472 // apply the correct override config.
4473 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4474 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4475 } else {
4476 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4477 }
4478 }
4479
4480 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4481 } finally {
4482 if (mWindowManager != null) {
4483 mWindowManager.continueSurfaceLayout();
4484 }
4485 }
4486
4487 if (result != null) {
4488 result.changes = changes;
4489 result.activityRelaunched = !kept;
4490 }
4491 return kept;
4492 }
4493
4494 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4495 int displayId) {
4496 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4497 final int changes = mTempConfig.updateFrom(values);
4498 if (changes != 0) {
4499 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4500 + mTempConfig + " for displayId=" + displayId);
4501 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4502
4503 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4504 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
4505 mAm.mAppWarnings.onDensityChanged();
4506
4507 mAm.killAllBackgroundProcessesExcept(N,
4508 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4509 }
4510 }
4511
4512 // Update the configuration with WM first and check if any of the stacks need to be resized
4513 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4514 // necessary. This way we don't need to relaunch again afterwards in
4515 // ensureActivityConfiguration().
4516 if (mWindowManager != null) {
4517 final int[] resizedStacks =
4518 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4519 if (resizedStacks != null) {
4520 for (int stackId : resizedStacks) {
4521 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4522 }
4523 }
4524 }
4525
4526 return changes;
4527 }
4528
Wale Ogunwalef6733932018-06-27 05:14:34 -07004529 private void updateEventDispatchingLocked(boolean booted) {
4530 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4531 }
4532
4533 void enableScreenAfterBoot(boolean booted) {
4534 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4535 SystemClock.uptimeMillis());
4536 mWindowManager.enableScreenAfterBoot();
4537
4538 synchronized (mGlobalLock) {
4539 updateEventDispatchingLocked(booted);
4540 }
4541 }
4542
4543 boolean canShowErrorDialogs() {
4544 return mShowDialogs && !mSleeping && !mShuttingDown
4545 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
4546 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
Wale Ogunwale86b74462018-07-02 08:42:43 -07004547 mAmInternal.getCurrentUserId())
Wale Ogunwalef6733932018-06-27 05:14:34 -07004548 && !(UserManager.isDeviceInDemoMode(mContext)
Wale Ogunwale86b74462018-07-02 08:42:43 -07004549 && mAmInternal.getCurrentUser().isDemo());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004550 }
4551
4552 /**
4553 * Decide based on the configuration whether we should show the ANR,
4554 * crash, etc dialogs. The idea is that if there is no affordance to
4555 * press the on-screen buttons, or the user experience would be more
4556 * greatly impacted than the crash itself, we shouldn't show the dialog.
4557 *
4558 * A thought: SystemUI might also want to get told about this, the Power
4559 * dialog / global actions also might want different behaviors.
4560 */
4561 private void updateShouldShowDialogsLocked(Configuration config) {
4562 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4563 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4564 && config.navigation == Configuration.NAVIGATION_NONAV);
4565 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4566 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4567 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4568 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4569 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4570 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4571 HIDE_ERROR_DIALOGS, 0) != 0;
4572 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4573 }
4574
4575 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4576 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4577 FONT_SCALE, 1.0f, userId);
4578
4579 synchronized (this) {
4580 if (getGlobalConfiguration().fontScale == scaleFactor) {
4581 return;
4582 }
4583
4584 final Configuration configuration
4585 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4586 configuration.fontScale = scaleFactor;
4587 updatePersistentConfiguration(configuration, userId);
4588 }
4589 }
4590
4591 // Actually is sleeping or shutting down or whatever else in the future
4592 // is an inactive state.
4593 boolean isSleepingOrShuttingDownLocked() {
4594 return isSleepingLocked() || mShuttingDown;
4595 }
4596
4597 boolean isSleepingLocked() {
4598 return mSleeping;
4599 }
4600
4601 /**
4602 * Update AMS states when an activity is resumed. This should only be called by
4603 * {@link ActivityStack#onActivityStateChanged(
4604 * ActivityRecord, ActivityStack.ActivityState, String)} when an activity is resumed.
4605 */
4606 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4607 final TaskRecord task = r.getTask();
4608 if (task.isActivityTypeStandard()) {
4609 if (mCurAppTimeTracker != r.appTimeTracker) {
4610 // We are switching app tracking. Complete the current one.
4611 if (mCurAppTimeTracker != null) {
4612 mCurAppTimeTracker.stop();
4613 mH.obtainMessage(
4614 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4615 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4616 mCurAppTimeTracker = null;
4617 }
4618 if (r.appTimeTracker != null) {
4619 mCurAppTimeTracker = r.appTimeTracker;
4620 startTimeTrackingFocusedActivityLocked();
4621 }
4622 } else {
4623 startTimeTrackingFocusedActivityLocked();
4624 }
4625 } else {
4626 r.appTimeTracker = null;
4627 }
4628 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
4629 // TODO: Probably not, because we don't want to resume voice on switching
4630 // back to this activity
4631 if (task.voiceInteractor != null) {
4632 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
4633 } else {
4634 finishRunningVoiceLocked();
4635
4636 if (mLastResumedActivity != null) {
4637 final IVoiceInteractionSession session;
4638
4639 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
4640 if (lastResumedActivityTask != null
4641 && lastResumedActivityTask.voiceSession != null) {
4642 session = lastResumedActivityTask.voiceSession;
4643 } else {
4644 session = mLastResumedActivity.voiceSession;
4645 }
4646
4647 if (session != null) {
4648 // We had been in a voice interaction session, but now focused has
4649 // move to something different. Just finish the session, we can't
4650 // return to it and retain the proper state and synchronization with
4651 // the voice interaction service.
4652 finishVoiceTask(session);
4653 }
4654 }
4655 }
4656
4657 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
4658 mAmInternal.sendForegroundProfileChanged(r.userId);
4659 }
4660 updateResumedAppTrace(r);
4661 mLastResumedActivity = r;
4662
4663 mWindowManager.setFocusedApp(r.appToken, true);
4664
4665 applyUpdateLockStateLocked(r);
4666 applyUpdateVrModeLocked(r);
4667
4668 EventLogTags.writeAmSetResumedActivity(
4669 r == null ? -1 : r.userId,
4670 r == null ? "NULL" : r.shortComponentName,
4671 reason);
4672 }
4673
4674 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
4675 synchronized (mGlobalLock) {
4676 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
4677 updateSleepIfNeededLocked();
4678 return token;
4679 }
4680 }
4681
4682 void updateSleepIfNeededLocked() {
4683 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
4684 final boolean wasSleeping = mSleeping;
4685 boolean updateOomAdj = false;
4686
4687 if (!shouldSleep) {
4688 // If wasSleeping is true, we need to wake up activity manager state from when
4689 // we started sleeping. In either case, we need to apply the sleep tokens, which
4690 // will wake up stacks or put them to sleep as appropriate.
4691 if (wasSleeping) {
4692 mSleeping = false;
4693 startTimeTrackingFocusedActivityLocked();
4694 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
4695 mStackSupervisor.comeOutOfSleepIfNeededLocked();
4696 }
4697 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
4698 if (wasSleeping) {
4699 updateOomAdj = true;
4700 }
4701 } else if (!mSleeping && shouldSleep) {
4702 mSleeping = true;
4703 if (mCurAppTimeTracker != null) {
4704 mCurAppTimeTracker.stop();
4705 }
4706 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
4707 mStackSupervisor.goingToSleepLocked();
4708 updateResumedAppTrace(null /* resumed */);
4709 updateOomAdj = true;
4710 }
4711 if (updateOomAdj) {
4712 mH.post(mAmInternal::updateOomAdj);
4713 }
4714 }
4715
4716 void updateOomAdj() {
4717 mH.post(mAmInternal::updateOomAdj);
4718 }
4719
Andrii Kulian52d255c2018-07-13 11:32:19 -07004720 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07004721 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07004722 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07004723 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
4724 mCurAppTimeTracker.start(resumedActivity.packageName);
4725 }
4726 }
4727
4728 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
4729 if (mTracedResumedActivity != null) {
4730 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
4731 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
4732 }
4733 if (resumed != null) {
4734 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
4735 constructResumedTraceName(resumed.packageName), 0);
4736 }
4737 mTracedResumedActivity = resumed;
4738 }
4739
4740 private String constructResumedTraceName(String packageName) {
4741 return "focused app: " + packageName;
4742 }
4743
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004744 /** Helper method that requests bounds from WM and applies them to stack. */
4745 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
4746 final Rect newStackBounds = new Rect();
4747 final ActivityStack stack = mStackSupervisor.getStack(stackId);
4748
4749 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
4750 if (stack == null) {
4751 final StringWriter writer = new StringWriter();
4752 final PrintWriter printWriter = new PrintWriter(writer);
4753 mStackSupervisor.dumpDisplays(printWriter);
4754 printWriter.flush();
4755
4756 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
4757 }
4758
4759 stack.getBoundsForNewConfiguration(newStackBounds);
4760 mStackSupervisor.resizeStackLocked(
4761 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
4762 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
4763 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
4764 }
4765
4766 /** Applies latest configuration and/or visibility updates if needed. */
4767 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
4768 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004769 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004770 // mainStack is null during startup.
4771 if (mainStack != null) {
4772 if (changes != 0 && starting == null) {
4773 // If the configuration changed, and the caller is not already
4774 // in the process of starting an activity, then find the top
4775 // activity to check if its configuration needs to change.
4776 starting = mainStack.topRunningActivityLocked();
4777 }
4778
4779 if (starting != null) {
4780 kept = starting.ensureActivityConfiguration(changes,
4781 false /* preserveWindow */);
4782 // And we need to make sure at this point that all other activities
4783 // are made visible with the correct configuration.
4784 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
4785 !PRESERVE_WINDOWS);
4786 }
4787 }
4788
4789 return kept;
4790 }
4791
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004792 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
4793 if (true || Build.IS_USER) {
4794 return;
4795 }
4796
4797 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4798 StrictMode.allowThreadDiskWrites();
4799 try {
4800 File tracesDir = new File("/data/anr");
4801 File tracesFile = null;
4802 try {
4803 tracesFile = File.createTempFile("app_slow", null, tracesDir);
4804
4805 StringBuilder sb = new StringBuilder();
4806 Time tobj = new Time();
4807 tobj.set(System.currentTimeMillis());
4808 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4809 sb.append(": ");
4810 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4811 sb.append(" since ");
4812 sb.append(msg);
4813 FileOutputStream fos = new FileOutputStream(tracesFile);
4814 fos.write(sb.toString().getBytes());
4815 if (app == null) {
4816 fos.write("\n*** No application process!".getBytes());
4817 }
4818 fos.close();
4819 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4820 } catch (IOException e) {
4821 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
4822 return;
4823 }
4824
4825 if (app != null && app.getPid() > 0) {
4826 ArrayList<Integer> firstPids = new ArrayList<Integer>();
4827 firstPids.add(app.getPid());
4828 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
4829 }
4830
4831 File lastTracesFile = null;
4832 File curTracesFile = null;
4833 for (int i=9; i>=0; i--) {
4834 String name = String.format(Locale.US, "slow%02d.txt", i);
4835 curTracesFile = new File(tracesDir, name);
4836 if (curTracesFile.exists()) {
4837 if (lastTracesFile != null) {
4838 curTracesFile.renameTo(lastTracesFile);
4839 } else {
4840 curTracesFile.delete();
4841 }
4842 }
4843 lastTracesFile = curTracesFile;
4844 }
4845 tracesFile.renameTo(curTracesFile);
4846 } finally {
4847 StrictMode.setThreadPolicy(oldPolicy);
4848 }
4849 }
4850
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004851 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004852 static final int REPORT_TIME_TRACKER_MSG = 1;
4853
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004854 public H(Looper looper) {
4855 super(looper, null, true);
4856 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004857
4858 @Override
4859 public void handleMessage(Message msg) {
4860 switch (msg.what) {
4861 case REPORT_TIME_TRACKER_MSG: {
4862 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
4863 tracker.deliverResult(mContext);
4864 } break;
4865 }
4866 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004867 }
4868
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004869 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004870 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004871
4872 public UiHandler() {
4873 super(com.android.server.UiThread.get().getLooper(), null, true);
4874 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004875
4876 @Override
4877 public void handleMessage(Message msg) {
4878 switch (msg.what) {
4879 case DISMISS_DIALOG_UI_MSG: {
4880 final Dialog d = (Dialog) msg.obj;
4881 d.dismiss();
4882 break;
4883 }
4884 }
4885 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004886 }
4887
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004888 final class LocalService extends ActivityTaskManagerInternal {
4889 @Override
4890 public SleepToken acquireSleepToken(String tag, int displayId) {
4891 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004892 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004893 }
4894
4895 @Override
4896 public ComponentName getHomeActivityForUser(int userId) {
4897 synchronized (mGlobalLock) {
4898 ActivityRecord homeActivity = mStackSupervisor.getHomeActivityForUser(userId);
4899 return homeActivity == null ? null : homeActivity.realActivity;
4900 }
4901 }
4902
4903 @Override
4904 public void onLocalVoiceInteractionStarted(IBinder activity,
4905 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
4906 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004907 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004908 }
4909 }
4910
4911 @Override
4912 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
4913 synchronized (mGlobalLock) {
4914 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
4915 reasons, timestamp);
4916 }
4917 }
4918
4919 @Override
4920 public void notifyAppTransitionFinished() {
4921 synchronized (mGlobalLock) {
4922 mStackSupervisor.notifyAppTransitionDone();
4923 }
4924 }
4925
4926 @Override
4927 public void notifyAppTransitionCancelled() {
4928 synchronized (mGlobalLock) {
4929 mStackSupervisor.notifyAppTransitionDone();
4930 }
4931 }
4932
4933 @Override
4934 public List<IBinder> getTopVisibleActivities() {
4935 synchronized (mGlobalLock) {
4936 return mStackSupervisor.getTopVisibleActivities();
4937 }
4938 }
4939
4940 @Override
4941 public void notifyDockedStackMinimizedChanged(boolean minimized) {
4942 synchronized (mGlobalLock) {
4943 mStackSupervisor.setDockedStackMinimized(minimized);
4944 }
4945 }
4946
4947 @Override
4948 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
4949 Bundle bOptions) {
4950 Preconditions.checkNotNull(intents, "intents");
4951 final String[] resolvedTypes = new String[intents.length];
4952
4953 // UID of the package on user userId.
4954 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
4955 // packageUid may not be initialized.
4956 int packageUid = 0;
4957 final long ident = Binder.clearCallingIdentity();
4958
4959 try {
4960 for (int i = 0; i < intents.length; i++) {
4961 resolvedTypes[i] =
4962 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
4963 }
4964
4965 packageUid = AppGlobals.getPackageManager().getPackageUid(
4966 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
4967 } catch (RemoteException e) {
4968 // Shouldn't happen.
4969 } finally {
4970 Binder.restoreCallingIdentity(ident);
4971 }
4972
4973 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004974 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004975 packageUid, packageName,
4976 intents, resolvedTypes, null /* resultTo */,
4977 SafeActivityOptions.fromBundle(bOptions), userId,
4978 false /* validateIncomingUser */);
4979 }
4980 }
4981
4982 @Override
4983 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
4984 Intent intent, Bundle options, int userId) {
4985 return ActivityTaskManagerService.this.startActivityAsUser(
4986 caller, callerPacakge, intent,
4987 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
4988 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
4989 false /*validateIncomingUser*/);
4990 }
4991
4992 @Override
4993 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback) {
4994 synchronized (mGlobalLock) {
4995
4996 // We might change the visibilities here, so prepare an empty app transition which
4997 // might be overridden later if we actually change visibilities.
4998 final boolean wasTransitionSet =
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004999 mWindowManager.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005000 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005001 mWindowManager.prepareAppTransition(TRANSIT_NONE,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005002 false /* alwaysKeepCurrent */);
5003 }
5004 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5005
5006 // If there was a transition set already we don't want to interfere with it as we
5007 // might be starting it too early.
5008 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005009 mWindowManager.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005010 }
5011 }
5012 if (callback != null) {
5013 callback.run();
5014 }
5015 }
5016
5017 @Override
5018 public void notifyKeyguardTrustedChanged() {
5019 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005020 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005021 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5022 }
5023 }
5024 }
5025
5026 /**
5027 * Called after virtual display Id is updated by
5028 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5029 * {@param vrVr2dDisplayId}.
5030 */
5031 @Override
5032 public void setVr2dDisplayId(int vr2dDisplayId) {
5033 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5034 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005035 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005036 }
5037 }
5038
5039 @Override
5040 public void setFocusedActivity(IBinder token) {
5041 synchronized (mGlobalLock) {
5042 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5043 if (r == null) {
5044 throw new IllegalArgumentException(
5045 "setFocusedActivity: No activity record matching token=" + token);
5046 }
5047 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
5048 r, "setFocusedActivity")) {
5049 mStackSupervisor.resumeFocusedStackTopActivityLocked();
5050 }
5051 }
5052 }
5053
5054 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005055 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005056 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005057 }
5058
5059 @Override
5060 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005061 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005062 }
5063
5064 @Override
5065 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005066 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005067 }
5068
5069 @Override
5070 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5071 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5072 }
5073
5074 @Override
5075 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005077 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005078
5079 @Override
5080 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5081 synchronized (mGlobalLock) {
5082 mActiveVoiceInteractionServiceComponent = component;
5083 }
5084 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005085
5086 @Override
5087 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5088 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5089 return;
5090 }
5091 synchronized (mGlobalLock) {
5092 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5093 if (types == null) {
5094 if (uid < 0) {
5095 return;
5096 }
5097 types = new ArrayMap<>();
5098 mAllowAppSwitchUids.put(userId, types);
5099 }
5100 if (uid < 0) {
5101 types.remove(type);
5102 } else {
5103 types.put(type, uid);
5104 }
5105 }
5106 }
5107
5108 @Override
5109 public void onUserStopped(int userId) {
5110 synchronized (mGlobalLock) {
5111 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5112 mAllowAppSwitchUids.remove(userId);
5113 }
5114 }
5115
5116 @Override
5117 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5118 synchronized (mGlobalLock) {
5119 return ActivityTaskManagerService.this.isGetTasksAllowed(
5120 caller, callingPid, callingUid);
5121 }
5122 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005123
5124 @Override
5125 public void onProcessAdded(WindowProcessController proc) {
5126 synchronized (mGlobalLock) {
5127 mProcessNames.put(proc.mName, proc.mUid, proc);
5128 }
5129 }
5130
5131 @Override
5132 public void onProcessRemoved(String name, int uid) {
5133 synchronized (mGlobalLock) {
5134 mProcessNames.remove(name, uid);
5135 }
5136 }
5137
5138 @Override
5139 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5140 synchronized (mGlobalLock) {
5141 if (proc == mHomeProcess) {
5142 mHomeProcess = null;
5143 }
5144 if (proc == mPreviousProcess) {
5145 mPreviousProcess = null;
5146 }
5147 }
5148 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005149
5150 @Override
5151 public int getTopProcessState() {
5152 synchronized (mGlobalLock) {
5153 return mTopProcessState;
5154 }
5155 }
5156
5157 @Override
5158 public boolean isSleeping() {
5159 synchronized (mGlobalLock) {
5160 return isSleepingLocked();
5161 }
5162 }
5163
5164 @Override
5165 public boolean isShuttingDown() {
5166 synchronized (mGlobalLock) {
5167 return mShuttingDown;
5168 }
5169 }
5170
5171 @Override
5172 public boolean shuttingDown(boolean booted, int timeout) {
5173 synchronized (mGlobalLock) {
5174 mShuttingDown = true;
5175 mStackSupervisor.prepareForShutdownLocked();
5176 updateEventDispatchingLocked(booted);
5177 return mStackSupervisor.shutdownLocked(timeout);
5178 }
5179 }
5180
5181 @Override
5182 public void enableScreenAfterBoot(boolean booted) {
5183 synchronized (mGlobalLock) {
5184 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5185 SystemClock.uptimeMillis());
5186 mWindowManager.enableScreenAfterBoot();
5187 updateEventDispatchingLocked(booted);
5188 }
5189 }
5190
5191 @Override
5192 public boolean showStrictModeViolationDialog() {
5193 synchronized (mGlobalLock) {
5194 return mShowDialogs && !mSleeping && !mShuttingDown;
5195 }
5196 }
5197
5198 @Override
5199 public void showSystemReadyErrorDialogsIfNeeded() {
5200 synchronized (mGlobalLock) {
5201 try {
5202 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5203 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5204 + " data partition or your device will be unstable.");
5205 mUiHandler.post(() -> {
5206 if (mShowDialogs) {
5207 AlertDialog d = new BaseErrorDialog(mUiContext);
5208 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5209 d.setCancelable(false);
5210 d.setTitle(mUiContext.getText(R.string.android_system_label));
5211 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5212 d.setButton(DialogInterface.BUTTON_POSITIVE,
5213 mUiContext.getText(R.string.ok),
5214 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5215 d.show();
5216 }
5217 });
5218 }
5219 } catch (RemoteException e) {
5220 }
5221
5222 if (!Build.isBuildConsistent()) {
5223 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5224 mUiHandler.post(() -> {
5225 if (mShowDialogs) {
5226 AlertDialog d = new BaseErrorDialog(mUiContext);
5227 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5228 d.setCancelable(false);
5229 d.setTitle(mUiContext.getText(R.string.android_system_label));
5230 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5231 d.setButton(DialogInterface.BUTTON_POSITIVE,
5232 mUiContext.getText(R.string.ok),
5233 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5234 d.show();
5235 }
5236 });
5237 }
5238 }
5239 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005240 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07005241}