blob: 10e0182e62eb1ca1c6defd41473e4927afaa971d [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
2775 public int createStackOnDisplay(int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "createStackOnDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 synchronized (mGlobalLock) {
2778 final ActivityDisplay display =
2779 mStackSupervisor.getActivityDisplayOrCreateLocked(displayId);
2780 if (display == null) {
2781 return INVALID_STACK_ID;
2782 }
2783 // TODO(multi-display): Have the caller pass in the windowing mode and activity type.
2784 final ActivityStack stack = display.createStack(
2785 WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD,
2786 ON_TOP);
2787 return (stack != null) ? stack.mStackId : INVALID_STACK_ID;
2788 }
2789 }
2790
2791 @Override
2792 public void exitFreeformMode(IBinder token) {
2793 synchronized (mGlobalLock) {
2794 long ident = Binder.clearCallingIdentity();
2795 try {
2796 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2797 if (r == null) {
2798 throw new IllegalArgumentException(
2799 "exitFreeformMode: No activity record matching token=" + token);
2800 }
2801
2802 final ActivityStack stack = r.getStack();
2803 if (stack == null || !stack.inFreeformWindowingMode()) {
2804 throw new IllegalStateException(
2805 "exitFreeformMode: You can only go fullscreen from freeform.");
2806 }
2807
2808 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
2809 } finally {
2810 Binder.restoreCallingIdentity(ident);
2811 }
2812 }
2813 }
2814
2815 /** Sets the task stack listener that gets callbacks when a task stack changes. */
2816 @Override
2817 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002818 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002820 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822
2823 /** Unregister a task stack listener so that it stops receiving callbacks. */
2824 @Override
2825 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002826 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002828 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 }
2830
2831 private void reportCurKeyguardUsageEventLocked(boolean keyguardShowing) {
2832 mAm.reportGlobalUsageEventLocked(keyguardShowing
2833 ? UsageEvents.Event.KEYGUARD_SHOWN
2834 : UsageEvents.Event.KEYGUARD_HIDDEN);
2835 }
2836
2837 @Override
2838 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
2839 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
2840 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
2841 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
2842 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
2843 }
2844
2845 @Override
2846 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
2847 IBinder activityToken, int flags) {
2848 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
2849 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
2850 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
2851 }
2852
2853 @Override
2854 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
2855 Bundle args) {
2856 return enqueueAssistContext(requestType, intent, hint, null, null, null,
2857 true /* focused */, true /* newSessionId */, userHandle, args,
2858 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
2859 }
2860
2861 @Override
2862 public Bundle getAssistContextExtras(int requestType) {
2863 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
2864 null, null, true /* focused */, true /* newSessionId */,
2865 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
2866 if (pae == null) {
2867 return null;
2868 }
2869 synchronized (pae) {
2870 while (!pae.haveResult) {
2871 try {
2872 pae.wait();
2873 } catch (InterruptedException e) {
2874 }
2875 }
2876 }
2877 synchronized (mGlobalLock) {
2878 buildAssistBundleLocked(pae, pae.result);
2879 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002880 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 }
2882 return pae.extras;
2883 }
2884
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002885 /**
2886 * Binder IPC calls go through the public entry point.
2887 * This can be called with or without the global lock held.
2888 */
2889 private static int checkCallingPermission(String permission) {
2890 return checkPermission(
2891 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
2892 }
2893
2894 /** This can be called with or without the global lock held. */
2895 void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
2896 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
2897 mAmInternal.enforceCallingPermission(permission, func);
2898 }
2899 }
2900
2901 @VisibleForTesting
2902 int checkGetTasksPermission(String permission, int pid, int uid) {
2903 return checkPermission(permission, pid, uid);
2904 }
2905
2906 static int checkPermission(String permission, int pid, int uid) {
2907 if (permission == null) {
2908 return PackageManager.PERMISSION_DENIED;
2909 }
2910 return checkComponentPermission(permission, pid, uid, -1, true);
2911 }
2912
2913 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
2914 if (getRecentTasks().isCallerRecents(callingUid)) {
2915 // Always allow the recents component to get tasks
2916 return true;
2917 }
2918
2919 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
2920 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2921 if (!allowed) {
2922 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
2923 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
2924 // Temporary compatibility: some existing apps on the system image may
2925 // still be requesting the old permission and not switched to the new
2926 // one; if so, we'll still allow them full access. This means we need
2927 // to see if they are holding the old permission and are a system app.
2928 try {
2929 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
2930 allowed = true;
2931 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2932 + " is using old GET_TASKS but privileged; allowing");
2933 }
2934 } catch (RemoteException e) {
2935 }
2936 }
2937 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2938 + " does not hold REAL_GET_TASKS; limiting output");
2939 }
2940 return allowed;
2941 }
2942
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
2944 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
2945 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
2946 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002947 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 "enqueueAssistContext()");
2949
2950 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002951 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 if (activity == null) {
2953 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
2954 return null;
2955 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002956 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
2958 return null;
2959 }
2960 if (focused) {
2961 if (activityToken != null) {
2962 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
2963 if (activity != caller) {
2964 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
2965 + " is not current top " + activity);
2966 return null;
2967 }
2968 }
2969 } else {
2970 activity = ActivityRecord.forTokenLocked(activityToken);
2971 if (activity == null) {
2972 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
2973 + " couldn't be found");
2974 return null;
2975 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002976 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
2978 return null;
2979 }
2980 }
2981
2982 PendingAssistExtras pae;
2983 Bundle extras = new Bundle();
2984 if (args != null) {
2985 extras.putAll(args);
2986 }
2987 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002988 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002989
2990 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
2991 userHandle);
2992 pae.isHome = activity.isActivityTypeHome();
2993
2994 // Increment the sessionId if necessary
2995 if (newSessionId) {
2996 mViSessionId++;
2997 }
2998 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002999 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3000 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003002 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 } catch (RemoteException e) {
3004 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3005 return null;
3006 }
3007 return pae;
3008 }
3009 }
3010
3011 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3012 if (result != null) {
3013 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3014 }
3015 if (pae.hint != null) {
3016 pae.extras.putBoolean(pae.hint, true);
3017 }
3018 }
3019
3020 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3021 IAssistDataReceiver receiver;
3022 synchronized (mGlobalLock) {
3023 mPendingAssistExtras.remove(pae);
3024 receiver = pae.receiver;
3025 }
3026 if (receiver != null) {
3027 // Caller wants result sent back to them.
3028 Bundle sendBundle = new Bundle();
3029 // At least return the receiver extras
3030 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3031 try {
3032 pae.receiver.onHandleAssistData(sendBundle);
3033 } catch (RemoteException e) {
3034 }
3035 }
3036 }
3037
3038 public class PendingAssistExtras extends Binder implements Runnable {
3039 public final ActivityRecord activity;
3040 public boolean isHome;
3041 public final Bundle extras;
3042 public final Intent intent;
3043 public final String hint;
3044 public final IAssistDataReceiver receiver;
3045 public final int userHandle;
3046 public boolean haveResult = false;
3047 public Bundle result = null;
3048 public AssistStructure structure = null;
3049 public AssistContent content = null;
3050 public Bundle receiverExtras;
3051
3052 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3053 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3054 int _userHandle) {
3055 activity = _activity;
3056 extras = _extras;
3057 intent = _intent;
3058 hint = _hint;
3059 receiver = _receiver;
3060 receiverExtras = _receiverExtras;
3061 userHandle = _userHandle;
3062 }
3063
3064 @Override
3065 public void run() {
3066 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3067 synchronized (this) {
3068 haveResult = true;
3069 notifyAll();
3070 }
3071 pendingAssistExtrasTimedOut(this);
3072 }
3073 }
3074
3075 @Override
3076 public boolean isAssistDataAllowedOnCurrentActivity() {
3077 int userId;
3078 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003079 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3081 return false;
3082 }
3083
3084 final ActivityRecord activity = focusedStack.getTopActivity();
3085 if (activity == null) {
3086 return false;
3087 }
3088 userId = activity.userId;
3089 }
3090 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3091 }
3092
3093 @Override
3094 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3095 long ident = Binder.clearCallingIdentity();
3096 try {
3097 synchronized (mGlobalLock) {
3098 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003099 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100 if (top != caller) {
3101 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3102 + " is not current top " + top);
3103 return false;
3104 }
3105 if (!top.nowVisible) {
3106 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3107 + " is not visible");
3108 return false;
3109 }
3110 }
3111 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3112 token);
3113 } finally {
3114 Binder.restoreCallingIdentity(ident);
3115 }
3116 }
3117
3118 @Override
3119 public boolean isRootVoiceInteraction(IBinder token) {
3120 synchronized (mGlobalLock) {
3121 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3122 if (r == null) {
3123 return false;
3124 }
3125 return r.rootVoiceInteraction;
3126 }
3127 }
3128
Wale Ogunwalef6733932018-06-27 05:14:34 -07003129 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3130 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3131 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3132 if (activityToCallback == null) return;
3133 activityToCallback.setVoiceSessionLocked(voiceSession);
3134
3135 // Inform the activity
3136 try {
3137 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3138 voiceInteractor);
3139 long token = Binder.clearCallingIdentity();
3140 try {
3141 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3142 } finally {
3143 Binder.restoreCallingIdentity(token);
3144 }
3145 // TODO: VI Should we cache the activity so that it's easier to find later
3146 // rather than scan through all the stacks and activities?
3147 } catch (RemoteException re) {
3148 activityToCallback.clearVoiceSessionLocked();
3149 // TODO: VI Should this terminate the voice session?
3150 }
3151 }
3152
3153 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3154 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3155 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3156 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3157 boolean wasRunningVoice = mRunningVoice != null;
3158 mRunningVoice = session;
3159 if (!wasRunningVoice) {
3160 mVoiceWakeLock.acquire();
3161 updateSleepIfNeededLocked();
3162 }
3163 }
3164 }
3165
3166 void finishRunningVoiceLocked() {
3167 if (mRunningVoice != null) {
3168 mRunningVoice = null;
3169 mVoiceWakeLock.release();
3170 updateSleepIfNeededLocked();
3171 }
3172 }
3173
3174 @Override
3175 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3176 synchronized (mGlobalLock) {
3177 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3178 if (keepAwake) {
3179 mVoiceWakeLock.acquire();
3180 } else {
3181 mVoiceWakeLock.release();
3182 }
3183 }
3184 }
3185 }
3186
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 @Override
3188 public ComponentName getActivityClassForToken(IBinder token) {
3189 synchronized (mGlobalLock) {
3190 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3191 if (r == null) {
3192 return null;
3193 }
3194 return r.intent.getComponent();
3195 }
3196 }
3197
3198 @Override
3199 public String getPackageForToken(IBinder token) {
3200 synchronized (mGlobalLock) {
3201 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3202 if (r == null) {
3203 return null;
3204 }
3205 return r.packageName;
3206 }
3207 }
3208
3209 @Override
3210 public void showLockTaskEscapeMessage(IBinder token) {
3211 synchronized (mGlobalLock) {
3212 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3213 if (r == null) {
3214 return;
3215 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003216 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 }
3218 }
3219
3220 @Override
3221 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003222 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003223 final long token = Binder.clearCallingIdentity();
3224 try {
3225 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003226 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228 } finally {
3229 Binder.restoreCallingIdentity(token);
3230 }
3231 }
3232
3233 /**
3234 * Try to place task to provided position. The final position might be different depending on
3235 * current user and stacks state. The task will be moved to target stack if it's currently in
3236 * different stack.
3237 */
3238 @Override
3239 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003240 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 synchronized (mGlobalLock) {
3242 long ident = Binder.clearCallingIdentity();
3243 try {
3244 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3245 + taskId + " in stackId=" + stackId + " at position=" + position);
3246 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3247 if (task == null) {
3248 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3249 + taskId);
3250 }
3251
3252 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3253
3254 if (stack == null) {
3255 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3256 + stackId);
3257 }
3258 if (!stack.isActivityTypeStandardOrUndefined()) {
3259 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3260 + " the position of task " + taskId + " in/to non-standard stack");
3261 }
3262
3263 // TODO: Have the callers of this API call a separate reparent method if that is
3264 // what they intended to do vs. having this method also do reparenting.
3265 if (task.getStack() == stack) {
3266 // Change position in current stack.
3267 stack.positionChildAt(task, position);
3268 } else {
3269 // Reparent to new stack.
3270 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3271 !DEFER_RESUME, "positionTaskInStack");
3272 }
3273 } finally {
3274 Binder.restoreCallingIdentity(ident);
3275 }
3276 }
3277 }
3278
3279 @Override
3280 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3281 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3282 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3283 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3284 synchronized (mGlobalLock) {
3285 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3286 if (record == null) {
3287 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3288 + "found for: " + token);
3289 }
3290 record.setSizeConfigurations(horizontalSizeConfiguration,
3291 verticalSizeConfigurations, smallestSizeConfigurations);
3292 }
3293 }
3294
3295 /**
3296 * Dismisses split-screen multi-window mode.
3297 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3298 */
3299 @Override
3300 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3303 final long ident = Binder.clearCallingIdentity();
3304 try {
3305 synchronized (mGlobalLock) {
3306 final ActivityStack stack =
3307 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3308 if (stack == null) {
3309 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3310 return;
3311 }
3312
3313 if (toTop) {
3314 // Caller wants the current split-screen primary stack to be the top stack after
3315 // it goes fullscreen, so move it to the front.
3316 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003317 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 // In this case the current split-screen primary stack shouldn't be the top
3319 // stack after it goes fullscreen, but it current has focus, so we move the
3320 // focus to the top-most split-screen secondary stack next to it.
3321 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3322 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3323 if (otherStack != null) {
3324 otherStack.moveToFront("dismissSplitScreenMode_other");
3325 }
3326 }
3327
3328 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3329 }
3330 } finally {
3331 Binder.restoreCallingIdentity(ident);
3332 }
3333 }
3334
3335 /**
3336 * Dismisses Pip
3337 * @param animate True if the dismissal should be animated.
3338 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3339 * default animation duration should be used.
3340 */
3341 @Override
3342 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003343 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 final long ident = Binder.clearCallingIdentity();
3345 try {
3346 synchronized (mGlobalLock) {
3347 final PinnedActivityStack stack =
3348 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3349 if (stack == null) {
3350 Slog.w(TAG, "dismissPip: pinned stack not found.");
3351 return;
3352 }
3353 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3354 throw new IllegalArgumentException("Stack: " + stack
3355 + " doesn't support animated resize.");
3356 }
3357 if (animate) {
3358 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3359 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3360 } else {
3361 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3362 }
3363 }
3364 } finally {
3365 Binder.restoreCallingIdentity(ident);
3366 }
3367 }
3368
3369 @Override
3370 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003371 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 synchronized (mGlobalLock) {
3373 mSuppressResizeConfigChanges = suppress;
3374 }
3375 }
3376
3377 /**
3378 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3379 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3380 * activity and clearing the task at the same time.
3381 */
3382 @Override
3383 // TODO: API should just be about changing windowing modes...
3384 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003385 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 "moveTasksToFullscreenStack()");
3387 synchronized (mGlobalLock) {
3388 final long origId = Binder.clearCallingIdentity();
3389 try {
3390 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3391 if (stack != null){
3392 if (!stack.isActivityTypeStandardOrUndefined()) {
3393 throw new IllegalArgumentException(
3394 "You can't move tasks from non-standard stacks.");
3395 }
3396 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3397 }
3398 } finally {
3399 Binder.restoreCallingIdentity(origId);
3400 }
3401 }
3402 }
3403
3404 /**
3405 * Moves the top activity in the input stackId to the pinned stack.
3406 *
3407 * @param stackId Id of stack to move the top activity to pinned stack.
3408 * @param bounds Bounds to use for pinned stack.
3409 *
3410 * @return True if the top activity of the input stack was successfully moved to the pinned
3411 * stack.
3412 */
3413 @Override
3414 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 "moveTopActivityToPinnedStack()");
3417 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003418 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3420 + "Device doesn't support picture-in-picture mode");
3421 }
3422
3423 long ident = Binder.clearCallingIdentity();
3424 try {
3425 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3426 } finally {
3427 Binder.restoreCallingIdentity(ident);
3428 }
3429 }
3430 }
3431
3432 @Override
3433 public boolean isInMultiWindowMode(IBinder token) {
3434 final long origId = Binder.clearCallingIdentity();
3435 try {
3436 synchronized (mGlobalLock) {
3437 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3438 if (r == null) {
3439 return false;
3440 }
3441 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3442 return r.inMultiWindowMode();
3443 }
3444 } finally {
3445 Binder.restoreCallingIdentity(origId);
3446 }
3447 }
3448
3449 @Override
3450 public boolean isInPictureInPictureMode(IBinder token) {
3451 final long origId = Binder.clearCallingIdentity();
3452 try {
3453 synchronized (mGlobalLock) {
3454 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3455 }
3456 } finally {
3457 Binder.restoreCallingIdentity(origId);
3458 }
3459 }
3460
3461 private boolean isInPictureInPictureMode(ActivityRecord r) {
3462 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3463 || r.getStack().isInStackLocked(r) == null) {
3464 return false;
3465 }
3466
3467 // If we are animating to fullscreen then we have already dispatched the PIP mode
3468 // changed, so we should reflect that check here as well.
3469 final PinnedActivityStack stack = r.getStack();
3470 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3471 return !windowController.isAnimatingBoundsToFullscreen();
3472 }
3473
3474 @Override
3475 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3476 final long origId = Binder.clearCallingIdentity();
3477 try {
3478 synchronized (mGlobalLock) {
3479 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3480 "enterPictureInPictureMode", token, params);
3481
3482 // If the activity is already in picture in picture mode, then just return early
3483 if (isInPictureInPictureMode(r)) {
3484 return true;
3485 }
3486
3487 // Activity supports picture-in-picture, now check that we can enter PiP at this
3488 // point, if it is
3489 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3490 false /* beforeStopping */)) {
3491 return false;
3492 }
3493
3494 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003495 synchronized (mGlobalLock) {
3496 // Only update the saved args from the args that are set
3497 r.pictureInPictureArgs.copyOnlySet(params);
3498 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3499 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3500 // Adjust the source bounds by the insets for the transition down
3501 final Rect sourceBounds = new Rect(
3502 r.pictureInPictureArgs.getSourceRectHint());
3503 mStackSupervisor.moveActivityToPinnedStackLocked(
3504 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3505 final PinnedActivityStack stack = r.getStack();
3506 stack.setPictureInPictureAspectRatio(aspectRatio);
3507 stack.setPictureInPictureActions(actions);
3508 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3509 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3510 logPictureInPictureArgs(params);
3511 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 };
3513
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003514 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 // If the keyguard is showing or occluded, then try and dismiss it before
3516 // entering picture-in-picture (this will prompt the user to authenticate if the
3517 // device is currently locked).
3518 dismissKeyguard(token, new KeyguardDismissCallback() {
3519 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003520 public void onDismissSucceeded() {
3521 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 }
3523 }, null /* message */);
3524 } else {
3525 // Enter picture in picture immediately otherwise
3526 enterPipRunnable.run();
3527 }
3528 return true;
3529 }
3530 } finally {
3531 Binder.restoreCallingIdentity(origId);
3532 }
3533 }
3534
3535 @Override
3536 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3537 final long origId = Binder.clearCallingIdentity();
3538 try {
3539 synchronized (mGlobalLock) {
3540 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3541 "setPictureInPictureParams", token, params);
3542
3543 // Only update the saved args from the args that are set
3544 r.pictureInPictureArgs.copyOnlySet(params);
3545 if (r.inPinnedWindowingMode()) {
3546 // If the activity is already in picture-in-picture, update the pinned stack now
3547 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3548 // be used the next time the activity enters PiP
3549 final PinnedActivityStack stack = r.getStack();
3550 if (!stack.isAnimatingBoundsToFullscreen()) {
3551 stack.setPictureInPictureAspectRatio(
3552 r.pictureInPictureArgs.getAspectRatio());
3553 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3554 }
3555 }
3556 logPictureInPictureArgs(params);
3557 }
3558 } finally {
3559 Binder.restoreCallingIdentity(origId);
3560 }
3561 }
3562
3563 @Override
3564 public int getMaxNumPictureInPictureActions(IBinder token) {
3565 // Currently, this is a static constant, but later, we may change this to be dependent on
3566 // the context of the activity
3567 return 3;
3568 }
3569
3570 private void logPictureInPictureArgs(PictureInPictureParams params) {
3571 if (params.hasSetActions()) {
3572 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3573 params.getActions().size());
3574 }
3575 if (params.hasSetAspectRatio()) {
3576 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3577 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3578 MetricsLogger.action(lm);
3579 }
3580 }
3581
3582 /**
3583 * Checks the state of the system and the activity associated with the given {@param token} to
3584 * verify that picture-in-picture is supported for that activity.
3585 *
3586 * @return the activity record for the given {@param token} if all the checks pass.
3587 */
3588 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3589 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 throw new IllegalStateException(caller
3592 + ": Device doesn't support picture-in-picture mode.");
3593 }
3594
3595 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3596 if (r == null) {
3597 throw new IllegalStateException(caller
3598 + ": Can't find activity for token=" + token);
3599 }
3600
3601 if (!r.supportsPictureInPicture()) {
3602 throw new IllegalStateException(caller
3603 + ": Current activity does not support picture-in-picture.");
3604 }
3605
3606 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003607 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 params.getAspectRatio())) {
3609 final float minAspectRatio = mContext.getResources().getFloat(
3610 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3611 final float maxAspectRatio = mContext.getResources().getFloat(
3612 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3613 throw new IllegalArgumentException(String.format(caller
3614 + ": Aspect ratio is too extreme (must be between %f and %f).",
3615 minAspectRatio, maxAspectRatio));
3616 }
3617
3618 // Truncate the number of actions if necessary
3619 params.truncateActions(getMaxNumPictureInPictureActions(token));
3620
3621 return r;
3622 }
3623
3624 @Override
3625 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003626 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003627 synchronized (mGlobalLock) {
3628 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3629 if (r == null) {
3630 throw new IllegalArgumentException("Activity does not exist; token="
3631 + activityToken);
3632 }
3633 return r.getUriPermissionsLocked().getExternalTokenLocked();
3634 }
3635 }
3636
3637 @Override
3638 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3639 Rect tempDockedTaskInsetBounds,
3640 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003641 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 long ident = Binder.clearCallingIdentity();
3643 try {
3644 synchronized (mGlobalLock) {
3645 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3646 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3647 PRESERVE_WINDOWS);
3648 }
3649 } finally {
3650 Binder.restoreCallingIdentity(ident);
3651 }
3652 }
3653
3654 @Override
3655 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003656 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003657 final long ident = Binder.clearCallingIdentity();
3658 try {
3659 synchronized (mGlobalLock) {
3660 mStackSupervisor.setSplitScreenResizing(resizing);
3661 }
3662 } finally {
3663 Binder.restoreCallingIdentity(ident);
3664 }
3665 }
3666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003667 /**
3668 * Check that we have the features required for VR-related API calls, and throw an exception if
3669 * not.
3670 */
3671 void enforceSystemHasVrFeature() {
3672 if (!mContext.getPackageManager().hasSystemFeature(
3673 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3674 throw new UnsupportedOperationException("VR mode not supported on this device!");
3675 }
3676 }
3677
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003678 @Override
3679 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003680 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681
3682 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3683
3684 ActivityRecord r;
3685 synchronized (mGlobalLock) {
3686 r = ActivityRecord.isInStackLocked(token);
3687 }
3688
3689 if (r == null) {
3690 throw new IllegalArgumentException();
3691 }
3692
3693 int err;
3694 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3695 VrManagerInternal.NO_ERROR) {
3696 return err;
3697 }
3698
3699 // Clear the binder calling uid since this path may call moveToTask().
3700 final long callingId = Binder.clearCallingIdentity();
3701 try {
3702 synchronized (mGlobalLock) {
3703 r.requestedVrComponent = (enabled) ? packageName : null;
3704
3705 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003706 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003707 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 }
3709 return 0;
3710 }
3711 } finally {
3712 Binder.restoreCallingIdentity(callingId);
3713 }
3714 }
3715
3716 @Override
3717 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3718 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3719 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003720 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3722 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3723 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003724 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003725 || activity.voiceSession != null) {
3726 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3727 return;
3728 }
3729 if (activity.pendingVoiceInteractionStart) {
3730 Slog.w(TAG, "Pending start of voice interaction already.");
3731 return;
3732 }
3733 activity.pendingVoiceInteractionStart = true;
3734 }
3735 LocalServices.getService(VoiceInteractionManagerInternal.class)
3736 .startLocalVoiceInteraction(callingActivity, options);
3737 }
3738
3739 @Override
3740 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3741 LocalServices.getService(VoiceInteractionManagerInternal.class)
3742 .stopLocalVoiceInteraction(callingActivity);
3743 }
3744
3745 @Override
3746 public boolean supportsLocalVoiceInteraction() {
3747 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3748 .supportsLocalVoiceInteraction();
3749 }
3750
3751 /** Notifies all listeners when the pinned stack animation starts. */
3752 @Override
3753 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003754 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 }
3756
3757 /** Notifies all listeners when the pinned stack animation ends. */
3758 @Override
3759 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003760 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003761 }
3762
3763 @Override
3764 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003765 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003766 final long ident = Binder.clearCallingIdentity();
3767 try {
3768 synchronized (mGlobalLock) {
3769 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3770 }
3771 } finally {
3772 Binder.restoreCallingIdentity(ident);
3773 }
3774 }
3775
3776 @Override
3777 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003778 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003779
3780 synchronized (mGlobalLock) {
3781 // Check if display is initialized in AM.
3782 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3783 // Call might come when display is not yet added or has already been removed.
3784 if (DEBUG_CONFIGURATION) {
3785 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
3786 + displayId);
3787 }
3788 return false;
3789 }
3790
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003791 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003793 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 }
3795
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003796 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003797 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003798 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003799 }
3800
3801 final long origId = Binder.clearCallingIdentity();
3802 try {
3803 if (values != null) {
3804 Settings.System.clearConfiguration(values);
3805 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003806 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003807 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
3808 return mTmpUpdateConfigurationResult.changes != 0;
3809 } finally {
3810 Binder.restoreCallingIdentity(origId);
3811 }
3812 }
3813 }
3814
3815 @Override
3816 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003817 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818
3819 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003820 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003822 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 }
3824
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003825 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003826 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003827 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 }
3829
3830 final long origId = Binder.clearCallingIdentity();
3831 try {
3832 if (values != null) {
3833 Settings.System.clearConfiguration(values);
3834 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003835 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 UserHandle.USER_NULL, false /* deferResume */,
3837 mTmpUpdateConfigurationResult);
3838 return mTmpUpdateConfigurationResult.changes != 0;
3839 } finally {
3840 Binder.restoreCallingIdentity(origId);
3841 }
3842 }
3843 }
3844
3845 @Override
3846 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
3847 CharSequence message) {
3848 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003849 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
3851 }
3852 final long callingId = Binder.clearCallingIdentity();
3853 try {
3854 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003855 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003856 }
3857 } finally {
3858 Binder.restoreCallingIdentity(callingId);
3859 }
3860 }
3861
3862 @Override
3863 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003864 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003865 "cancelTaskWindowTransition()");
3866 final long ident = Binder.clearCallingIdentity();
3867 try {
3868 synchronized (mGlobalLock) {
3869 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
3870 MATCH_TASK_IN_STACKS_ONLY);
3871 if (task == null) {
3872 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
3873 return;
3874 }
3875 task.cancelWindowTransition();
3876 }
3877 } finally {
3878 Binder.restoreCallingIdentity(ident);
3879 }
3880 }
3881
3882 @Override
3883 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003884 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 final long ident = Binder.clearCallingIdentity();
3886 try {
3887 final TaskRecord task;
3888 synchronized (mGlobalLock) {
3889 task = mStackSupervisor.anyTaskForIdLocked(taskId,
3890 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3891 if (task == null) {
3892 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
3893 return null;
3894 }
3895 }
3896 // Don't call this while holding the lock as this operation might hit the disk.
3897 return task.getSnapshot(reducedResolution);
3898 } finally {
3899 Binder.restoreCallingIdentity(ident);
3900 }
3901 }
3902
3903 @Override
3904 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
3905 synchronized (mGlobalLock) {
3906 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3907 if (r == null) {
3908 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
3909 + token);
3910 return;
3911 }
3912 final long origId = Binder.clearCallingIdentity();
3913 try {
3914 r.setDisablePreviewScreenshots(disable);
3915 } finally {
3916 Binder.restoreCallingIdentity(origId);
3917 }
3918 }
3919 }
3920
3921 /** Return the user id of the last resumed activity. */
3922 @Override
3923 public @UserIdInt
3924 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003925 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003926 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
3927 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07003928 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003929 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003931 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 }
3933 }
3934
3935 @Override
3936 public void updateLockTaskFeatures(int userId, int flags) {
3937 final int callingUid = Binder.getCallingUid();
3938 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003939 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 "updateLockTaskFeatures()");
3941 }
3942 synchronized (mGlobalLock) {
3943 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
3944 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003945 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 }
3947 }
3948
3949 @Override
3950 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
3951 synchronized (mGlobalLock) {
3952 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3953 if (r == null) {
3954 return;
3955 }
3956 final long origId = Binder.clearCallingIdentity();
3957 try {
3958 r.setShowWhenLocked(showWhenLocked);
3959 } finally {
3960 Binder.restoreCallingIdentity(origId);
3961 }
3962 }
3963 }
3964
3965 @Override
3966 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
3967 synchronized (mGlobalLock) {
3968 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3969 if (r == null) {
3970 return;
3971 }
3972 final long origId = Binder.clearCallingIdentity();
3973 try {
3974 r.setTurnScreenOn(turnScreenOn);
3975 } finally {
3976 Binder.restoreCallingIdentity(origId);
3977 }
3978 }
3979 }
3980
3981 @Override
3982 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003983 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 "registerRemoteAnimations");
3985 definition.setCallingPid(Binder.getCallingPid());
3986 synchronized (mGlobalLock) {
3987 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3988 if (r == null) {
3989 return;
3990 }
3991 final long origId = Binder.clearCallingIdentity();
3992 try {
3993 r.registerRemoteAnimations(definition);
3994 } finally {
3995 Binder.restoreCallingIdentity(origId);
3996 }
3997 }
3998 }
3999
4000 @Override
4001 public void registerRemoteAnimationForNextActivityStart(String packageName,
4002 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004003 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004004 "registerRemoteAnimationForNextActivityStart");
4005 adapter.setCallingPid(Binder.getCallingPid());
4006 synchronized (mGlobalLock) {
4007 final long origId = Binder.clearCallingIdentity();
4008 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004009 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 packageName, adapter);
4011 } finally {
4012 Binder.restoreCallingIdentity(origId);
4013 }
4014 }
4015 }
4016
4017 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4018 @Override
4019 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4020 synchronized (mGlobalLock) {
4021 final long origId = Binder.clearCallingIdentity();
4022 try {
4023 mAm.mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4024 } finally {
4025 Binder.restoreCallingIdentity(origId);
4026 }
4027 }
4028 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004029
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004030 @Override
4031 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004033 synchronized (mGlobalLock) {
4034 synchronized (mAm.mPidsSelfLocked) {
4035 final int pid = Binder.getCallingPid();
4036 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004037 mVrController.setVrThreadLocked(tid, pid, proc.getWindowProcessController());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004038 }
4039 }
4040 }
4041
4042 @Override
4043 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004044 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004045 != PERMISSION_GRANTED) {
4046 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4047 + Binder.getCallingPid()
4048 + ", uid=" + Binder.getCallingUid()
4049 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4050 Slog.w(TAG, msg);
4051 throw new SecurityException(msg);
4052 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004053 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004054 synchronized (mGlobalLock) {
4055 synchronized (mAm.mPidsSelfLocked) {
4056 final int pid = Binder.getCallingPid();
4057 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
4058 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4059 }
4060 }
4061 }
4062
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004063 @Override
4064 public void stopAppSwitches() {
4065 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4066 synchronized (mGlobalLock) {
4067 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4068 mDidAppSwitch = false;
4069 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4070 }
4071 }
4072
4073 @Override
4074 public void resumeAppSwitches() {
4075 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4076 synchronized (mGlobalLock) {
4077 // Note that we don't execute any pending app switches... we will
4078 // let those wait until either the timeout, or the next start
4079 // activity request.
4080 mAppSwitchesAllowedTime = 0;
4081 }
4082 }
4083
4084 void onStartActivitySetDidAppSwitch() {
4085 if (mDidAppSwitch) {
4086 // This is the second allowed switch since we stopped switches, so now just generally
4087 // allow switches. Use case:
4088 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4089 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4090 // anyone to switch again).
4091 mAppSwitchesAllowedTime = 0;
4092 } else {
4093 mDidAppSwitch = true;
4094 }
4095 }
4096
4097 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004098 boolean shouldDisableNonVrUiLocked() {
4099 return mVrController.shouldDisableNonVrUiLocked();
4100 }
4101
4102 void applyUpdateVrModeLocked(ActivityRecord r) {
4103 // VR apps are expected to run in a main display. If an app is turning on VR for
4104 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4105 // fullscreen stack before enabling VR Mode.
4106 // TODO: The goal of this code is to keep the VR app on the main display. When the
4107 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4108 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4109 // option would be a better choice here.
4110 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4111 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4112 + " to main stack for VR");
4113 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4114 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4115 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4116 }
4117 mH.post(() -> {
4118 if (!mVrController.onVrModeChanged(r)) {
4119 return;
4120 }
4121 synchronized (mGlobalLock) {
4122 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4123 mWindowManager.disableNonVrUi(disableNonVrUi);
4124 if (disableNonVrUi) {
4125 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4126 // then remove the pinned stack.
4127 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4128 }
4129 }
4130 });
4131 }
4132
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004133 ActivityStack getTopDisplayFocusedStack() {
4134 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004135 }
4136
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004137 /** Pokes the task persister. */
4138 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4139 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4140 }
4141
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004142 void onTopProcChangedLocked(WindowProcessController proc) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004143 mVrController.onTopProcChangedLocked(proc);
4144 }
4145
4146 boolean isKeyguardLocked() {
4147 return mKeyguardController.isKeyguardLocked();
4148 }
4149
4150 boolean isNextTransitionForward() {
4151 int transit = mWindowManager.getPendingAppTransition();
4152 return transit == TRANSIT_ACTIVITY_OPEN
4153 || transit == TRANSIT_TASK_OPEN
4154 || transit == TRANSIT_TASK_TO_FRONT;
4155 }
4156
Wale Ogunwalef6733932018-06-27 05:14:34 -07004157 void dumpSleepStates(PrintWriter pw, boolean testPssMode) {
4158 synchronized (mGlobalLock) {
4159 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
4160 if (mRunningVoice != null) {
4161 pw.println(" mRunningVoice=" + mRunningVoice);
4162 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
4163 }
4164 pw.println(" mSleeping=" + mSleeping);
4165 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
4166 pw.println(" mVrController=" + mVrController);
4167 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004168 }
4169
Wale Ogunwalef6733932018-06-27 05:14:34 -07004170 void writeSleepStateToProto(ProtoOutputStream proto) {
4171 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4172 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4173 st.toString());
4174 }
4175
4176 if (mRunningVoice != null) {
4177 final long vrToken = proto.start(
4178 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4179 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4180 mRunningVoice.toString());
4181 mVoiceWakeLock.writeToProto(
4182 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4183 proto.end(vrToken);
4184 }
4185
4186 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4187 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4188 mShuttingDown);
4189 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004190 }
4191
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 int getCurrentUserId() {
4193 return mAmInternal.getCurrentUserId();
4194 }
4195
4196 private void enforceNotIsolatedCaller(String caller) {
4197 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4198 throw new SecurityException("Isolated process not allowed to call " + caller);
4199 }
4200 }
4201
Wale Ogunwalef6733932018-06-27 05:14:34 -07004202 public Configuration getConfiguration() {
4203 Configuration ci;
4204 synchronized(mGlobalLock) {
4205 ci = new Configuration(getGlobalConfiguration());
4206 ci.userSetLocale = false;
4207 }
4208 return ci;
4209 }
4210
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004211 /**
4212 * Current global configuration information. Contains general settings for the entire system,
4213 * also corresponds to the merged configuration of the default display.
4214 */
4215 Configuration getGlobalConfiguration() {
4216 return mStackSupervisor.getConfiguration();
4217 }
4218
4219 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4220 boolean initLocale) {
4221 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4222 }
4223
4224 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4225 boolean initLocale, boolean deferResume) {
4226 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4227 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4228 UserHandle.USER_NULL, deferResume);
4229 }
4230
4231 void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4232 final long origId = Binder.clearCallingIdentity();
4233 try {
4234 synchronized (mGlobalLock) {
4235 updateConfigurationLocked(values, null, false, true, userId,
4236 false /* deferResume */);
4237 }
4238 } finally {
4239 Binder.restoreCallingIdentity(origId);
4240 }
4241 }
4242
4243 void updateUserConfiguration() {
4244 synchronized (mGlobalLock) {
4245 final Configuration configuration = new Configuration(getGlobalConfiguration());
4246 final int currentUserId = mAmInternal.getCurrentUserId();
4247 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(), configuration,
4248 currentUserId, Settings.System.canWrite(mContext));
4249 updateConfigurationLocked(configuration, null /* starting */, false /* initLocale */,
4250 false /* persistent */, currentUserId, false /* deferResume */);
4251 }
4252 }
4253
4254 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4255 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4256 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4257 deferResume, null /* result */);
4258 }
4259
4260 /**
4261 * Do either or both things: (1) change the current configuration, and (2)
4262 * make sure the given activity is running with the (now) current
4263 * configuration. Returns true if the activity has been left running, or
4264 * false if <var>starting</var> is being destroyed to match the new
4265 * configuration.
4266 *
4267 * @param userId is only used when persistent parameter is set to true to persist configuration
4268 * for that particular user
4269 */
4270 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4271 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4272 ActivityTaskManagerService.UpdateConfigurationResult result) {
4273 int changes = 0;
4274 boolean kept = true;
4275
4276 if (mWindowManager != null) {
4277 mWindowManager.deferSurfaceLayout();
4278 }
4279 try {
4280 if (values != null) {
4281 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4282 deferResume);
4283 }
4284
4285 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4286 } finally {
4287 if (mWindowManager != null) {
4288 mWindowManager.continueSurfaceLayout();
4289 }
4290 }
4291
4292 if (result != null) {
4293 result.changes = changes;
4294 result.activityRelaunched = !kept;
4295 }
4296 return kept;
4297 }
4298
4299 /**
4300 * Returns true if this configuration change is interesting enough to send an
4301 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
4302 */
4303 private static boolean isSplitConfigurationChange(int configDiff) {
4304 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
4305 }
4306
4307 /** Update default (global) configuration and notify listeners about changes. */
4308 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4309 boolean persistent, int userId, boolean deferResume) {
4310 mTempConfig.setTo(getGlobalConfiguration());
4311 final int changes = mTempConfig.updateFrom(values);
4312 if (changes == 0) {
4313 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4314 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4315 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4316 // (even if there are no actual changes) to unfreeze the window.
4317 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4318 return 0;
4319 }
4320
4321 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4322 "Updating global configuration to: " + values);
4323
4324 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4325 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4326 values.colorMode,
4327 values.densityDpi,
4328 values.fontScale,
4329 values.hardKeyboardHidden,
4330 values.keyboard,
4331 values.keyboardHidden,
4332 values.mcc,
4333 values.mnc,
4334 values.navigation,
4335 values.navigationHidden,
4336 values.orientation,
4337 values.screenHeightDp,
4338 values.screenLayout,
4339 values.screenWidthDp,
4340 values.smallestScreenWidthDp,
4341 values.touchscreen,
4342 values.uiMode);
4343
4344
4345 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4346 final LocaleList locales = values.getLocales();
4347 int bestLocaleIndex = 0;
4348 if (locales.size() > 1) {
4349 if (mSupportedSystemLocales == null) {
4350 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4351 }
4352 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4353 }
4354 SystemProperties.set("persist.sys.locale",
4355 locales.get(bestLocaleIndex).toLanguageTag());
4356 LocaleList.setDefault(locales, bestLocaleIndex);
4357 mAm.mHandler.sendMessage(mAm.mHandler.obtainMessage(SEND_LOCALE_TO_MOUNT_DAEMON_MSG,
4358 locales.get(bestLocaleIndex)));
4359 }
4360
4361 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
4362 mTempConfig.seq = mConfigurationSeq;
4363
4364 // Update stored global config and notify everyone about the change.
4365 mStackSupervisor.onConfigurationChanged(mTempConfig);
4366
4367 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4368 // TODO(multi-display): Update UsageEvents#Event to include displayId.
4369 mAm.mUsageStatsService.reportConfigurationChange(
4370 mTempConfig, mAmInternal.getCurrentUserId());
4371
4372 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004373 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374
4375 AttributeCache ac = AttributeCache.instance();
4376 if (ac != null) {
4377 ac.updateConfiguration(mTempConfig);
4378 }
4379
4380 // Make sure all resources in our process are updated right now, so that anyone who is going
4381 // to retrieve resource values after we return will be sure to get the new ones. This is
4382 // especially important during boot, where the first config change needs to guarantee all
4383 // resources have that config before following boot code is executed.
4384 mAm.mSystemThread.applyConfigurationToResources(mTempConfig);
4385
4386 // We need another copy of global config because we're scheduling some calls instead of
4387 // running them in place. We need to be sure that object we send will be handled unchanged.
4388 final Configuration configCopy = new Configuration(mTempConfig);
4389 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
4390 Message msg = mAm.mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
4391 msg.obj = configCopy;
4392 msg.arg1 = userId;
4393 mAm.mHandler.sendMessage(msg);
4394 }
4395
4396 for (int i = mAm.mLruProcesses.size() - 1; i >= 0; i--) {
4397 ProcessRecord app = mAm.mLruProcesses.get(i);
4398 try {
4399 if (app.thread != null) {
4400 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Sending to proc "
4401 + app.processName + " new config " + configCopy);
4402 getLifecycleManager().scheduleTransaction(app.thread,
4403 ConfigurationChangeItem.obtain(configCopy));
4404 }
4405 } catch (Exception e) {
4406 Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change", e);
4407 }
4408 }
4409
4410 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
4411 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING
4412 | Intent.FLAG_RECEIVER_FOREGROUND
4413 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4414 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4415 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4416 UserHandle.USER_ALL);
4417 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
4418 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
4419 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
4420 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
4421 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4422 if (initLocale || !mAm.mProcessesReady) {
4423 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4424 }
4425 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4426 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4427 UserHandle.USER_ALL);
4428 }
4429
4430 // Send a broadcast to PackageInstallers if the configuration change is interesting
4431 // for the purposes of installing additional splits.
4432 if (!initLocale && isSplitConfigurationChange(changes)) {
4433 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
4434 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
4435 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4436
4437 // Typically only app stores will have this permission.
4438 String[] permissions = new String[] { android.Manifest.permission.INSTALL_PACKAGES };
4439 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, permissions,
4440 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
4441 }
4442
4443 // Override configuration of the default display duplicates global config, so we need to
4444 // update it also. This will also notify WindowManager about changes.
4445 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4446 DEFAULT_DISPLAY);
4447
4448 return changes;
4449 }
4450
4451 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4452 boolean deferResume, int displayId) {
4453 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4454 displayId, null /* result */);
4455 }
4456
4457 /**
4458 * Updates override configuration specific for the selected display. If no config is provided,
4459 * new one will be computed in WM based on current display info.
4460 */
4461 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4462 ActivityRecord starting, boolean deferResume, int displayId,
4463 ActivityTaskManagerService.UpdateConfigurationResult result) {
4464 int changes = 0;
4465 boolean kept = true;
4466
4467 if (mWindowManager != null) {
4468 mWindowManager.deferSurfaceLayout();
4469 }
4470 try {
4471 if (values != null) {
4472 if (displayId == DEFAULT_DISPLAY) {
4473 // Override configuration of the default display duplicates global config, so
4474 // we're calling global config update instead for default display. It will also
4475 // apply the correct override config.
4476 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4477 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4478 } else {
4479 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4480 }
4481 }
4482
4483 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4484 } finally {
4485 if (mWindowManager != null) {
4486 mWindowManager.continueSurfaceLayout();
4487 }
4488 }
4489
4490 if (result != null) {
4491 result.changes = changes;
4492 result.activityRelaunched = !kept;
4493 }
4494 return kept;
4495 }
4496
4497 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4498 int displayId) {
4499 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4500 final int changes = mTempConfig.updateFrom(values);
4501 if (changes != 0) {
4502 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4503 + mTempConfig + " for displayId=" + displayId);
4504 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4505
4506 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4507 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
4508 mAm.mAppWarnings.onDensityChanged();
4509
4510 mAm.killAllBackgroundProcessesExcept(N,
4511 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4512 }
4513 }
4514
4515 // Update the configuration with WM first and check if any of the stacks need to be resized
4516 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4517 // necessary. This way we don't need to relaunch again afterwards in
4518 // ensureActivityConfiguration().
4519 if (mWindowManager != null) {
4520 final int[] resizedStacks =
4521 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4522 if (resizedStacks != null) {
4523 for (int stackId : resizedStacks) {
4524 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4525 }
4526 }
4527 }
4528
4529 return changes;
4530 }
4531
Wale Ogunwalef6733932018-06-27 05:14:34 -07004532 private void updateEventDispatchingLocked(boolean booted) {
4533 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4534 }
4535
4536 void enableScreenAfterBoot(boolean booted) {
4537 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4538 SystemClock.uptimeMillis());
4539 mWindowManager.enableScreenAfterBoot();
4540
4541 synchronized (mGlobalLock) {
4542 updateEventDispatchingLocked(booted);
4543 }
4544 }
4545
4546 boolean canShowErrorDialogs() {
4547 return mShowDialogs && !mSleeping && !mShuttingDown
4548 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
4549 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
Wale Ogunwale86b74462018-07-02 08:42:43 -07004550 mAmInternal.getCurrentUserId())
Wale Ogunwalef6733932018-06-27 05:14:34 -07004551 && !(UserManager.isDeviceInDemoMode(mContext)
Wale Ogunwale86b74462018-07-02 08:42:43 -07004552 && mAmInternal.getCurrentUser().isDemo());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004553 }
4554
4555 /**
4556 * Decide based on the configuration whether we should show the ANR,
4557 * crash, etc dialogs. The idea is that if there is no affordance to
4558 * press the on-screen buttons, or the user experience would be more
4559 * greatly impacted than the crash itself, we shouldn't show the dialog.
4560 *
4561 * A thought: SystemUI might also want to get told about this, the Power
4562 * dialog / global actions also might want different behaviors.
4563 */
4564 private void updateShouldShowDialogsLocked(Configuration config) {
4565 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4566 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4567 && config.navigation == Configuration.NAVIGATION_NONAV);
4568 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4569 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4570 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4571 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4572 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4573 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4574 HIDE_ERROR_DIALOGS, 0) != 0;
4575 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4576 }
4577
4578 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4579 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4580 FONT_SCALE, 1.0f, userId);
4581
4582 synchronized (this) {
4583 if (getGlobalConfiguration().fontScale == scaleFactor) {
4584 return;
4585 }
4586
4587 final Configuration configuration
4588 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4589 configuration.fontScale = scaleFactor;
4590 updatePersistentConfiguration(configuration, userId);
4591 }
4592 }
4593
4594 // Actually is sleeping or shutting down or whatever else in the future
4595 // is an inactive state.
4596 boolean isSleepingOrShuttingDownLocked() {
4597 return isSleepingLocked() || mShuttingDown;
4598 }
4599
4600 boolean isSleepingLocked() {
4601 return mSleeping;
4602 }
4603
4604 /**
4605 * Update AMS states when an activity is resumed. This should only be called by
4606 * {@link ActivityStack#onActivityStateChanged(
4607 * ActivityRecord, ActivityStack.ActivityState, String)} when an activity is resumed.
4608 */
4609 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4610 final TaskRecord task = r.getTask();
4611 if (task.isActivityTypeStandard()) {
4612 if (mCurAppTimeTracker != r.appTimeTracker) {
4613 // We are switching app tracking. Complete the current one.
4614 if (mCurAppTimeTracker != null) {
4615 mCurAppTimeTracker.stop();
4616 mH.obtainMessage(
4617 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4618 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4619 mCurAppTimeTracker = null;
4620 }
4621 if (r.appTimeTracker != null) {
4622 mCurAppTimeTracker = r.appTimeTracker;
4623 startTimeTrackingFocusedActivityLocked();
4624 }
4625 } else {
4626 startTimeTrackingFocusedActivityLocked();
4627 }
4628 } else {
4629 r.appTimeTracker = null;
4630 }
4631 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
4632 // TODO: Probably not, because we don't want to resume voice on switching
4633 // back to this activity
4634 if (task.voiceInteractor != null) {
4635 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
4636 } else {
4637 finishRunningVoiceLocked();
4638
4639 if (mLastResumedActivity != null) {
4640 final IVoiceInteractionSession session;
4641
4642 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
4643 if (lastResumedActivityTask != null
4644 && lastResumedActivityTask.voiceSession != null) {
4645 session = lastResumedActivityTask.voiceSession;
4646 } else {
4647 session = mLastResumedActivity.voiceSession;
4648 }
4649
4650 if (session != null) {
4651 // We had been in a voice interaction session, but now focused has
4652 // move to something different. Just finish the session, we can't
4653 // return to it and retain the proper state and synchronization with
4654 // the voice interaction service.
4655 finishVoiceTask(session);
4656 }
4657 }
4658 }
4659
4660 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
4661 mAmInternal.sendForegroundProfileChanged(r.userId);
4662 }
4663 updateResumedAppTrace(r);
4664 mLastResumedActivity = r;
4665
4666 mWindowManager.setFocusedApp(r.appToken, true);
4667
4668 applyUpdateLockStateLocked(r);
4669 applyUpdateVrModeLocked(r);
4670
4671 EventLogTags.writeAmSetResumedActivity(
4672 r == null ? -1 : r.userId,
4673 r == null ? "NULL" : r.shortComponentName,
4674 reason);
4675 }
4676
4677 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
4678 synchronized (mGlobalLock) {
4679 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
4680 updateSleepIfNeededLocked();
4681 return token;
4682 }
4683 }
4684
4685 void updateSleepIfNeededLocked() {
4686 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
4687 final boolean wasSleeping = mSleeping;
4688 boolean updateOomAdj = false;
4689
4690 if (!shouldSleep) {
4691 // If wasSleeping is true, we need to wake up activity manager state from when
4692 // we started sleeping. In either case, we need to apply the sleep tokens, which
4693 // will wake up stacks or put them to sleep as appropriate.
4694 if (wasSleeping) {
4695 mSleeping = false;
4696 startTimeTrackingFocusedActivityLocked();
4697 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
4698 mStackSupervisor.comeOutOfSleepIfNeededLocked();
4699 }
4700 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
4701 if (wasSleeping) {
4702 updateOomAdj = true;
4703 }
4704 } else if (!mSleeping && shouldSleep) {
4705 mSleeping = true;
4706 if (mCurAppTimeTracker != null) {
4707 mCurAppTimeTracker.stop();
4708 }
4709 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
4710 mStackSupervisor.goingToSleepLocked();
4711 updateResumedAppTrace(null /* resumed */);
4712 updateOomAdj = true;
4713 }
4714 if (updateOomAdj) {
4715 mH.post(mAmInternal::updateOomAdj);
4716 }
4717 }
4718
4719 void updateOomAdj() {
4720 mH.post(mAmInternal::updateOomAdj);
4721 }
4722
Andrii Kulian52d255c2018-07-13 11:32:19 -07004723 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07004724 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07004725 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07004726 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
4727 mCurAppTimeTracker.start(resumedActivity.packageName);
4728 }
4729 }
4730
4731 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
4732 if (mTracedResumedActivity != null) {
4733 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
4734 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
4735 }
4736 if (resumed != null) {
4737 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
4738 constructResumedTraceName(resumed.packageName), 0);
4739 }
4740 mTracedResumedActivity = resumed;
4741 }
4742
4743 private String constructResumedTraceName(String packageName) {
4744 return "focused app: " + packageName;
4745 }
4746
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004747 /** Helper method that requests bounds from WM and applies them to stack. */
4748 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
4749 final Rect newStackBounds = new Rect();
4750 final ActivityStack stack = mStackSupervisor.getStack(stackId);
4751
4752 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
4753 if (stack == null) {
4754 final StringWriter writer = new StringWriter();
4755 final PrintWriter printWriter = new PrintWriter(writer);
4756 mStackSupervisor.dumpDisplays(printWriter);
4757 printWriter.flush();
4758
4759 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
4760 }
4761
4762 stack.getBoundsForNewConfiguration(newStackBounds);
4763 mStackSupervisor.resizeStackLocked(
4764 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
4765 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
4766 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
4767 }
4768
4769 /** Applies latest configuration and/or visibility updates if needed. */
4770 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
4771 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004772 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004773 // mainStack is null during startup.
4774 if (mainStack != null) {
4775 if (changes != 0 && starting == null) {
4776 // If the configuration changed, and the caller is not already
4777 // in the process of starting an activity, then find the top
4778 // activity to check if its configuration needs to change.
4779 starting = mainStack.topRunningActivityLocked();
4780 }
4781
4782 if (starting != null) {
4783 kept = starting.ensureActivityConfiguration(changes,
4784 false /* preserveWindow */);
4785 // And we need to make sure at this point that all other activities
4786 // are made visible with the correct configuration.
4787 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
4788 !PRESERVE_WINDOWS);
4789 }
4790 }
4791
4792 return kept;
4793 }
4794
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004795 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
4796 if (true || Build.IS_USER) {
4797 return;
4798 }
4799
4800 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4801 StrictMode.allowThreadDiskWrites();
4802 try {
4803 File tracesDir = new File("/data/anr");
4804 File tracesFile = null;
4805 try {
4806 tracesFile = File.createTempFile("app_slow", null, tracesDir);
4807
4808 StringBuilder sb = new StringBuilder();
4809 Time tobj = new Time();
4810 tobj.set(System.currentTimeMillis());
4811 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4812 sb.append(": ");
4813 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4814 sb.append(" since ");
4815 sb.append(msg);
4816 FileOutputStream fos = new FileOutputStream(tracesFile);
4817 fos.write(sb.toString().getBytes());
4818 if (app == null) {
4819 fos.write("\n*** No application process!".getBytes());
4820 }
4821 fos.close();
4822 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4823 } catch (IOException e) {
4824 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
4825 return;
4826 }
4827
4828 if (app != null && app.getPid() > 0) {
4829 ArrayList<Integer> firstPids = new ArrayList<Integer>();
4830 firstPids.add(app.getPid());
4831 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
4832 }
4833
4834 File lastTracesFile = null;
4835 File curTracesFile = null;
4836 for (int i=9; i>=0; i--) {
4837 String name = String.format(Locale.US, "slow%02d.txt", i);
4838 curTracesFile = new File(tracesDir, name);
4839 if (curTracesFile.exists()) {
4840 if (lastTracesFile != null) {
4841 curTracesFile.renameTo(lastTracesFile);
4842 } else {
4843 curTracesFile.delete();
4844 }
4845 }
4846 lastTracesFile = curTracesFile;
4847 }
4848 tracesFile.renameTo(curTracesFile);
4849 } finally {
4850 StrictMode.setThreadPolicy(oldPolicy);
4851 }
4852 }
4853
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004854 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004855 static final int REPORT_TIME_TRACKER_MSG = 1;
4856
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004857 public H(Looper looper) {
4858 super(looper, null, true);
4859 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004860
4861 @Override
4862 public void handleMessage(Message msg) {
4863 switch (msg.what) {
4864 case REPORT_TIME_TRACKER_MSG: {
4865 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
4866 tracker.deliverResult(mContext);
4867 } break;
4868 }
4869 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004870 }
4871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004872 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004873 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004874
4875 public UiHandler() {
4876 super(com.android.server.UiThread.get().getLooper(), null, true);
4877 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004878
4879 @Override
4880 public void handleMessage(Message msg) {
4881 switch (msg.what) {
4882 case DISMISS_DIALOG_UI_MSG: {
4883 final Dialog d = (Dialog) msg.obj;
4884 d.dismiss();
4885 break;
4886 }
4887 }
4888 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004889 }
4890
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004891 final class LocalService extends ActivityTaskManagerInternal {
4892 @Override
4893 public SleepToken acquireSleepToken(String tag, int displayId) {
4894 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004895 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004896 }
4897
4898 @Override
4899 public ComponentName getHomeActivityForUser(int userId) {
4900 synchronized (mGlobalLock) {
4901 ActivityRecord homeActivity = mStackSupervisor.getHomeActivityForUser(userId);
4902 return homeActivity == null ? null : homeActivity.realActivity;
4903 }
4904 }
4905
4906 @Override
4907 public void onLocalVoiceInteractionStarted(IBinder activity,
4908 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
4909 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004910 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004911 }
4912 }
4913
4914 @Override
4915 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
4916 synchronized (mGlobalLock) {
4917 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
4918 reasons, timestamp);
4919 }
4920 }
4921
4922 @Override
4923 public void notifyAppTransitionFinished() {
4924 synchronized (mGlobalLock) {
4925 mStackSupervisor.notifyAppTransitionDone();
4926 }
4927 }
4928
4929 @Override
4930 public void notifyAppTransitionCancelled() {
4931 synchronized (mGlobalLock) {
4932 mStackSupervisor.notifyAppTransitionDone();
4933 }
4934 }
4935
4936 @Override
4937 public List<IBinder> getTopVisibleActivities() {
4938 synchronized (mGlobalLock) {
4939 return mStackSupervisor.getTopVisibleActivities();
4940 }
4941 }
4942
4943 @Override
4944 public void notifyDockedStackMinimizedChanged(boolean minimized) {
4945 synchronized (mGlobalLock) {
4946 mStackSupervisor.setDockedStackMinimized(minimized);
4947 }
4948 }
4949
4950 @Override
4951 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
4952 Bundle bOptions) {
4953 Preconditions.checkNotNull(intents, "intents");
4954 final String[] resolvedTypes = new String[intents.length];
4955
4956 // UID of the package on user userId.
4957 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
4958 // packageUid may not be initialized.
4959 int packageUid = 0;
4960 final long ident = Binder.clearCallingIdentity();
4961
4962 try {
4963 for (int i = 0; i < intents.length; i++) {
4964 resolvedTypes[i] =
4965 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
4966 }
4967
4968 packageUid = AppGlobals.getPackageManager().getPackageUid(
4969 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
4970 } catch (RemoteException e) {
4971 // Shouldn't happen.
4972 } finally {
4973 Binder.restoreCallingIdentity(ident);
4974 }
4975
4976 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004977 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004978 packageUid, packageName,
4979 intents, resolvedTypes, null /* resultTo */,
4980 SafeActivityOptions.fromBundle(bOptions), userId,
4981 false /* validateIncomingUser */);
4982 }
4983 }
4984
4985 @Override
4986 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
4987 Intent intent, Bundle options, int userId) {
4988 return ActivityTaskManagerService.this.startActivityAsUser(
4989 caller, callerPacakge, intent,
4990 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
4991 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
4992 false /*validateIncomingUser*/);
4993 }
4994
4995 @Override
4996 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback) {
4997 synchronized (mGlobalLock) {
4998
4999 // We might change the visibilities here, so prepare an empty app transition which
5000 // might be overridden later if we actually change visibilities.
5001 final boolean wasTransitionSet =
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005002 mWindowManager.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005003 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005004 mWindowManager.prepareAppTransition(TRANSIT_NONE,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005005 false /* alwaysKeepCurrent */);
5006 }
5007 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5008
5009 // If there was a transition set already we don't want to interfere with it as we
5010 // might be starting it too early.
5011 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005012 mWindowManager.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005013 }
5014 }
5015 if (callback != null) {
5016 callback.run();
5017 }
5018 }
5019
5020 @Override
5021 public void notifyKeyguardTrustedChanged() {
5022 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005023 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005024 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5025 }
5026 }
5027 }
5028
5029 /**
5030 * Called after virtual display Id is updated by
5031 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5032 * {@param vrVr2dDisplayId}.
5033 */
5034 @Override
5035 public void setVr2dDisplayId(int vr2dDisplayId) {
5036 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5037 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005038 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005039 }
5040 }
5041
5042 @Override
5043 public void setFocusedActivity(IBinder token) {
5044 synchronized (mGlobalLock) {
5045 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5046 if (r == null) {
5047 throw new IllegalArgumentException(
5048 "setFocusedActivity: No activity record matching token=" + token);
5049 }
5050 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
5051 r, "setFocusedActivity")) {
5052 mStackSupervisor.resumeFocusedStackTopActivityLocked();
5053 }
5054 }
5055 }
5056
5057 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005058 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005060 }
5061
5062 @Override
5063 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005064 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005065 }
5066
5067 @Override
5068 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005069 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005070 }
5071
5072 @Override
5073 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5074 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5075 }
5076
5077 @Override
5078 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005079 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005080 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005081
5082 @Override
5083 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5084 synchronized (mGlobalLock) {
5085 mActiveVoiceInteractionServiceComponent = component;
5086 }
5087 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005088
5089 @Override
5090 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5091 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5092 return;
5093 }
5094 synchronized (mGlobalLock) {
5095 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5096 if (types == null) {
5097 if (uid < 0) {
5098 return;
5099 }
5100 types = new ArrayMap<>();
5101 mAllowAppSwitchUids.put(userId, types);
5102 }
5103 if (uid < 0) {
5104 types.remove(type);
5105 } else {
5106 types.put(type, uid);
5107 }
5108 }
5109 }
5110
5111 @Override
5112 public void onUserStopped(int userId) {
5113 synchronized (mGlobalLock) {
5114 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5115 mAllowAppSwitchUids.remove(userId);
5116 }
5117 }
5118
5119 @Override
5120 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5121 synchronized (mGlobalLock) {
5122 return ActivityTaskManagerService.this.isGetTasksAllowed(
5123 caller, callingPid, callingUid);
5124 }
5125 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005126
5127 @Override
5128 public void onProcessAdded(WindowProcessController proc) {
5129 synchronized (mGlobalLock) {
5130 mProcessNames.put(proc.mName, proc.mUid, proc);
5131 }
5132 }
5133
5134 @Override
5135 public void onProcessRemoved(String name, int uid) {
5136 synchronized (mGlobalLock) {
5137 mProcessNames.remove(name, uid);
5138 }
5139 }
5140
5141 @Override
5142 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5143 synchronized (mGlobalLock) {
5144 if (proc == mHomeProcess) {
5145 mHomeProcess = null;
5146 }
5147 if (proc == mPreviousProcess) {
5148 mPreviousProcess = null;
5149 }
5150 }
5151 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005152
5153 @Override
5154 public int getTopProcessState() {
5155 synchronized (mGlobalLock) {
5156 return mTopProcessState;
5157 }
5158 }
5159
5160 @Override
5161 public boolean isSleeping() {
5162 synchronized (mGlobalLock) {
5163 return isSleepingLocked();
5164 }
5165 }
5166
5167 @Override
5168 public boolean isShuttingDown() {
5169 synchronized (mGlobalLock) {
5170 return mShuttingDown;
5171 }
5172 }
5173
5174 @Override
5175 public boolean shuttingDown(boolean booted, int timeout) {
5176 synchronized (mGlobalLock) {
5177 mShuttingDown = true;
5178 mStackSupervisor.prepareForShutdownLocked();
5179 updateEventDispatchingLocked(booted);
5180 return mStackSupervisor.shutdownLocked(timeout);
5181 }
5182 }
5183
5184 @Override
5185 public void enableScreenAfterBoot(boolean booted) {
5186 synchronized (mGlobalLock) {
5187 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5188 SystemClock.uptimeMillis());
5189 mWindowManager.enableScreenAfterBoot();
5190 updateEventDispatchingLocked(booted);
5191 }
5192 }
5193
5194 @Override
5195 public boolean showStrictModeViolationDialog() {
5196 synchronized (mGlobalLock) {
5197 return mShowDialogs && !mSleeping && !mShuttingDown;
5198 }
5199 }
5200
5201 @Override
5202 public void showSystemReadyErrorDialogsIfNeeded() {
5203 synchronized (mGlobalLock) {
5204 try {
5205 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5206 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5207 + " data partition or your device will be unstable.");
5208 mUiHandler.post(() -> {
5209 if (mShowDialogs) {
5210 AlertDialog d = new BaseErrorDialog(mUiContext);
5211 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5212 d.setCancelable(false);
5213 d.setTitle(mUiContext.getText(R.string.android_system_label));
5214 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5215 d.setButton(DialogInterface.BUTTON_POSITIVE,
5216 mUiContext.getText(R.string.ok),
5217 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5218 d.show();
5219 }
5220 });
5221 }
5222 } catch (RemoteException e) {
5223 }
5224
5225 if (!Build.isBuildConsistent()) {
5226 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5227 mUiHandler.post(() -> {
5228 if (mShowDialogs) {
5229 AlertDialog d = new BaseErrorDialog(mUiContext);
5230 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5231 d.setCancelable(false);
5232 d.setTitle(mUiContext.getText(R.string.android_system_label));
5233 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5234 d.setButton(DialogInterface.BUTTON_POSITIVE,
5235 mUiContext.getText(R.string.ok),
5236 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5237 d.show();
5238 }
5239 });
5240 }
5241 }
5242 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005243 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07005244}