blob: de732c7f3404830808517cf3d6cf5e9fa9d045f7 [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);
2398 if (r == null) {
2399 throw new IllegalArgumentException();
2400 }
2401 return r.getTask().getTopActivity() == r;
2402 }
2403 }
2404
2405 @Override
2406 public void notifyLaunchTaskBehindComplete(IBinder token) {
2407 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2408 }
2409
2410 @Override
2411 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002412 mH.post(() -> {
2413 synchronized (mGlobalLock) {
2414 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002415 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002416 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002417 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002418 } catch (RemoteException e) {
2419 }
2420 }
2421 }
2422
2423 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 }
2425
2426 /** Called from an app when assist data is ready. */
2427 @Override
2428 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2429 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002430 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002431 synchronized (pae) {
2432 pae.result = extras;
2433 pae.structure = structure;
2434 pae.content = content;
2435 if (referrer != null) {
2436 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2437 }
2438 if (structure != null) {
2439 structure.setHomeActivity(pae.isHome);
2440 }
2441 pae.haveResult = true;
2442 pae.notifyAll();
2443 if (pae.intent == null && pae.receiver == null) {
2444 // Caller is just waiting for the result.
2445 return;
2446 }
2447 }
2448 // We are now ready to launch the assist activity.
2449 IAssistDataReceiver sendReceiver = null;
2450 Bundle sendBundle = null;
2451 synchronized (mGlobalLock) {
2452 buildAssistBundleLocked(pae, extras);
2453 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002454 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002455 if (!exists) {
2456 // Timed out.
2457 return;
2458 }
2459
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002460 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002461 // Caller wants result sent back to them.
2462 sendBundle = new Bundle();
2463 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2464 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2465 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2466 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2467 }
2468 }
2469 if (sendReceiver != null) {
2470 try {
2471 sendReceiver.onHandleAssistData(sendBundle);
2472 } catch (RemoteException e) {
2473 }
2474 return;
2475 }
2476
2477 final long ident = Binder.clearCallingIdentity();
2478 try {
2479 if (TextUtils.equals(pae.intent.getAction(),
2480 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2481 pae.intent.putExtras(pae.extras);
2482 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2483 } else {
2484 pae.intent.replaceExtras(pae.extras);
2485 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2486 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2487 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002488 mAmInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489
2490 try {
2491 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2492 } catch (ActivityNotFoundException e) {
2493 Slog.w(TAG, "No activity to handle assist action.", e);
2494 }
2495 }
2496 } finally {
2497 Binder.restoreCallingIdentity(ident);
2498 }
2499 }
2500
2501 @Override
2502 public int addAppTask(IBinder activityToken, Intent intent,
2503 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2504 final int callingUid = Binder.getCallingUid();
2505 final long callingIdent = Binder.clearCallingIdentity();
2506
2507 try {
2508 synchronized (mGlobalLock) {
2509 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2510 if (r == null) {
2511 throw new IllegalArgumentException("Activity does not exist; token="
2512 + activityToken);
2513 }
2514 ComponentName comp = intent.getComponent();
2515 if (comp == null) {
2516 throw new IllegalArgumentException("Intent " + intent
2517 + " must specify explicit component");
2518 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002519 if (thumbnail.getWidth() != mThumbnailWidth
2520 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002521 throw new IllegalArgumentException("Bad thumbnail size: got "
2522 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 }
2525 if (intent.getSelector() != null) {
2526 intent.setSelector(null);
2527 }
2528 if (intent.getSourceBounds() != null) {
2529 intent.setSourceBounds(null);
2530 }
2531 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2532 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2533 // The caller has added this as an auto-remove task... that makes no
2534 // sense, so turn off auto-remove.
2535 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2536 }
2537 }
2538 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2539 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2540 if (ainfo.applicationInfo.uid != callingUid) {
2541 throw new SecurityException(
2542 "Can't add task for another application: target uid="
2543 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2544 }
2545
2546 final ActivityStack stack = r.getStack();
2547 final TaskRecord task = stack.createTaskRecord(
2548 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2549 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002550 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002551 // The app has too many tasks already and we can't add any more
2552 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2553 return INVALID_TASK_ID;
2554 }
2555 task.lastTaskDescription.copyFrom(description);
2556
2557 // TODO: Send the thumbnail to WM to store it.
2558
2559 return task.taskId;
2560 }
2561 } finally {
2562 Binder.restoreCallingIdentity(callingIdent);
2563 }
2564 }
2565
2566 @Override
2567 public Point getAppTaskThumbnailSize() {
2568 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002569 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002570 }
2571 }
2572
2573 @Override
2574 public void setTaskResizeable(int taskId, int resizeableMode) {
2575 synchronized (mGlobalLock) {
2576 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2577 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2578 if (task == null) {
2579 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2580 return;
2581 }
2582 task.setResizeMode(resizeableMode);
2583 }
2584 }
2585
2586 @Override
2587 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002589 long ident = Binder.clearCallingIdentity();
2590 try {
2591 synchronized (mGlobalLock) {
2592 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2593 if (task == null) {
2594 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2595 return;
2596 }
2597 // Place the task in the right stack if it isn't there already based on
2598 // the requested bounds.
2599 // The stack transition logic is:
2600 // - a null bounds on a freeform task moves that task to fullscreen
2601 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2602 // that task to freeform
2603 // - otherwise the task is not moved
2604 ActivityStack stack = task.getStack();
2605 if (!task.getWindowConfiguration().canResizeTask()) {
2606 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2607 }
2608 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2609 stack = stack.getDisplay().getOrCreateStack(
2610 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2611 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2612 stack = stack.getDisplay().getOrCreateStack(
2613 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2614 }
2615
2616 // Reparent the task to the right stack if necessary
2617 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2618 if (stack != task.getStack()) {
2619 // Defer resume until the task is resized below
2620 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2621 DEFER_RESUME, "resizeTask");
2622 preserveWindow = false;
2623 }
2624
2625 // After reparenting (which only resizes the task to the stack bounds), resize the
2626 // task to the actual bounds provided
2627 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2628 }
2629 } finally {
2630 Binder.restoreCallingIdentity(ident);
2631 }
2632 }
2633
2634 @Override
2635 public boolean releaseActivityInstance(IBinder token) {
2636 synchronized (mGlobalLock) {
2637 final long origId = Binder.clearCallingIdentity();
2638 try {
2639 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2640 if (r == null) {
2641 return false;
2642 }
2643 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2644 } finally {
2645 Binder.restoreCallingIdentity(origId);
2646 }
2647 }
2648 }
2649
2650 @Override
2651 public void releaseSomeActivities(IApplicationThread appInt) {
2652 synchronized (mGlobalLock) {
2653 final long origId = Binder.clearCallingIdentity();
2654 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002655 WindowProcessController app =
2656 mAm.getRecordForAppLocked(appInt).getWindowProcessController();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002657 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2658 } finally {
2659 Binder.restoreCallingIdentity(origId);
2660 }
2661 }
2662 }
2663
2664 @Override
2665 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
2666 int secondaryDisplayShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002667 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002668 != PackageManager.PERMISSION_GRANTED) {
2669 throw new SecurityException("Requires permission "
2670 + android.Manifest.permission.DEVICE_POWER);
2671 }
2672
2673 synchronized (mGlobalLock) {
2674 long ident = Binder.clearCallingIdentity();
2675 if (mKeyguardShown != keyguardShowing) {
2676 mKeyguardShown = keyguardShowing;
2677 reportCurKeyguardUsageEventLocked(keyguardShowing);
2678 }
2679 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002680 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002681 secondaryDisplayShowing);
2682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
2686
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002687 mH.post(() -> {
2688 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2689 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2690 }
2691 });
2692 }
2693
2694 void onScreenAwakeChanged(boolean isAwake) {
2695 mH.post(() -> {
2696 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2697 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2698 }
2699 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002700 }
2701
2702 @Override
2703 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002704 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2705 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002706
2707 final File passedIconFile = new File(filePath);
2708 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2709 passedIconFile.getName());
2710 if (!legitIconFile.getPath().equals(filePath)
2711 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2712 throw new IllegalArgumentException("Bad file path: " + filePath
2713 + " passed for userId " + userId);
2714 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002715 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002716 }
2717
2718 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002719 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2721 final ActivityOptions activityOptions = safeOptions != null
2722 ? safeOptions.getOptions(mStackSupervisor)
2723 : null;
2724 if (activityOptions == null
2725 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2726 || activityOptions.getCustomInPlaceResId() == 0) {
2727 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2728 "with valid animation");
2729 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002730 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2731 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002732 activityOptions.getCustomInPlaceResId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002733 mWindowManager.executeAppTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734 }
2735
2736 @Override
2737 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002738 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739 synchronized (mGlobalLock) {
2740 final long ident = Binder.clearCallingIdentity();
2741 try {
2742 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2743 if (stack == null) {
2744 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2745 return;
2746 }
2747 if (!stack.isActivityTypeStandardOrUndefined()) {
2748 throw new IllegalArgumentException(
2749 "Removing non-standard stack is not allowed.");
2750 }
2751 mStackSupervisor.removeStack(stack);
2752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756 }
2757
2758 @Override
2759 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761
2762 synchronized (mGlobalLock) {
2763 final long ident = Binder.clearCallingIdentity();
2764 try {
2765 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
2766 + " to displayId=" + displayId);
2767 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
2768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772 }
2773
2774 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 public void exitFreeformMode(IBinder token) {
2776 synchronized (mGlobalLock) {
2777 long ident = Binder.clearCallingIdentity();
2778 try {
2779 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2780 if (r == null) {
2781 throw new IllegalArgumentException(
2782 "exitFreeformMode: No activity record matching token=" + token);
2783 }
2784
2785 final ActivityStack stack = r.getStack();
2786 if (stack == null || !stack.inFreeformWindowingMode()) {
2787 throw new IllegalStateException(
2788 "exitFreeformMode: You can only go fullscreen from freeform.");
2789 }
2790
2791 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
2792 } finally {
2793 Binder.restoreCallingIdentity(ident);
2794 }
2795 }
2796 }
2797
2798 /** Sets the task stack listener that gets callbacks when a task stack changes. */
2799 @Override
2800 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002801 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002803 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 }
2805
2806 /** Unregister a task stack listener so that it stops receiving callbacks. */
2807 @Override
2808 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002809 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002811 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 }
2813
2814 private void reportCurKeyguardUsageEventLocked(boolean keyguardShowing) {
2815 mAm.reportGlobalUsageEventLocked(keyguardShowing
2816 ? UsageEvents.Event.KEYGUARD_SHOWN
2817 : UsageEvents.Event.KEYGUARD_HIDDEN);
2818 }
2819
2820 @Override
2821 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
2822 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
2823 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
2824 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
2825 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
2826 }
2827
2828 @Override
2829 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
2830 IBinder activityToken, int flags) {
2831 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
2832 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
2833 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
2834 }
2835
2836 @Override
2837 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
2838 Bundle args) {
2839 return enqueueAssistContext(requestType, intent, hint, null, null, null,
2840 true /* focused */, true /* newSessionId */, userHandle, args,
2841 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
2842 }
2843
2844 @Override
2845 public Bundle getAssistContextExtras(int requestType) {
2846 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
2847 null, null, true /* focused */, true /* newSessionId */,
2848 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
2849 if (pae == null) {
2850 return null;
2851 }
2852 synchronized (pae) {
2853 while (!pae.haveResult) {
2854 try {
2855 pae.wait();
2856 } catch (InterruptedException e) {
2857 }
2858 }
2859 }
2860 synchronized (mGlobalLock) {
2861 buildAssistBundleLocked(pae, pae.result);
2862 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002863 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 }
2865 return pae.extras;
2866 }
2867
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002868 /**
2869 * Binder IPC calls go through the public entry point.
2870 * This can be called with or without the global lock held.
2871 */
2872 private static int checkCallingPermission(String permission) {
2873 return checkPermission(
2874 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
2875 }
2876
2877 /** This can be called with or without the global lock held. */
2878 void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
2879 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
2880 mAmInternal.enforceCallingPermission(permission, func);
2881 }
2882 }
2883
2884 @VisibleForTesting
2885 int checkGetTasksPermission(String permission, int pid, int uid) {
2886 return checkPermission(permission, pid, uid);
2887 }
2888
2889 static int checkPermission(String permission, int pid, int uid) {
2890 if (permission == null) {
2891 return PackageManager.PERMISSION_DENIED;
2892 }
2893 return checkComponentPermission(permission, pid, uid, -1, true);
2894 }
2895
2896 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
2897 if (getRecentTasks().isCallerRecents(callingUid)) {
2898 // Always allow the recents component to get tasks
2899 return true;
2900 }
2901
2902 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
2903 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2904 if (!allowed) {
2905 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
2906 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
2907 // Temporary compatibility: some existing apps on the system image may
2908 // still be requesting the old permission and not switched to the new
2909 // one; if so, we'll still allow them full access. This means we need
2910 // to see if they are holding the old permission and are a system app.
2911 try {
2912 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
2913 allowed = true;
2914 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2915 + " is using old GET_TASKS but privileged; allowing");
2916 }
2917 } catch (RemoteException e) {
2918 }
2919 }
2920 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2921 + " does not hold REAL_GET_TASKS; limiting output");
2922 }
2923 return allowed;
2924 }
2925
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
2927 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
2928 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
2929 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002930 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 "enqueueAssistContext()");
2932
2933 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002934 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 if (activity == null) {
2936 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
2937 return null;
2938 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002939 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
2941 return null;
2942 }
2943 if (focused) {
2944 if (activityToken != null) {
2945 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
2946 if (activity != caller) {
2947 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
2948 + " is not current top " + activity);
2949 return null;
2950 }
2951 }
2952 } else {
2953 activity = ActivityRecord.forTokenLocked(activityToken);
2954 if (activity == null) {
2955 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
2956 + " couldn't be found");
2957 return null;
2958 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002959 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
2961 return null;
2962 }
2963 }
2964
2965 PendingAssistExtras pae;
2966 Bundle extras = new Bundle();
2967 if (args != null) {
2968 extras.putAll(args);
2969 }
2970 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002971 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972
2973 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
2974 userHandle);
2975 pae.isHome = activity.isActivityTypeHome();
2976
2977 // Increment the sessionId if necessary
2978 if (newSessionId) {
2979 mViSessionId++;
2980 }
2981 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002982 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
2983 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002985 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 } catch (RemoteException e) {
2987 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
2988 return null;
2989 }
2990 return pae;
2991 }
2992 }
2993
2994 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
2995 if (result != null) {
2996 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
2997 }
2998 if (pae.hint != null) {
2999 pae.extras.putBoolean(pae.hint, true);
3000 }
3001 }
3002
3003 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3004 IAssistDataReceiver receiver;
3005 synchronized (mGlobalLock) {
3006 mPendingAssistExtras.remove(pae);
3007 receiver = pae.receiver;
3008 }
3009 if (receiver != null) {
3010 // Caller wants result sent back to them.
3011 Bundle sendBundle = new Bundle();
3012 // At least return the receiver extras
3013 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3014 try {
3015 pae.receiver.onHandleAssistData(sendBundle);
3016 } catch (RemoteException e) {
3017 }
3018 }
3019 }
3020
3021 public class PendingAssistExtras extends Binder implements Runnable {
3022 public final ActivityRecord activity;
3023 public boolean isHome;
3024 public final Bundle extras;
3025 public final Intent intent;
3026 public final String hint;
3027 public final IAssistDataReceiver receiver;
3028 public final int userHandle;
3029 public boolean haveResult = false;
3030 public Bundle result = null;
3031 public AssistStructure structure = null;
3032 public AssistContent content = null;
3033 public Bundle receiverExtras;
3034
3035 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3036 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3037 int _userHandle) {
3038 activity = _activity;
3039 extras = _extras;
3040 intent = _intent;
3041 hint = _hint;
3042 receiver = _receiver;
3043 receiverExtras = _receiverExtras;
3044 userHandle = _userHandle;
3045 }
3046
3047 @Override
3048 public void run() {
3049 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3050 synchronized (this) {
3051 haveResult = true;
3052 notifyAll();
3053 }
3054 pendingAssistExtrasTimedOut(this);
3055 }
3056 }
3057
3058 @Override
3059 public boolean isAssistDataAllowedOnCurrentActivity() {
3060 int userId;
3061 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003062 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003063 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3064 return false;
3065 }
3066
3067 final ActivityRecord activity = focusedStack.getTopActivity();
3068 if (activity == null) {
3069 return false;
3070 }
3071 userId = activity.userId;
3072 }
3073 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3074 }
3075
3076 @Override
3077 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3078 long ident = Binder.clearCallingIdentity();
3079 try {
3080 synchronized (mGlobalLock) {
3081 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003082 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 if (top != caller) {
3084 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3085 + " is not current top " + top);
3086 return false;
3087 }
3088 if (!top.nowVisible) {
3089 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3090 + " is not visible");
3091 return false;
3092 }
3093 }
3094 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3095 token);
3096 } finally {
3097 Binder.restoreCallingIdentity(ident);
3098 }
3099 }
3100
3101 @Override
3102 public boolean isRootVoiceInteraction(IBinder token) {
3103 synchronized (mGlobalLock) {
3104 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3105 if (r == null) {
3106 return false;
3107 }
3108 return r.rootVoiceInteraction;
3109 }
3110 }
3111
Wale Ogunwalef6733932018-06-27 05:14:34 -07003112 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3113 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3114 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3115 if (activityToCallback == null) return;
3116 activityToCallback.setVoiceSessionLocked(voiceSession);
3117
3118 // Inform the activity
3119 try {
3120 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3121 voiceInteractor);
3122 long token = Binder.clearCallingIdentity();
3123 try {
3124 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3125 } finally {
3126 Binder.restoreCallingIdentity(token);
3127 }
3128 // TODO: VI Should we cache the activity so that it's easier to find later
3129 // rather than scan through all the stacks and activities?
3130 } catch (RemoteException re) {
3131 activityToCallback.clearVoiceSessionLocked();
3132 // TODO: VI Should this terminate the voice session?
3133 }
3134 }
3135
3136 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3137 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3138 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3139 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3140 boolean wasRunningVoice = mRunningVoice != null;
3141 mRunningVoice = session;
3142 if (!wasRunningVoice) {
3143 mVoiceWakeLock.acquire();
3144 updateSleepIfNeededLocked();
3145 }
3146 }
3147 }
3148
3149 void finishRunningVoiceLocked() {
3150 if (mRunningVoice != null) {
3151 mRunningVoice = null;
3152 mVoiceWakeLock.release();
3153 updateSleepIfNeededLocked();
3154 }
3155 }
3156
3157 @Override
3158 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3159 synchronized (mGlobalLock) {
3160 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3161 if (keepAwake) {
3162 mVoiceWakeLock.acquire();
3163 } else {
3164 mVoiceWakeLock.release();
3165 }
3166 }
3167 }
3168 }
3169
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 @Override
3171 public ComponentName getActivityClassForToken(IBinder token) {
3172 synchronized (mGlobalLock) {
3173 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3174 if (r == null) {
3175 return null;
3176 }
3177 return r.intent.getComponent();
3178 }
3179 }
3180
3181 @Override
3182 public String getPackageForToken(IBinder token) {
3183 synchronized (mGlobalLock) {
3184 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3185 if (r == null) {
3186 return null;
3187 }
3188 return r.packageName;
3189 }
3190 }
3191
3192 @Override
3193 public void showLockTaskEscapeMessage(IBinder token) {
3194 synchronized (mGlobalLock) {
3195 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3196 if (r == null) {
3197 return;
3198 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003199 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 }
3201 }
3202
3203 @Override
3204 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003205 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 final long token = Binder.clearCallingIdentity();
3207 try {
3208 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003209 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 }
3211 } finally {
3212 Binder.restoreCallingIdentity(token);
3213 }
3214 }
3215
3216 /**
3217 * Try to place task to provided position. The final position might be different depending on
3218 * current user and stacks state. The task will be moved to target stack if it's currently in
3219 * different stack.
3220 */
3221 @Override
3222 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003223 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 synchronized (mGlobalLock) {
3225 long ident = Binder.clearCallingIdentity();
3226 try {
3227 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3228 + taskId + " in stackId=" + stackId + " at position=" + position);
3229 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3230 if (task == null) {
3231 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3232 + taskId);
3233 }
3234
3235 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3236
3237 if (stack == null) {
3238 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3239 + stackId);
3240 }
3241 if (!stack.isActivityTypeStandardOrUndefined()) {
3242 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3243 + " the position of task " + taskId + " in/to non-standard stack");
3244 }
3245
3246 // TODO: Have the callers of this API call a separate reparent method if that is
3247 // what they intended to do vs. having this method also do reparenting.
3248 if (task.getStack() == stack) {
3249 // Change position in current stack.
3250 stack.positionChildAt(task, position);
3251 } else {
3252 // Reparent to new stack.
3253 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3254 !DEFER_RESUME, "positionTaskInStack");
3255 }
3256 } finally {
3257 Binder.restoreCallingIdentity(ident);
3258 }
3259 }
3260 }
3261
3262 @Override
3263 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3264 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3265 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3266 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3267 synchronized (mGlobalLock) {
3268 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3269 if (record == null) {
3270 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3271 + "found for: " + token);
3272 }
3273 record.setSizeConfigurations(horizontalSizeConfiguration,
3274 verticalSizeConfigurations, smallestSizeConfigurations);
3275 }
3276 }
3277
3278 /**
3279 * Dismisses split-screen multi-window mode.
3280 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3281 */
3282 @Override
3283 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003284 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3286 final long ident = Binder.clearCallingIdentity();
3287 try {
3288 synchronized (mGlobalLock) {
3289 final ActivityStack stack =
3290 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3291 if (stack == null) {
3292 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3293 return;
3294 }
3295
3296 if (toTop) {
3297 // Caller wants the current split-screen primary stack to be the top stack after
3298 // it goes fullscreen, so move it to the front.
3299 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003300 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301 // In this case the current split-screen primary stack shouldn't be the top
3302 // stack after it goes fullscreen, but it current has focus, so we move the
3303 // focus to the top-most split-screen secondary stack next to it.
3304 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3305 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3306 if (otherStack != null) {
3307 otherStack.moveToFront("dismissSplitScreenMode_other");
3308 }
3309 }
3310
3311 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3312 }
3313 } finally {
3314 Binder.restoreCallingIdentity(ident);
3315 }
3316 }
3317
3318 /**
3319 * Dismisses Pip
3320 * @param animate True if the dismissal should be animated.
3321 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3322 * default animation duration should be used.
3323 */
3324 @Override
3325 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 final long ident = Binder.clearCallingIdentity();
3328 try {
3329 synchronized (mGlobalLock) {
3330 final PinnedActivityStack stack =
3331 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3332 if (stack == null) {
3333 Slog.w(TAG, "dismissPip: pinned stack not found.");
3334 return;
3335 }
3336 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3337 throw new IllegalArgumentException("Stack: " + stack
3338 + " doesn't support animated resize.");
3339 }
3340 if (animate) {
3341 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3342 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3343 } else {
3344 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3345 }
3346 }
3347 } finally {
3348 Binder.restoreCallingIdentity(ident);
3349 }
3350 }
3351
3352 @Override
3353 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003354 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355 synchronized (mGlobalLock) {
3356 mSuppressResizeConfigChanges = suppress;
3357 }
3358 }
3359
3360 /**
3361 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3362 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3363 * activity and clearing the task at the same time.
3364 */
3365 @Override
3366 // TODO: API should just be about changing windowing modes...
3367 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003368 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 "moveTasksToFullscreenStack()");
3370 synchronized (mGlobalLock) {
3371 final long origId = Binder.clearCallingIdentity();
3372 try {
3373 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3374 if (stack != null){
3375 if (!stack.isActivityTypeStandardOrUndefined()) {
3376 throw new IllegalArgumentException(
3377 "You can't move tasks from non-standard stacks.");
3378 }
3379 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3380 }
3381 } finally {
3382 Binder.restoreCallingIdentity(origId);
3383 }
3384 }
3385 }
3386
3387 /**
3388 * Moves the top activity in the input stackId to the pinned stack.
3389 *
3390 * @param stackId Id of stack to move the top activity to pinned stack.
3391 * @param bounds Bounds to use for pinned stack.
3392 *
3393 * @return True if the top activity of the input stack was successfully moved to the pinned
3394 * stack.
3395 */
3396 @Override
3397 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003398 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 "moveTopActivityToPinnedStack()");
3400 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003401 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3403 + "Device doesn't support picture-in-picture mode");
3404 }
3405
3406 long ident = Binder.clearCallingIdentity();
3407 try {
3408 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3409 } finally {
3410 Binder.restoreCallingIdentity(ident);
3411 }
3412 }
3413 }
3414
3415 @Override
3416 public boolean isInMultiWindowMode(IBinder token) {
3417 final long origId = Binder.clearCallingIdentity();
3418 try {
3419 synchronized (mGlobalLock) {
3420 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3421 if (r == null) {
3422 return false;
3423 }
3424 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3425 return r.inMultiWindowMode();
3426 }
3427 } finally {
3428 Binder.restoreCallingIdentity(origId);
3429 }
3430 }
3431
3432 @Override
3433 public boolean isInPictureInPictureMode(IBinder token) {
3434 final long origId = Binder.clearCallingIdentity();
3435 try {
3436 synchronized (mGlobalLock) {
3437 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3438 }
3439 } finally {
3440 Binder.restoreCallingIdentity(origId);
3441 }
3442 }
3443
3444 private boolean isInPictureInPictureMode(ActivityRecord r) {
3445 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3446 || r.getStack().isInStackLocked(r) == null) {
3447 return false;
3448 }
3449
3450 // If we are animating to fullscreen then we have already dispatched the PIP mode
3451 // changed, so we should reflect that check here as well.
3452 final PinnedActivityStack stack = r.getStack();
3453 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3454 return !windowController.isAnimatingBoundsToFullscreen();
3455 }
3456
3457 @Override
3458 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3459 final long origId = Binder.clearCallingIdentity();
3460 try {
3461 synchronized (mGlobalLock) {
3462 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3463 "enterPictureInPictureMode", token, params);
3464
3465 // If the activity is already in picture in picture mode, then just return early
3466 if (isInPictureInPictureMode(r)) {
3467 return true;
3468 }
3469
3470 // Activity supports picture-in-picture, now check that we can enter PiP at this
3471 // point, if it is
3472 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3473 false /* beforeStopping */)) {
3474 return false;
3475 }
3476
3477 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003478 synchronized (mGlobalLock) {
3479 // Only update the saved args from the args that are set
3480 r.pictureInPictureArgs.copyOnlySet(params);
3481 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3482 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3483 // Adjust the source bounds by the insets for the transition down
3484 final Rect sourceBounds = new Rect(
3485 r.pictureInPictureArgs.getSourceRectHint());
3486 mStackSupervisor.moveActivityToPinnedStackLocked(
3487 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3488 final PinnedActivityStack stack = r.getStack();
3489 stack.setPictureInPictureAspectRatio(aspectRatio);
3490 stack.setPictureInPictureActions(actions);
3491 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3492 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3493 logPictureInPictureArgs(params);
3494 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003495 };
3496
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003497 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003498 // If the keyguard is showing or occluded, then try and dismiss it before
3499 // entering picture-in-picture (this will prompt the user to authenticate if the
3500 // device is currently locked).
3501 dismissKeyguard(token, new KeyguardDismissCallback() {
3502 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003503 public void onDismissSucceeded() {
3504 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 }
3506 }, null /* message */);
3507 } else {
3508 // Enter picture in picture immediately otherwise
3509 enterPipRunnable.run();
3510 }
3511 return true;
3512 }
3513 } finally {
3514 Binder.restoreCallingIdentity(origId);
3515 }
3516 }
3517
3518 @Override
3519 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3520 final long origId = Binder.clearCallingIdentity();
3521 try {
3522 synchronized (mGlobalLock) {
3523 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3524 "setPictureInPictureParams", token, params);
3525
3526 // Only update the saved args from the args that are set
3527 r.pictureInPictureArgs.copyOnlySet(params);
3528 if (r.inPinnedWindowingMode()) {
3529 // If the activity is already in picture-in-picture, update the pinned stack now
3530 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3531 // be used the next time the activity enters PiP
3532 final PinnedActivityStack stack = r.getStack();
3533 if (!stack.isAnimatingBoundsToFullscreen()) {
3534 stack.setPictureInPictureAspectRatio(
3535 r.pictureInPictureArgs.getAspectRatio());
3536 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3537 }
3538 }
3539 logPictureInPictureArgs(params);
3540 }
3541 } finally {
3542 Binder.restoreCallingIdentity(origId);
3543 }
3544 }
3545
3546 @Override
3547 public int getMaxNumPictureInPictureActions(IBinder token) {
3548 // Currently, this is a static constant, but later, we may change this to be dependent on
3549 // the context of the activity
3550 return 3;
3551 }
3552
3553 private void logPictureInPictureArgs(PictureInPictureParams params) {
3554 if (params.hasSetActions()) {
3555 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3556 params.getActions().size());
3557 }
3558 if (params.hasSetAspectRatio()) {
3559 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3560 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3561 MetricsLogger.action(lm);
3562 }
3563 }
3564
3565 /**
3566 * Checks the state of the system and the activity associated with the given {@param token} to
3567 * verify that picture-in-picture is supported for that activity.
3568 *
3569 * @return the activity record for the given {@param token} if all the checks pass.
3570 */
3571 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3572 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003573 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003574 throw new IllegalStateException(caller
3575 + ": Device doesn't support picture-in-picture mode.");
3576 }
3577
3578 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3579 if (r == null) {
3580 throw new IllegalStateException(caller
3581 + ": Can't find activity for token=" + token);
3582 }
3583
3584 if (!r.supportsPictureInPicture()) {
3585 throw new IllegalStateException(caller
3586 + ": Current activity does not support picture-in-picture.");
3587 }
3588
3589 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 params.getAspectRatio())) {
3592 final float minAspectRatio = mContext.getResources().getFloat(
3593 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3594 final float maxAspectRatio = mContext.getResources().getFloat(
3595 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3596 throw new IllegalArgumentException(String.format(caller
3597 + ": Aspect ratio is too extreme (must be between %f and %f).",
3598 minAspectRatio, maxAspectRatio));
3599 }
3600
3601 // Truncate the number of actions if necessary
3602 params.truncateActions(getMaxNumPictureInPictureActions(token));
3603
3604 return r;
3605 }
3606
3607 @Override
3608 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003609 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610 synchronized (mGlobalLock) {
3611 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3612 if (r == null) {
3613 throw new IllegalArgumentException("Activity does not exist; token="
3614 + activityToken);
3615 }
3616 return r.getUriPermissionsLocked().getExternalTokenLocked();
3617 }
3618 }
3619
3620 @Override
3621 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3622 Rect tempDockedTaskInsetBounds,
3623 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003624 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 long ident = Binder.clearCallingIdentity();
3626 try {
3627 synchronized (mGlobalLock) {
3628 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3629 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3630 PRESERVE_WINDOWS);
3631 }
3632 } finally {
3633 Binder.restoreCallingIdentity(ident);
3634 }
3635 }
3636
3637 @Override
3638 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003639 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003640 final long ident = Binder.clearCallingIdentity();
3641 try {
3642 synchronized (mGlobalLock) {
3643 mStackSupervisor.setSplitScreenResizing(resizing);
3644 }
3645 } finally {
3646 Binder.restoreCallingIdentity(ident);
3647 }
3648 }
3649
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003650 /**
3651 * Check that we have the features required for VR-related API calls, and throw an exception if
3652 * not.
3653 */
3654 void enforceSystemHasVrFeature() {
3655 if (!mContext.getPackageManager().hasSystemFeature(
3656 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3657 throw new UnsupportedOperationException("VR mode not supported on this device!");
3658 }
3659 }
3660
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003661 @Override
3662 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003663 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003664
3665 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3666
3667 ActivityRecord r;
3668 synchronized (mGlobalLock) {
3669 r = ActivityRecord.isInStackLocked(token);
3670 }
3671
3672 if (r == null) {
3673 throw new IllegalArgumentException();
3674 }
3675
3676 int err;
3677 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3678 VrManagerInternal.NO_ERROR) {
3679 return err;
3680 }
3681
3682 // Clear the binder calling uid since this path may call moveToTask().
3683 final long callingId = Binder.clearCallingIdentity();
3684 try {
3685 synchronized (mGlobalLock) {
3686 r.requestedVrComponent = (enabled) ? packageName : null;
3687
3688 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003689 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003690 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 }
3692 return 0;
3693 }
3694 } finally {
3695 Binder.restoreCallingIdentity(callingId);
3696 }
3697 }
3698
3699 @Override
3700 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3701 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3702 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003703 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003704 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3705 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3706 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003707 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 || activity.voiceSession != null) {
3709 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3710 return;
3711 }
3712 if (activity.pendingVoiceInteractionStart) {
3713 Slog.w(TAG, "Pending start of voice interaction already.");
3714 return;
3715 }
3716 activity.pendingVoiceInteractionStart = true;
3717 }
3718 LocalServices.getService(VoiceInteractionManagerInternal.class)
3719 .startLocalVoiceInteraction(callingActivity, options);
3720 }
3721
3722 @Override
3723 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3724 LocalServices.getService(VoiceInteractionManagerInternal.class)
3725 .stopLocalVoiceInteraction(callingActivity);
3726 }
3727
3728 @Override
3729 public boolean supportsLocalVoiceInteraction() {
3730 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3731 .supportsLocalVoiceInteraction();
3732 }
3733
3734 /** Notifies all listeners when the pinned stack animation starts. */
3735 @Override
3736 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003737 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 }
3739
3740 /** Notifies all listeners when the pinned stack animation ends. */
3741 @Override
3742 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003743 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 }
3745
3746 @Override
3747 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003748 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 final long ident = Binder.clearCallingIdentity();
3750 try {
3751 synchronized (mGlobalLock) {
3752 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3753 }
3754 } finally {
3755 Binder.restoreCallingIdentity(ident);
3756 }
3757 }
3758
3759 @Override
3760 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003761 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003762
3763 synchronized (mGlobalLock) {
3764 // Check if display is initialized in AM.
3765 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3766 // Call might come when display is not yet added or has already been removed.
3767 if (DEBUG_CONFIGURATION) {
3768 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
3769 + displayId);
3770 }
3771 return false;
3772 }
3773
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003774 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003776 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003777 }
3778
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003779 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003780 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003781 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 }
3783
3784 final long origId = Binder.clearCallingIdentity();
3785 try {
3786 if (values != null) {
3787 Settings.System.clearConfiguration(values);
3788 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003789 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003790 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
3791 return mTmpUpdateConfigurationResult.changes != 0;
3792 } finally {
3793 Binder.restoreCallingIdentity(origId);
3794 }
3795 }
3796 }
3797
3798 @Override
3799 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003800 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801
3802 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003803 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003805 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 }
3807
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003808 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003809 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003810 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003811 }
3812
3813 final long origId = Binder.clearCallingIdentity();
3814 try {
3815 if (values != null) {
3816 Settings.System.clearConfiguration(values);
3817 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003818 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003819 UserHandle.USER_NULL, false /* deferResume */,
3820 mTmpUpdateConfigurationResult);
3821 return mTmpUpdateConfigurationResult.changes != 0;
3822 } finally {
3823 Binder.restoreCallingIdentity(origId);
3824 }
3825 }
3826 }
3827
3828 @Override
3829 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
3830 CharSequence message) {
3831 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003832 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
3834 }
3835 final long callingId = Binder.clearCallingIdentity();
3836 try {
3837 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003838 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 }
3840 } finally {
3841 Binder.restoreCallingIdentity(callingId);
3842 }
3843 }
3844
3845 @Override
3846 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003847 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 "cancelTaskWindowTransition()");
3849 final long ident = Binder.clearCallingIdentity();
3850 try {
3851 synchronized (mGlobalLock) {
3852 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
3853 MATCH_TASK_IN_STACKS_ONLY);
3854 if (task == null) {
3855 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
3856 return;
3857 }
3858 task.cancelWindowTransition();
3859 }
3860 } finally {
3861 Binder.restoreCallingIdentity(ident);
3862 }
3863 }
3864
3865 @Override
3866 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003867 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003868 final long ident = Binder.clearCallingIdentity();
3869 try {
3870 final TaskRecord task;
3871 synchronized (mGlobalLock) {
3872 task = mStackSupervisor.anyTaskForIdLocked(taskId,
3873 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3874 if (task == null) {
3875 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
3876 return null;
3877 }
3878 }
3879 // Don't call this while holding the lock as this operation might hit the disk.
3880 return task.getSnapshot(reducedResolution);
3881 } finally {
3882 Binder.restoreCallingIdentity(ident);
3883 }
3884 }
3885
3886 @Override
3887 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
3888 synchronized (mGlobalLock) {
3889 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3890 if (r == null) {
3891 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
3892 + token);
3893 return;
3894 }
3895 final long origId = Binder.clearCallingIdentity();
3896 try {
3897 r.setDisablePreviewScreenshots(disable);
3898 } finally {
3899 Binder.restoreCallingIdentity(origId);
3900 }
3901 }
3902 }
3903
3904 /** Return the user id of the last resumed activity. */
3905 @Override
3906 public @UserIdInt
3907 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
3910 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07003911 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003912 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003914 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 }
3916 }
3917
3918 @Override
3919 public void updateLockTaskFeatures(int userId, int flags) {
3920 final int callingUid = Binder.getCallingUid();
3921 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003922 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 "updateLockTaskFeatures()");
3924 }
3925 synchronized (mGlobalLock) {
3926 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
3927 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003928 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 }
3930 }
3931
3932 @Override
3933 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
3934 synchronized (mGlobalLock) {
3935 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3936 if (r == null) {
3937 return;
3938 }
3939 final long origId = Binder.clearCallingIdentity();
3940 try {
3941 r.setShowWhenLocked(showWhenLocked);
3942 } finally {
3943 Binder.restoreCallingIdentity(origId);
3944 }
3945 }
3946 }
3947
3948 @Override
3949 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
3950 synchronized (mGlobalLock) {
3951 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3952 if (r == null) {
3953 return;
3954 }
3955 final long origId = Binder.clearCallingIdentity();
3956 try {
3957 r.setTurnScreenOn(turnScreenOn);
3958 } finally {
3959 Binder.restoreCallingIdentity(origId);
3960 }
3961 }
3962 }
3963
3964 @Override
3965 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003966 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003967 "registerRemoteAnimations");
3968 definition.setCallingPid(Binder.getCallingPid());
3969 synchronized (mGlobalLock) {
3970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3971 if (r == null) {
3972 return;
3973 }
3974 final long origId = Binder.clearCallingIdentity();
3975 try {
3976 r.registerRemoteAnimations(definition);
3977 } finally {
3978 Binder.restoreCallingIdentity(origId);
3979 }
3980 }
3981 }
3982
3983 @Override
3984 public void registerRemoteAnimationForNextActivityStart(String packageName,
3985 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 "registerRemoteAnimationForNextActivityStart");
3988 adapter.setCallingPid(Binder.getCallingPid());
3989 synchronized (mGlobalLock) {
3990 final long origId = Binder.clearCallingIdentity();
3991 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07003992 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 packageName, adapter);
3994 } finally {
3995 Binder.restoreCallingIdentity(origId);
3996 }
3997 }
3998 }
3999
4000 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4001 @Override
4002 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4003 synchronized (mGlobalLock) {
4004 final long origId = Binder.clearCallingIdentity();
4005 try {
4006 mAm.mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4007 } finally {
4008 Binder.restoreCallingIdentity(origId);
4009 }
4010 }
4011 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004012
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004013 @Override
4014 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004015 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004016 synchronized (mGlobalLock) {
4017 synchronized (mAm.mPidsSelfLocked) {
4018 final int pid = Binder.getCallingPid();
4019 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004020 mVrController.setVrThreadLocked(tid, pid, proc.getWindowProcessController());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004021 }
4022 }
4023 }
4024
4025 @Override
4026 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004027 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004028 != PERMISSION_GRANTED) {
4029 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4030 + Binder.getCallingPid()
4031 + ", uid=" + Binder.getCallingUid()
4032 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4033 Slog.w(TAG, msg);
4034 throw new SecurityException(msg);
4035 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004036 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004037 synchronized (mGlobalLock) {
4038 synchronized (mAm.mPidsSelfLocked) {
4039 final int pid = Binder.getCallingPid();
4040 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
4041 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4042 }
4043 }
4044 }
4045
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 @Override
4047 public void stopAppSwitches() {
4048 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4049 synchronized (mGlobalLock) {
4050 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4051 mDidAppSwitch = false;
4052 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4053 }
4054 }
4055
4056 @Override
4057 public void resumeAppSwitches() {
4058 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4059 synchronized (mGlobalLock) {
4060 // Note that we don't execute any pending app switches... we will
4061 // let those wait until either the timeout, or the next start
4062 // activity request.
4063 mAppSwitchesAllowedTime = 0;
4064 }
4065 }
4066
4067 void onStartActivitySetDidAppSwitch() {
4068 if (mDidAppSwitch) {
4069 // This is the second allowed switch since we stopped switches, so now just generally
4070 // allow switches. Use case:
4071 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4072 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4073 // anyone to switch again).
4074 mAppSwitchesAllowedTime = 0;
4075 } else {
4076 mDidAppSwitch = true;
4077 }
4078 }
4079
4080 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004081 boolean shouldDisableNonVrUiLocked() {
4082 return mVrController.shouldDisableNonVrUiLocked();
4083 }
4084
4085 void applyUpdateVrModeLocked(ActivityRecord r) {
4086 // VR apps are expected to run in a main display. If an app is turning on VR for
4087 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4088 // fullscreen stack before enabling VR Mode.
4089 // TODO: The goal of this code is to keep the VR app on the main display. When the
4090 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4091 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4092 // option would be a better choice here.
4093 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4094 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4095 + " to main stack for VR");
4096 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4097 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4098 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4099 }
4100 mH.post(() -> {
4101 if (!mVrController.onVrModeChanged(r)) {
4102 return;
4103 }
4104 synchronized (mGlobalLock) {
4105 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4106 mWindowManager.disableNonVrUi(disableNonVrUi);
4107 if (disableNonVrUi) {
4108 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4109 // then remove the pinned stack.
4110 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4111 }
4112 }
4113 });
4114 }
4115
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004116 ActivityStack getTopDisplayFocusedStack() {
4117 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004118 }
4119
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004120 /** Pokes the task persister. */
4121 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4122 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4123 }
4124
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004125 void onTopProcChangedLocked(WindowProcessController proc) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004126 mVrController.onTopProcChangedLocked(proc);
4127 }
4128
4129 boolean isKeyguardLocked() {
4130 return mKeyguardController.isKeyguardLocked();
4131 }
4132
4133 boolean isNextTransitionForward() {
4134 int transit = mWindowManager.getPendingAppTransition();
4135 return transit == TRANSIT_ACTIVITY_OPEN
4136 || transit == TRANSIT_TASK_OPEN
4137 || transit == TRANSIT_TASK_TO_FRONT;
4138 }
4139
Wale Ogunwalef6733932018-06-27 05:14:34 -07004140 void dumpSleepStates(PrintWriter pw, boolean testPssMode) {
4141 synchronized (mGlobalLock) {
4142 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
4143 if (mRunningVoice != null) {
4144 pw.println(" mRunningVoice=" + mRunningVoice);
4145 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
4146 }
4147 pw.println(" mSleeping=" + mSleeping);
4148 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
4149 pw.println(" mVrController=" + mVrController);
4150 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004151 }
4152
Wale Ogunwalef6733932018-06-27 05:14:34 -07004153 void writeSleepStateToProto(ProtoOutputStream proto) {
4154 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4155 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4156 st.toString());
4157 }
4158
4159 if (mRunningVoice != null) {
4160 final long vrToken = proto.start(
4161 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4162 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4163 mRunningVoice.toString());
4164 mVoiceWakeLock.writeToProto(
4165 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4166 proto.end(vrToken);
4167 }
4168
4169 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4170 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4171 mShuttingDown);
4172 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004173 }
4174
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004175 int getCurrentUserId() {
4176 return mAmInternal.getCurrentUserId();
4177 }
4178
4179 private void enforceNotIsolatedCaller(String caller) {
4180 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4181 throw new SecurityException("Isolated process not allowed to call " + caller);
4182 }
4183 }
4184
Wale Ogunwalef6733932018-06-27 05:14:34 -07004185 public Configuration getConfiguration() {
4186 Configuration ci;
4187 synchronized(mGlobalLock) {
4188 ci = new Configuration(getGlobalConfiguration());
4189 ci.userSetLocale = false;
4190 }
4191 return ci;
4192 }
4193
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004194 /**
4195 * Current global configuration information. Contains general settings for the entire system,
4196 * also corresponds to the merged configuration of the default display.
4197 */
4198 Configuration getGlobalConfiguration() {
4199 return mStackSupervisor.getConfiguration();
4200 }
4201
4202 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4203 boolean initLocale) {
4204 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4205 }
4206
4207 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4208 boolean initLocale, boolean deferResume) {
4209 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4210 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4211 UserHandle.USER_NULL, deferResume);
4212 }
4213
4214 void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4215 final long origId = Binder.clearCallingIdentity();
4216 try {
4217 synchronized (mGlobalLock) {
4218 updateConfigurationLocked(values, null, false, true, userId,
4219 false /* deferResume */);
4220 }
4221 } finally {
4222 Binder.restoreCallingIdentity(origId);
4223 }
4224 }
4225
4226 void updateUserConfiguration() {
4227 synchronized (mGlobalLock) {
4228 final Configuration configuration = new Configuration(getGlobalConfiguration());
4229 final int currentUserId = mAmInternal.getCurrentUserId();
4230 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(), configuration,
4231 currentUserId, Settings.System.canWrite(mContext));
4232 updateConfigurationLocked(configuration, null /* starting */, false /* initLocale */,
4233 false /* persistent */, currentUserId, false /* deferResume */);
4234 }
4235 }
4236
4237 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4238 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4239 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4240 deferResume, null /* result */);
4241 }
4242
4243 /**
4244 * Do either or both things: (1) change the current configuration, and (2)
4245 * make sure the given activity is running with the (now) current
4246 * configuration. Returns true if the activity has been left running, or
4247 * false if <var>starting</var> is being destroyed to match the new
4248 * configuration.
4249 *
4250 * @param userId is only used when persistent parameter is set to true to persist configuration
4251 * for that particular user
4252 */
4253 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4254 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4255 ActivityTaskManagerService.UpdateConfigurationResult result) {
4256 int changes = 0;
4257 boolean kept = true;
4258
4259 if (mWindowManager != null) {
4260 mWindowManager.deferSurfaceLayout();
4261 }
4262 try {
4263 if (values != null) {
4264 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4265 deferResume);
4266 }
4267
4268 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4269 } finally {
4270 if (mWindowManager != null) {
4271 mWindowManager.continueSurfaceLayout();
4272 }
4273 }
4274
4275 if (result != null) {
4276 result.changes = changes;
4277 result.activityRelaunched = !kept;
4278 }
4279 return kept;
4280 }
4281
4282 /**
4283 * Returns true if this configuration change is interesting enough to send an
4284 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
4285 */
4286 private static boolean isSplitConfigurationChange(int configDiff) {
4287 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
4288 }
4289
4290 /** Update default (global) configuration and notify listeners about changes. */
4291 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4292 boolean persistent, int userId, boolean deferResume) {
4293 mTempConfig.setTo(getGlobalConfiguration());
4294 final int changes = mTempConfig.updateFrom(values);
4295 if (changes == 0) {
4296 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4297 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4298 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4299 // (even if there are no actual changes) to unfreeze the window.
4300 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4301 return 0;
4302 }
4303
4304 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4305 "Updating global configuration to: " + values);
4306
4307 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4308 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4309 values.colorMode,
4310 values.densityDpi,
4311 values.fontScale,
4312 values.hardKeyboardHidden,
4313 values.keyboard,
4314 values.keyboardHidden,
4315 values.mcc,
4316 values.mnc,
4317 values.navigation,
4318 values.navigationHidden,
4319 values.orientation,
4320 values.screenHeightDp,
4321 values.screenLayout,
4322 values.screenWidthDp,
4323 values.smallestScreenWidthDp,
4324 values.touchscreen,
4325 values.uiMode);
4326
4327
4328 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4329 final LocaleList locales = values.getLocales();
4330 int bestLocaleIndex = 0;
4331 if (locales.size() > 1) {
4332 if (mSupportedSystemLocales == null) {
4333 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4334 }
4335 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4336 }
4337 SystemProperties.set("persist.sys.locale",
4338 locales.get(bestLocaleIndex).toLanguageTag());
4339 LocaleList.setDefault(locales, bestLocaleIndex);
4340 mAm.mHandler.sendMessage(mAm.mHandler.obtainMessage(SEND_LOCALE_TO_MOUNT_DAEMON_MSG,
4341 locales.get(bestLocaleIndex)));
4342 }
4343
4344 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
4345 mTempConfig.seq = mConfigurationSeq;
4346
4347 // Update stored global config and notify everyone about the change.
4348 mStackSupervisor.onConfigurationChanged(mTempConfig);
4349
4350 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4351 // TODO(multi-display): Update UsageEvents#Event to include displayId.
4352 mAm.mUsageStatsService.reportConfigurationChange(
4353 mTempConfig, mAmInternal.getCurrentUserId());
4354
4355 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004356 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004357
4358 AttributeCache ac = AttributeCache.instance();
4359 if (ac != null) {
4360 ac.updateConfiguration(mTempConfig);
4361 }
4362
4363 // Make sure all resources in our process are updated right now, so that anyone who is going
4364 // to retrieve resource values after we return will be sure to get the new ones. This is
4365 // especially important during boot, where the first config change needs to guarantee all
4366 // resources have that config before following boot code is executed.
4367 mAm.mSystemThread.applyConfigurationToResources(mTempConfig);
4368
4369 // We need another copy of global config because we're scheduling some calls instead of
4370 // running them in place. We need to be sure that object we send will be handled unchanged.
4371 final Configuration configCopy = new Configuration(mTempConfig);
4372 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
4373 Message msg = mAm.mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
4374 msg.obj = configCopy;
4375 msg.arg1 = userId;
4376 mAm.mHandler.sendMessage(msg);
4377 }
4378
4379 for (int i = mAm.mLruProcesses.size() - 1; i >= 0; i--) {
4380 ProcessRecord app = mAm.mLruProcesses.get(i);
4381 try {
4382 if (app.thread != null) {
4383 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Sending to proc "
4384 + app.processName + " new config " + configCopy);
4385 getLifecycleManager().scheduleTransaction(app.thread,
4386 ConfigurationChangeItem.obtain(configCopy));
4387 }
4388 } catch (Exception e) {
4389 Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change", e);
4390 }
4391 }
4392
4393 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
4394 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING
4395 | Intent.FLAG_RECEIVER_FOREGROUND
4396 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4397 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4398 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4399 UserHandle.USER_ALL);
4400 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
4401 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
4402 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
4403 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
4404 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4405 if (initLocale || !mAm.mProcessesReady) {
4406 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4407 }
4408 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4409 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4410 UserHandle.USER_ALL);
4411 }
4412
4413 // Send a broadcast to PackageInstallers if the configuration change is interesting
4414 // for the purposes of installing additional splits.
4415 if (!initLocale && isSplitConfigurationChange(changes)) {
4416 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
4417 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
4418 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4419
4420 // Typically only app stores will have this permission.
4421 String[] permissions = new String[] { android.Manifest.permission.INSTALL_PACKAGES };
4422 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, permissions,
4423 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
4424 }
4425
4426 // Override configuration of the default display duplicates global config, so we need to
4427 // update it also. This will also notify WindowManager about changes.
4428 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4429 DEFAULT_DISPLAY);
4430
4431 return changes;
4432 }
4433
4434 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4435 boolean deferResume, int displayId) {
4436 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4437 displayId, null /* result */);
4438 }
4439
4440 /**
4441 * Updates override configuration specific for the selected display. If no config is provided,
4442 * new one will be computed in WM based on current display info.
4443 */
4444 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4445 ActivityRecord starting, boolean deferResume, int displayId,
4446 ActivityTaskManagerService.UpdateConfigurationResult result) {
4447 int changes = 0;
4448 boolean kept = true;
4449
4450 if (mWindowManager != null) {
4451 mWindowManager.deferSurfaceLayout();
4452 }
4453 try {
4454 if (values != null) {
4455 if (displayId == DEFAULT_DISPLAY) {
4456 // Override configuration of the default display duplicates global config, so
4457 // we're calling global config update instead for default display. It will also
4458 // apply the correct override config.
4459 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4460 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4461 } else {
4462 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4463 }
4464 }
4465
4466 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4467 } finally {
4468 if (mWindowManager != null) {
4469 mWindowManager.continueSurfaceLayout();
4470 }
4471 }
4472
4473 if (result != null) {
4474 result.changes = changes;
4475 result.activityRelaunched = !kept;
4476 }
4477 return kept;
4478 }
4479
4480 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4481 int displayId) {
4482 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4483 final int changes = mTempConfig.updateFrom(values);
4484 if (changes != 0) {
4485 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4486 + mTempConfig + " for displayId=" + displayId);
4487 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4488
4489 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4490 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
4491 mAm.mAppWarnings.onDensityChanged();
4492
4493 mAm.killAllBackgroundProcessesExcept(N,
4494 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4495 }
4496 }
4497
4498 // Update the configuration with WM first and check if any of the stacks need to be resized
4499 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4500 // necessary. This way we don't need to relaunch again afterwards in
4501 // ensureActivityConfiguration().
4502 if (mWindowManager != null) {
4503 final int[] resizedStacks =
4504 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4505 if (resizedStacks != null) {
4506 for (int stackId : resizedStacks) {
4507 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4508 }
4509 }
4510 }
4511
4512 return changes;
4513 }
4514
Wale Ogunwalef6733932018-06-27 05:14:34 -07004515 private void updateEventDispatchingLocked(boolean booted) {
4516 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4517 }
4518
4519 void enableScreenAfterBoot(boolean booted) {
4520 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4521 SystemClock.uptimeMillis());
4522 mWindowManager.enableScreenAfterBoot();
4523
4524 synchronized (mGlobalLock) {
4525 updateEventDispatchingLocked(booted);
4526 }
4527 }
4528
4529 boolean canShowErrorDialogs() {
4530 return mShowDialogs && !mSleeping && !mShuttingDown
4531 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
4532 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
Wale Ogunwale86b74462018-07-02 08:42:43 -07004533 mAmInternal.getCurrentUserId())
Wale Ogunwalef6733932018-06-27 05:14:34 -07004534 && !(UserManager.isDeviceInDemoMode(mContext)
Wale Ogunwale86b74462018-07-02 08:42:43 -07004535 && mAmInternal.getCurrentUser().isDemo());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004536 }
4537
4538 /**
4539 * Decide based on the configuration whether we should show the ANR,
4540 * crash, etc dialogs. The idea is that if there is no affordance to
4541 * press the on-screen buttons, or the user experience would be more
4542 * greatly impacted than the crash itself, we shouldn't show the dialog.
4543 *
4544 * A thought: SystemUI might also want to get told about this, the Power
4545 * dialog / global actions also might want different behaviors.
4546 */
4547 private void updateShouldShowDialogsLocked(Configuration config) {
4548 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4549 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4550 && config.navigation == Configuration.NAVIGATION_NONAV);
4551 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4552 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4553 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4554 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4555 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4556 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4557 HIDE_ERROR_DIALOGS, 0) != 0;
4558 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4559 }
4560
4561 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4562 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4563 FONT_SCALE, 1.0f, userId);
4564
4565 synchronized (this) {
4566 if (getGlobalConfiguration().fontScale == scaleFactor) {
4567 return;
4568 }
4569
4570 final Configuration configuration
4571 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4572 configuration.fontScale = scaleFactor;
4573 updatePersistentConfiguration(configuration, userId);
4574 }
4575 }
4576
4577 // Actually is sleeping or shutting down or whatever else in the future
4578 // is an inactive state.
4579 boolean isSleepingOrShuttingDownLocked() {
4580 return isSleepingLocked() || mShuttingDown;
4581 }
4582
4583 boolean isSleepingLocked() {
4584 return mSleeping;
4585 }
4586
4587 /**
4588 * Update AMS states when an activity is resumed. This should only be called by
4589 * {@link ActivityStack#onActivityStateChanged(
4590 * ActivityRecord, ActivityStack.ActivityState, String)} when an activity is resumed.
4591 */
4592 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4593 final TaskRecord task = r.getTask();
4594 if (task.isActivityTypeStandard()) {
4595 if (mCurAppTimeTracker != r.appTimeTracker) {
4596 // We are switching app tracking. Complete the current one.
4597 if (mCurAppTimeTracker != null) {
4598 mCurAppTimeTracker.stop();
4599 mH.obtainMessage(
4600 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4601 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4602 mCurAppTimeTracker = null;
4603 }
4604 if (r.appTimeTracker != null) {
4605 mCurAppTimeTracker = r.appTimeTracker;
4606 startTimeTrackingFocusedActivityLocked();
4607 }
4608 } else {
4609 startTimeTrackingFocusedActivityLocked();
4610 }
4611 } else {
4612 r.appTimeTracker = null;
4613 }
4614 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
4615 // TODO: Probably not, because we don't want to resume voice on switching
4616 // back to this activity
4617 if (task.voiceInteractor != null) {
4618 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
4619 } else {
4620 finishRunningVoiceLocked();
4621
4622 if (mLastResumedActivity != null) {
4623 final IVoiceInteractionSession session;
4624
4625 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
4626 if (lastResumedActivityTask != null
4627 && lastResumedActivityTask.voiceSession != null) {
4628 session = lastResumedActivityTask.voiceSession;
4629 } else {
4630 session = mLastResumedActivity.voiceSession;
4631 }
4632
4633 if (session != null) {
4634 // We had been in a voice interaction session, but now focused has
4635 // move to something different. Just finish the session, we can't
4636 // return to it and retain the proper state and synchronization with
4637 // the voice interaction service.
4638 finishVoiceTask(session);
4639 }
4640 }
4641 }
4642
4643 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
4644 mAmInternal.sendForegroundProfileChanged(r.userId);
4645 }
4646 updateResumedAppTrace(r);
4647 mLastResumedActivity = r;
4648
4649 mWindowManager.setFocusedApp(r.appToken, true);
4650
4651 applyUpdateLockStateLocked(r);
4652 applyUpdateVrModeLocked(r);
4653
4654 EventLogTags.writeAmSetResumedActivity(
4655 r == null ? -1 : r.userId,
4656 r == null ? "NULL" : r.shortComponentName,
4657 reason);
4658 }
4659
4660 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
4661 synchronized (mGlobalLock) {
4662 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
4663 updateSleepIfNeededLocked();
4664 return token;
4665 }
4666 }
4667
4668 void updateSleepIfNeededLocked() {
4669 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
4670 final boolean wasSleeping = mSleeping;
4671 boolean updateOomAdj = false;
4672
4673 if (!shouldSleep) {
4674 // If wasSleeping is true, we need to wake up activity manager state from when
4675 // we started sleeping. In either case, we need to apply the sleep tokens, which
4676 // will wake up stacks or put them to sleep as appropriate.
4677 if (wasSleeping) {
4678 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07004679 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
4680 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004681 startTimeTrackingFocusedActivityLocked();
4682 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
4683 mStackSupervisor.comeOutOfSleepIfNeededLocked();
4684 }
4685 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
4686 if (wasSleeping) {
4687 updateOomAdj = true;
4688 }
4689 } else if (!mSleeping && shouldSleep) {
4690 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07004691 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
4692 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004693 if (mCurAppTimeTracker != null) {
4694 mCurAppTimeTracker.stop();
4695 }
4696 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
4697 mStackSupervisor.goingToSleepLocked();
4698 updateResumedAppTrace(null /* resumed */);
4699 updateOomAdj = true;
4700 }
4701 if (updateOomAdj) {
4702 mH.post(mAmInternal::updateOomAdj);
4703 }
4704 }
4705
4706 void updateOomAdj() {
4707 mH.post(mAmInternal::updateOomAdj);
4708 }
4709
Andrii Kulian52d255c2018-07-13 11:32:19 -07004710 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07004711 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07004712 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07004713 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
4714 mCurAppTimeTracker.start(resumedActivity.packageName);
4715 }
4716 }
4717
4718 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
4719 if (mTracedResumedActivity != null) {
4720 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
4721 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
4722 }
4723 if (resumed != null) {
4724 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
4725 constructResumedTraceName(resumed.packageName), 0);
4726 }
4727 mTracedResumedActivity = resumed;
4728 }
4729
4730 private String constructResumedTraceName(String packageName) {
4731 return "focused app: " + packageName;
4732 }
4733
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004734 /** Helper method that requests bounds from WM and applies them to stack. */
4735 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
4736 final Rect newStackBounds = new Rect();
4737 final ActivityStack stack = mStackSupervisor.getStack(stackId);
4738
4739 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
4740 if (stack == null) {
4741 final StringWriter writer = new StringWriter();
4742 final PrintWriter printWriter = new PrintWriter(writer);
4743 mStackSupervisor.dumpDisplays(printWriter);
4744 printWriter.flush();
4745
4746 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
4747 }
4748
4749 stack.getBoundsForNewConfiguration(newStackBounds);
4750 mStackSupervisor.resizeStackLocked(
4751 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
4752 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
4753 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
4754 }
4755
4756 /** Applies latest configuration and/or visibility updates if needed. */
4757 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
4758 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004759 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004760 // mainStack is null during startup.
4761 if (mainStack != null) {
4762 if (changes != 0 && starting == null) {
4763 // If the configuration changed, and the caller is not already
4764 // in the process of starting an activity, then find the top
4765 // activity to check if its configuration needs to change.
4766 starting = mainStack.topRunningActivityLocked();
4767 }
4768
4769 if (starting != null) {
4770 kept = starting.ensureActivityConfiguration(changes,
4771 false /* preserveWindow */);
4772 // And we need to make sure at this point that all other activities
4773 // are made visible with the correct configuration.
4774 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
4775 !PRESERVE_WINDOWS);
4776 }
4777 }
4778
4779 return kept;
4780 }
4781
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004782 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
4783 if (true || Build.IS_USER) {
4784 return;
4785 }
4786
4787 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4788 StrictMode.allowThreadDiskWrites();
4789 try {
4790 File tracesDir = new File("/data/anr");
4791 File tracesFile = null;
4792 try {
4793 tracesFile = File.createTempFile("app_slow", null, tracesDir);
4794
4795 StringBuilder sb = new StringBuilder();
4796 Time tobj = new Time();
4797 tobj.set(System.currentTimeMillis());
4798 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4799 sb.append(": ");
4800 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4801 sb.append(" since ");
4802 sb.append(msg);
4803 FileOutputStream fos = new FileOutputStream(tracesFile);
4804 fos.write(sb.toString().getBytes());
4805 if (app == null) {
4806 fos.write("\n*** No application process!".getBytes());
4807 }
4808 fos.close();
4809 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4810 } catch (IOException e) {
4811 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
4812 return;
4813 }
4814
4815 if (app != null && app.getPid() > 0) {
4816 ArrayList<Integer> firstPids = new ArrayList<Integer>();
4817 firstPids.add(app.getPid());
4818 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
4819 }
4820
4821 File lastTracesFile = null;
4822 File curTracesFile = null;
4823 for (int i=9; i>=0; i--) {
4824 String name = String.format(Locale.US, "slow%02d.txt", i);
4825 curTracesFile = new File(tracesDir, name);
4826 if (curTracesFile.exists()) {
4827 if (lastTracesFile != null) {
4828 curTracesFile.renameTo(lastTracesFile);
4829 } else {
4830 curTracesFile.delete();
4831 }
4832 }
4833 lastTracesFile = curTracesFile;
4834 }
4835 tracesFile.renameTo(curTracesFile);
4836 } finally {
4837 StrictMode.setThreadPolicy(oldPolicy);
4838 }
4839 }
4840
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004841 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004842 static final int REPORT_TIME_TRACKER_MSG = 1;
4843
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004844 public H(Looper looper) {
4845 super(looper, null, true);
4846 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004847
4848 @Override
4849 public void handleMessage(Message msg) {
4850 switch (msg.what) {
4851 case REPORT_TIME_TRACKER_MSG: {
4852 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
4853 tracker.deliverResult(mContext);
4854 } break;
4855 }
4856 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004857 }
4858
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004859 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004860 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861
4862 public UiHandler() {
4863 super(com.android.server.UiThread.get().getLooper(), null, true);
4864 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004865
4866 @Override
4867 public void handleMessage(Message msg) {
4868 switch (msg.what) {
4869 case DISMISS_DIALOG_UI_MSG: {
4870 final Dialog d = (Dialog) msg.obj;
4871 d.dismiss();
4872 break;
4873 }
4874 }
4875 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004876 }
4877
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004878 final class LocalService extends ActivityTaskManagerInternal {
4879 @Override
4880 public SleepToken acquireSleepToken(String tag, int displayId) {
4881 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004882 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004883 }
4884
4885 @Override
4886 public ComponentName getHomeActivityForUser(int userId) {
4887 synchronized (mGlobalLock) {
4888 ActivityRecord homeActivity = mStackSupervisor.getHomeActivityForUser(userId);
4889 return homeActivity == null ? null : homeActivity.realActivity;
4890 }
4891 }
4892
4893 @Override
4894 public void onLocalVoiceInteractionStarted(IBinder activity,
4895 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
4896 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004897 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004898 }
4899 }
4900
4901 @Override
4902 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
4903 synchronized (mGlobalLock) {
4904 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
4905 reasons, timestamp);
4906 }
4907 }
4908
4909 @Override
4910 public void notifyAppTransitionFinished() {
4911 synchronized (mGlobalLock) {
4912 mStackSupervisor.notifyAppTransitionDone();
4913 }
4914 }
4915
4916 @Override
4917 public void notifyAppTransitionCancelled() {
4918 synchronized (mGlobalLock) {
4919 mStackSupervisor.notifyAppTransitionDone();
4920 }
4921 }
4922
4923 @Override
4924 public List<IBinder> getTopVisibleActivities() {
4925 synchronized (mGlobalLock) {
4926 return mStackSupervisor.getTopVisibleActivities();
4927 }
4928 }
4929
4930 @Override
4931 public void notifyDockedStackMinimizedChanged(boolean minimized) {
4932 synchronized (mGlobalLock) {
4933 mStackSupervisor.setDockedStackMinimized(minimized);
4934 }
4935 }
4936
4937 @Override
4938 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
4939 Bundle bOptions) {
4940 Preconditions.checkNotNull(intents, "intents");
4941 final String[] resolvedTypes = new String[intents.length];
4942
4943 // UID of the package on user userId.
4944 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
4945 // packageUid may not be initialized.
4946 int packageUid = 0;
4947 final long ident = Binder.clearCallingIdentity();
4948
4949 try {
4950 for (int i = 0; i < intents.length; i++) {
4951 resolvedTypes[i] =
4952 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
4953 }
4954
4955 packageUid = AppGlobals.getPackageManager().getPackageUid(
4956 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
4957 } catch (RemoteException e) {
4958 // Shouldn't happen.
4959 } finally {
4960 Binder.restoreCallingIdentity(ident);
4961 }
4962
4963 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004964 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004965 packageUid, packageName,
4966 intents, resolvedTypes, null /* resultTo */,
4967 SafeActivityOptions.fromBundle(bOptions), userId,
4968 false /* validateIncomingUser */);
4969 }
4970 }
4971
4972 @Override
4973 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
4974 Intent intent, Bundle options, int userId) {
4975 return ActivityTaskManagerService.this.startActivityAsUser(
4976 caller, callerPacakge, intent,
4977 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
4978 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
4979 false /*validateIncomingUser*/);
4980 }
4981
4982 @Override
4983 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback) {
4984 synchronized (mGlobalLock) {
4985
4986 // We might change the visibilities here, so prepare an empty app transition which
4987 // might be overridden later if we actually change visibilities.
4988 final boolean wasTransitionSet =
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004989 mWindowManager.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004990 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004991 mWindowManager.prepareAppTransition(TRANSIT_NONE,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004992 false /* alwaysKeepCurrent */);
4993 }
4994 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
4995
4996 // If there was a transition set already we don't want to interfere with it as we
4997 // might be starting it too early.
4998 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004999 mWindowManager.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005000 }
5001 }
5002 if (callback != null) {
5003 callback.run();
5004 }
5005 }
5006
5007 @Override
5008 public void notifyKeyguardTrustedChanged() {
5009 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005010 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005011 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5012 }
5013 }
5014 }
5015
5016 /**
5017 * Called after virtual display Id is updated by
5018 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5019 * {@param vrVr2dDisplayId}.
5020 */
5021 @Override
5022 public void setVr2dDisplayId(int vr2dDisplayId) {
5023 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5024 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005025 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005026 }
5027 }
5028
5029 @Override
5030 public void setFocusedActivity(IBinder token) {
5031 synchronized (mGlobalLock) {
5032 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5033 if (r == null) {
5034 throw new IllegalArgumentException(
5035 "setFocusedActivity: No activity record matching token=" + token);
5036 }
5037 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
5038 r, "setFocusedActivity")) {
5039 mStackSupervisor.resumeFocusedStackTopActivityLocked();
5040 }
5041 }
5042 }
5043
5044 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005045 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005046 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005047 }
5048
5049 @Override
5050 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005051 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005052 }
5053
5054 @Override
5055 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005056 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005057 }
5058
5059 @Override
5060 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5061 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5062 }
5063
5064 @Override
5065 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005066 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005067 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005068
5069 @Override
5070 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5071 synchronized (mGlobalLock) {
5072 mActiveVoiceInteractionServiceComponent = component;
5073 }
5074 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005075
5076 @Override
5077 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5078 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5079 return;
5080 }
5081 synchronized (mGlobalLock) {
5082 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5083 if (types == null) {
5084 if (uid < 0) {
5085 return;
5086 }
5087 types = new ArrayMap<>();
5088 mAllowAppSwitchUids.put(userId, types);
5089 }
5090 if (uid < 0) {
5091 types.remove(type);
5092 } else {
5093 types.put(type, uid);
5094 }
5095 }
5096 }
5097
5098 @Override
5099 public void onUserStopped(int userId) {
5100 synchronized (mGlobalLock) {
5101 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5102 mAllowAppSwitchUids.remove(userId);
5103 }
5104 }
5105
5106 @Override
5107 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5108 synchronized (mGlobalLock) {
5109 return ActivityTaskManagerService.this.isGetTasksAllowed(
5110 caller, callingPid, callingUid);
5111 }
5112 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005113
5114 @Override
5115 public void onProcessAdded(WindowProcessController proc) {
5116 synchronized (mGlobalLock) {
5117 mProcessNames.put(proc.mName, proc.mUid, proc);
5118 }
5119 }
5120
5121 @Override
5122 public void onProcessRemoved(String name, int uid) {
5123 synchronized (mGlobalLock) {
5124 mProcessNames.remove(name, uid);
5125 }
5126 }
5127
5128 @Override
5129 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5130 synchronized (mGlobalLock) {
5131 if (proc == mHomeProcess) {
5132 mHomeProcess = null;
5133 }
5134 if (proc == mPreviousProcess) {
5135 mPreviousProcess = null;
5136 }
5137 }
5138 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005139
5140 @Override
5141 public int getTopProcessState() {
5142 synchronized (mGlobalLock) {
5143 return mTopProcessState;
5144 }
5145 }
5146
5147 @Override
5148 public boolean isSleeping() {
5149 synchronized (mGlobalLock) {
5150 return isSleepingLocked();
5151 }
5152 }
5153
5154 @Override
5155 public boolean isShuttingDown() {
5156 synchronized (mGlobalLock) {
5157 return mShuttingDown;
5158 }
5159 }
5160
5161 @Override
5162 public boolean shuttingDown(boolean booted, int timeout) {
5163 synchronized (mGlobalLock) {
5164 mShuttingDown = true;
5165 mStackSupervisor.prepareForShutdownLocked();
5166 updateEventDispatchingLocked(booted);
5167 return mStackSupervisor.shutdownLocked(timeout);
5168 }
5169 }
5170
5171 @Override
5172 public void enableScreenAfterBoot(boolean booted) {
5173 synchronized (mGlobalLock) {
5174 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5175 SystemClock.uptimeMillis());
5176 mWindowManager.enableScreenAfterBoot();
5177 updateEventDispatchingLocked(booted);
5178 }
5179 }
5180
5181 @Override
5182 public boolean showStrictModeViolationDialog() {
5183 synchronized (mGlobalLock) {
5184 return mShowDialogs && !mSleeping && !mShuttingDown;
5185 }
5186 }
5187
5188 @Override
5189 public void showSystemReadyErrorDialogsIfNeeded() {
5190 synchronized (mGlobalLock) {
5191 try {
5192 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5193 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5194 + " data partition or your device will be unstable.");
5195 mUiHandler.post(() -> {
5196 if (mShowDialogs) {
5197 AlertDialog d = new BaseErrorDialog(mUiContext);
5198 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5199 d.setCancelable(false);
5200 d.setTitle(mUiContext.getText(R.string.android_system_label));
5201 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5202 d.setButton(DialogInterface.BUTTON_POSITIVE,
5203 mUiContext.getText(R.string.ok),
5204 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5205 d.show();
5206 }
5207 });
5208 }
5209 } catch (RemoteException e) {
5210 }
5211
5212 if (!Build.isBuildConsistent()) {
5213 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5214 mUiHandler.post(() -> {
5215 if (mShowDialogs) {
5216 AlertDialog d = new BaseErrorDialog(mUiContext);
5217 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5218 d.setCancelable(false);
5219 d.setTitle(mUiContext.getText(R.string.android_system_label));
5220 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5221 d.setButton(DialogInterface.BUTTON_POSITIVE,
5222 mUiContext.getText(R.string.ok),
5223 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5224 d.show();
5225 }
5226 });
5227 }
5228 }
5229 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005230 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07005231}