blob: d77e1a20e0c00c28e06cdb46ce0ca67009db06bd [file] [log] [blame]
Benjamin Franza83859f2017-07-03 16:34:14 +01001/*
2 * Copyright 2017, 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
19import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
20import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
21import static android.app.ActivityManager.LOCK_TASK_MODE_PINNED;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070022import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Benjamin Franza83859f2017-07-03 16:34:14 +010023import static android.content.Context.DEVICE_POLICY_SERVICE;
24import static android.content.Context.STATUS_BAR_SERVICE;
25import static android.os.UserHandle.USER_ALL;
Amith Yamasani7cbbf2222017-08-30 14:22:37 -070026import static android.os.UserHandle.USER_CURRENT;
Benjamin Franza83859f2017-07-03 16:34:14 +010027import static android.view.Display.DEFAULT_DISPLAY;
Charles He520b2832017-09-02 15:27:16 +010028
Benjamin Franza83859f2017-07-03 16:34:14 +010029import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
30import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
31import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
32import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
33import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
34import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
35import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
36import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
37import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
38
39import android.annotation.NonNull;
40import android.annotation.Nullable;
41import android.app.Activity;
42import android.app.ActivityManager;
Charles Hee078db72017-10-19 18:03:20 +010043import android.app.StatusBarManager;
44import android.app.admin.DevicePolicyManager;
Benjamin Franza83859f2017-07-03 16:34:14 +010045import android.app.admin.IDevicePolicyManager;
Charles Hee078db72017-10-19 18:03:20 +010046import android.content.ComponentName;
Benjamin Franza83859f2017-07-03 16:34:14 +010047import android.content.Context;
48import android.os.Binder;
49import android.os.Debug;
50import android.os.Handler;
51import android.os.IBinder;
52import android.os.RemoteException;
53import android.os.ServiceManager;
54import android.provider.Settings;
Charles Hee078db72017-10-19 18:03:20 +010055import android.util.Pair;
Benjamin Franza83859f2017-07-03 16:34:14 +010056import android.util.Slog;
Charles He520b2832017-09-02 15:27:16 +010057import android.util.SparseArray;
Benjamin Franza83859f2017-07-03 16:34:14 +010058
59import com.android.internal.annotations.VisibleForTesting;
60import com.android.internal.statusbar.IStatusBarService;
61import com.android.internal.widget.LockPatternUtils;
62import com.android.server.LocalServices;
63import com.android.server.statusbar.StatusBarManagerInternal;
64import com.android.server.wm.WindowManagerService;
65
66import java.io.PrintWriter;
67import java.util.ArrayList;
Charles He520b2832017-09-02 15:27:16 +010068import java.util.Arrays;
Benjamin Franza83859f2017-07-03 16:34:14 +010069
70/**
71 * Helper class that deals with all things related to task locking. This includes the screen pinning
72 * mode that can be launched via System UI as well as the fully locked mode that can be achieved
73 * on fully managed devices.
74 *
75 * Note: All methods in this class should only be called with the ActivityManagerService lock held.
76 *
77 * @see Activity#startLockTask()
78 * @see Activity#stopLockTask()
79 */
80public class LockTaskController {
81 private static final String TAG = TAG_WITH_CLASS_NAME ? "LockTaskController" : TAG_AM;
82 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
83
84 @VisibleForTesting
Charles Hee078db72017-10-19 18:03:20 +010085 static final int STATUS_BAR_MASK_LOCKED = StatusBarManager.DISABLE_MASK
86 & (~StatusBarManager.DISABLE_EXPAND)
87 & (~StatusBarManager.DISABLE_NOTIFICATION_TICKER)
88 & (~StatusBarManager.DISABLE_SYSTEM_INFO)
89 & (~StatusBarManager.DISABLE_BACK);
Benjamin Franza83859f2017-07-03 16:34:14 +010090 @VisibleForTesting
Charles Hee078db72017-10-19 18:03:20 +010091 static final int STATUS_BAR_MASK_PINNED = StatusBarManager.DISABLE_MASK
92 & (~StatusBarManager.DISABLE_BACK)
93 & (~StatusBarManager.DISABLE_HOME)
94 & (~StatusBarManager.DISABLE_RECENT);
95
96 private static final SparseArray<Pair<Integer, Integer>> STATUS_BAR_FLAG_MAP_LOCKED;
97 static {
98 STATUS_BAR_FLAG_MAP_LOCKED = new SparseArray<>();
99
100 STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO,
101 new Pair<>(StatusBarManager.DISABLE_CLOCK, StatusBarManager.DISABLE2_SYSTEM_ICONS));
102
103 STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS,
104 new Pair<>(StatusBarManager.DISABLE_NOTIFICATION_ICONS
105 | StatusBarManager.DISABLE_NOTIFICATION_ALERTS,
106 StatusBarManager.DISABLE2_NOTIFICATION_SHADE));
107
108 STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_HOME,
109 new Pair<>(StatusBarManager.DISABLE_HOME, StatusBarManager.DISABLE2_NONE));
110
111 STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS,
112 new Pair<>(StatusBarManager.DISABLE_RECENT, StatusBarManager.DISABLE2_NONE));
113
114 STATUS_BAR_FLAG_MAP_LOCKED.append(DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
115 new Pair<>(StatusBarManager.DISABLE_NONE,
116 StatusBarManager.DISABLE2_GLOBAL_ACTIONS));
117 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100118
119 /** Tag used for disabling of keyguard */
120 private static final String LOCK_TASK_TAG = "Lock-to-App";
121
122 private final IBinder mToken = new Binder();
123 private final ActivityStackSupervisor mSupervisor;
124 private final Context mContext;
125
126 // The following system services cannot be final, because they do not exist when this class
127 // is instantiated during device boot
128 @VisibleForTesting
129 IStatusBarService mStatusBarService;
130 @VisibleForTesting
131 IDevicePolicyManager mDevicePolicyManager;
132 @VisibleForTesting
133 WindowManagerService mWindowManager;
134 @VisibleForTesting
135 LockPatternUtils mLockPatternUtils;
136
137 /**
138 * Helper that is responsible for showing the right toast when a disallowed activity operation
139 * occurred. In pinned mode, we show instructions on how to break out of this mode, whilst in
140 * fully locked mode we only show that unlocking is blocked.
141 */
142 @VisibleForTesting
143 LockTaskNotify mLockTaskNotify;
144
145 /**
Charles Heff9b4dff2017-09-22 10:18:37 +0100146 * The chain of tasks in LockTask mode, in the order of when they first entered LockTask mode.
147 *
148 * The first task in the list, which started the current LockTask session, is called the root
149 * task. It coincides with the Home task in a typical multi-app kiosk deployment. When there are
150 * more than one locked tasks, the root task can't be finished. Nor can it be moved to the back
151 * of the stack by {@link ActivityStack#moveTaskToBackLocked(int)};
152 *
153 * Calling {@link Activity#stopLockTask()} on the root task will finish all tasks but itself in
154 * this list, and the device will exit LockTask mode.
155 *
156 * The list is empty if LockTask is inactive.
Benjamin Franza83859f2017-07-03 16:34:14 +0100157 */
158 private final ArrayList<TaskRecord> mLockTaskModeTasks = new ArrayList<>();
159
160 /**
Charles He520b2832017-09-02 15:27:16 +0100161 * Packages that are allowed to be launched into the lock task mode for each user.
162 */
163 private final SparseArray<String[]> mLockTaskPackages = new SparseArray<>();
164
165 /**
Charles Hee078db72017-10-19 18:03:20 +0100166 * Features that are allowed by DPC to show during LockTask mode.
167 */
168 private final SparseArray<Integer> mLockTaskFeatures = new SparseArray<>();
169
170 /**
Benjamin Franza83859f2017-07-03 16:34:14 +0100171 * Store the current lock task mode. Possible values:
172 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
173 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}
174 */
Charles Heff9b4dff2017-09-22 10:18:37 +0100175 private int mLockTaskModeState = LOCK_TASK_MODE_NONE;
Benjamin Franza83859f2017-07-03 16:34:14 +0100176
177 /**
178 * This is ActivityStackSupervisor's Handler.
179 */
180 private final Handler mHandler;
181
182 LockTaskController(Context context, ActivityStackSupervisor supervisor,
183 Handler handler) {
184 mContext = context;
185 mSupervisor = supervisor;
186 mHandler = handler;
187 }
188
189 /**
190 * Set the window manager instance used in this class. This is necessary, because the window
191 * manager does not exist during instantiation of this class.
192 */
193 void setWindowManager(WindowManagerService windowManager) {
194 mWindowManager = windowManager;
195 }
196
197 /**
198 * @return the current lock task state. This can be any of
199 * {@link ActivityManager#LOCK_TASK_MODE_NONE}, {@link ActivityManager#LOCK_TASK_MODE_LOCKED},
200 * {@link ActivityManager#LOCK_TASK_MODE_PINNED}.
201 */
202 int getLockTaskModeState() {
203 return mLockTaskModeState;
204 }
205
206 /**
Charles He520b2832017-09-02 15:27:16 +0100207 * @return whether the given task is locked at the moment. Locked tasks cannot be moved to the
208 * back of the stack.
Benjamin Franza83859f2017-07-03 16:34:14 +0100209 */
Charles Heff9b4dff2017-09-22 10:18:37 +0100210 @VisibleForTesting
211 boolean isTaskLocked(TaskRecord task) {
212 return mLockTaskModeTasks.contains(task);
213 }
214
215 /**
216 * @return {@code true} whether this task first started the current LockTask session.
217 */
218 private boolean isRootTask(TaskRecord task) {
219 return mLockTaskModeTasks.indexOf(task) == 0;
220 }
221
222 /**
223 * @return whether the given activity is blocked from finishing, because it is the only activity
224 * of the last locked task and finishing it would mean that lock task mode is ended illegally.
225 */
226 boolean activityBlockedFromFinish(ActivityRecord activity) {
227 final TaskRecord task = activity.getTask();
228 if (activity == task.getRootActivity()
229 && activity == task.getTopActivity()
230 && task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV
231 && isRootTask(task)) {
232 Slog.i(TAG, "Not finishing task in lock task mode");
Benjamin Franza83859f2017-07-03 16:34:14 +0100233 showLockTaskToast();
234 return true;
235 }
236 return false;
237 }
238
239 /**
Charles Heff9b4dff2017-09-22 10:18:37 +0100240 * @return whether the given task can be moved to the back of the stack with
241 * {@link ActivityStack#moveTaskToBackLocked(int)}
242 * @see #mLockTaskModeTasks
Benjamin Franza83859f2017-07-03 16:34:14 +0100243 */
Charles Heff9b4dff2017-09-22 10:18:37 +0100244 boolean canMoveTaskToBack(TaskRecord task) {
245 if (isRootTask(task)) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100246 showLockTaskToast();
Charles Heff9b4dff2017-09-22 10:18:37 +0100247 return false;
Benjamin Franza83859f2017-07-03 16:34:14 +0100248 }
Charles Heff9b4dff2017-09-22 10:18:37 +0100249 return true;
Benjamin Franza83859f2017-07-03 16:34:14 +0100250 }
251
252 /**
Charles Hed62f9652017-11-01 10:05:51 +0000253 * @return whether the requested task is allowed to be locked (either whitelisted, or declares
254 * lockTaskMode="always" in the manifest).
255 */
256 boolean isTaskWhitelisted(TaskRecord task) {
257 switch(task.mLockTaskAuth) {
258 case LOCK_TASK_AUTH_WHITELISTED:
259 case LOCK_TASK_AUTH_LAUNCHABLE:
260 case LOCK_TASK_AUTH_LAUNCHABLE_PRIV:
261 return true;
262 case LOCK_TASK_AUTH_PINNABLE:
263 case LOCK_TASK_AUTH_DONT_LOCK:
264 default:
265 return false;
266 }
267 }
268
269 /**
270 * @return whether the requested task is disallowed to be launched.
Benjamin Franza83859f2017-07-03 16:34:14 +0100271 */
272 boolean isLockTaskModeViolation(TaskRecord task) {
273 return isLockTaskModeViolation(task, false);
274 }
275
276 /**
277 * @param isNewClearTask whether the task would be cleared as part of the operation.
Charles Hed62f9652017-11-01 10:05:51 +0000278 * @return whether the requested task is disallowed to be launched.
Benjamin Franza83859f2017-07-03 16:34:14 +0100279 */
280 boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) {
281 if (isLockTaskModeViolationInternal(task, isNewClearTask)) {
282 showLockTaskToast();
283 return true;
284 }
285 return false;
286 }
287
288 private boolean isLockTaskModeViolationInternal(TaskRecord task, boolean isNewClearTask) {
289 // TODO: Double check what's going on here. If the task is already in lock task mode, it's
290 // likely whitelisted, so will return false below.
Charles Heff9b4dff2017-09-22 10:18:37 +0100291 if (isTaskLocked(task) && !isNewClearTask) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100292 // If the task is already at the top and won't be cleared, then allow the operation
293 return false;
294 }
Charles Hed62f9652017-11-01 10:05:51 +0000295
296 // Allow recents activity if enabled by policy
297 if (task.isActivityTypeRecents() && isRecentsAllowed(task.userId)) {
298 return false;
Benjamin Franza83859f2017-07-03 16:34:14 +0100299 }
Charles Hed62f9652017-11-01 10:05:51 +0000300
301 return !(isTaskWhitelisted(task) || mLockTaskModeTasks.isEmpty());
302 }
303
304 private boolean isRecentsAllowed(int userId) {
305 return (getLockTaskFeaturesForUser(userId)
306 & DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS) != 0;
Benjamin Franza83859f2017-07-03 16:34:14 +0100307 }
308
309 /**
310 * Stop the current lock task mode.
311 *
Charles Heff9b4dff2017-09-22 10:18:37 +0100312 * This is called by {@link ActivityManagerService} and performs various checks before actually
313 * finishing the locked task.
314 *
315 * @param task the task that requested the end of lock task mode ({@code null} for quitting app
316 * pinning mode)
317 * @param isSystemCaller indicates whether this request comes from the system via
318 * {@link ActivityManagerService#stopSystemLockTaskMode()}. If
319 * {@code true}, it means the user intends to stop pinned mode through UI;
320 * otherwise, it's called by an app and we need to stop locked or pinned
321 * mode, subject to checks.
Benjamin Franza83859f2017-07-03 16:34:14 +0100322 * @param callingUid the caller that requested the end of lock task mode.
Charles Heff9b4dff2017-09-22 10:18:37 +0100323 * @throws IllegalArgumentException if the calling task is invalid (e.g., {@code null} or not in
324 * foreground)
Benjamin Franza83859f2017-07-03 16:34:14 +0100325 * @throws SecurityException if the caller is not authorized to stop the lock task mode, i.e. if
326 * they differ from the one that launched lock task mode.
327 */
Charles Heff9b4dff2017-09-22 10:18:37 +0100328 void stopLockTaskMode(@Nullable TaskRecord task, boolean isSystemCaller, int callingUid) {
329 if (mLockTaskModeState == LOCK_TASK_MODE_NONE) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100330 return;
331 }
332
Charles Heff9b4dff2017-09-22 10:18:37 +0100333 if (isSystemCaller) {
334 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
335 clearLockedTasks("stopAppPinning");
336 } else {
337 Slog.e(TAG_LOCKTASK, "Attempted to stop LockTask with isSystemCaller=true");
338 showLockTaskToast();
339 }
340
341 } else {
342 // Ensure calling activity is not null
343 if (task == null) {
344 throw new IllegalArgumentException("can't stop LockTask for null task");
345 }
346
347 // Ensure the same caller for startLockTaskMode and stopLockTaskMode.
348 // It is possible lockTaskMode was started by the system process because
349 // android:lockTaskMode is set to a locking value in the application manifest
350 // instead of the app calling startLockTaskMode. In this case
351 // {@link TaskRecord.mLockTaskUid} will be 0, so we compare the callingUid to the
352 // {@link TaskRecord.effectiveUid} instead. Also caller with
353 // {@link MANAGE_ACTIVITY_STACKS} can stop any lock task.
354 if (callingUid != task.mLockTaskUid
355 && (task.mLockTaskUid != 0 || callingUid != task.effectiveUid)) {
356 throw new SecurityException("Invalid uid, expected " + task.mLockTaskUid
357 + " callingUid=" + callingUid + " effectiveUid=" + task.effectiveUid);
358 }
359
360 // We don't care if it's pinned or locked mode; this will stop it anyways.
361 clearLockedTask(task);
362 }
363 }
364
365 /**
366 * Clear all locked tasks and request the end of LockTask mode.
367 *
368 * This method is called by {@link UserController} when starting a new foreground user, and,
369 * unlike {@link #stopLockTaskMode(TaskRecord, boolean, int)}, it doesn't perform the checks.
370 */
371 void clearLockedTasks(String reason) {
372 if (DEBUG_LOCKTASK) Slog.i(TAG_LOCKTASK, "clearLockedTasks: " + reason);
373 if (!mLockTaskModeTasks.isEmpty()) {
374 clearLockedTask(mLockTaskModeTasks.get(0));
375 }
376 }
377
378 /**
379 * Clear one locked task from LockTask mode.
380 *
381 * If the requested task is the root task (see {@link #mLockTaskModeTasks}), then all locked
382 * tasks are cleared. Otherwise, only the requested task is cleared. LockTask mode is stopped
383 * when the last locked task is cleared.
384 *
385 * @param task the task to be cleared from LockTask mode.
386 */
387 void clearLockedTask(final TaskRecord task) {
388 if (task == null || mLockTaskModeTasks.isEmpty()) return;
389
390 if (task == mLockTaskModeTasks.get(0)) {
391 // We're removing the root task while there are other locked tasks. Therefore we should
392 // clear all locked tasks in reverse order.
393 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx > 0; --taskNdx) {
394 clearLockedTask(mLockTaskModeTasks.get(taskNdx));
395 }
396 }
397
398 removeLockedTask(task);
399 if (mLockTaskModeTasks.isEmpty()) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100400 return;
401 }
Charles Heff9b4dff2017-09-22 10:18:37 +0100402 task.performClearTaskLocked();
403 mSupervisor.resumeFocusedStackTopActivityLocked();
Benjamin Franza83859f2017-07-03 16:34:14 +0100404 }
405
406 /**
407 * Remove the given task from the locked task list. If this was the last task in the list,
408 * lock task mode is stopped.
409 */
Charles Heff9b4dff2017-09-22 10:18:37 +0100410 private void removeLockedTask(final TaskRecord task) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100411 if (!mLockTaskModeTasks.remove(task)) {
412 return;
413 }
Charles Heff9b4dff2017-09-22 10:18:37 +0100414 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: removed " + task);
Benjamin Franza83859f2017-07-03 16:34:14 +0100415 if (mLockTaskModeTasks.isEmpty()) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100416 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
417 " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
418 mHandler.post(() -> performStopLockTask(task.userId));
419 }
420 }
421
Benjamin Franza83859f2017-07-03 16:34:14 +0100422 // This method should only be called on the handler thread
423 private void performStopLockTask(int userId) {
424 // When lock task ends, we enable the status bars.
425 try {
Charles Hee078db72017-10-19 18:03:20 +0100426 setStatusBarState(LOCK_TASK_MODE_NONE, userId);
427 setKeyguardState(LOCK_TASK_MODE_NONE, userId);
428 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
429 lockKeyguardIfNeeded();
Benjamin Franza83859f2017-07-03 16:34:14 +0100430 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100431 if (getDevicePolicyManager() != null) {
432 getDevicePolicyManager().notifyLockTaskModeChanged(false, null, userId);
433 }
Charles Hebfe82d12017-10-20 11:59:44 +0100434 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
435 getLockTaskNotify().showPinningExitToast();
436 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100437 } catch (RemoteException ex) {
438 throw new RuntimeException(ex);
439 } finally {
440 mLockTaskModeState = LOCK_TASK_MODE_NONE;
441 }
442 }
443
444 /**
Charles Hebfe82d12017-10-20 11:59:44 +0100445 * Show the lock task violation toast. Currently we only show toast for screen pinning mode, and
446 * no-op if the device is in locked mode.
Benjamin Franza83859f2017-07-03 16:34:14 +0100447 */
448 void showLockTaskToast() {
Charles Hebfe82d12017-10-20 11:59:44 +0100449 if (mLockTaskModeState == LOCK_TASK_MODE_PINNED) {
450 mHandler.post(() -> getLockTaskNotify().showEscapeToast());
451 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100452 }
453
454 // Starting lock task
455
456 /**
457 * Method to start lock task mode on a given task.
458 *
459 * @param task the task that should be locked.
Charles Heff9b4dff2017-09-22 10:18:37 +0100460 * @param isSystemCaller indicates whether this request was initiated by the system via
461 * {@link ActivityManagerService#startSystemLockTaskMode(int)}. If
462 * {@code true}, this intends to start pinned mode; otherwise, we look
463 * at the calling task's mLockTaskAuth to decide which mode to start.
Benjamin Franza83859f2017-07-03 16:34:14 +0100464 * @param callingUid the caller that requested the launch of lock task mode.
465 */
Charles Heff9b4dff2017-09-22 10:18:37 +0100466 void startLockTaskMode(@NonNull TaskRecord task, boolean isSystemCaller, int callingUid) {
467 if (!isSystemCaller) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100468 task.mLockTaskUid = callingUid;
469 if (task.mLockTaskAuth == LOCK_TASK_AUTH_PINNABLE) {
470 // startLockTask() called by app, but app is not part of lock task whitelist. Show
Charles Heff9b4dff2017-09-22 10:18:37 +0100471 // app pinning request. We will come back here with isSystemCaller true.
Benjamin Franza83859f2017-07-03 16:34:14 +0100472 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Mode default, asking user");
473 StatusBarManagerInternal statusBarManager = LocalServices.getService(
474 StatusBarManagerInternal.class);
475 if (statusBarManager != null) {
476 statusBarManager.showScreenPinningRequest(task.taskId);
477 }
478 return;
479 }
480 }
481
482 // System can only initiate screen pinning, not full lock task mode
Charles Heff9b4dff2017-09-22 10:18:37 +0100483 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
484 isSystemCaller ? "Locking pinned" : "Locking fully");
485 setLockTaskMode(task, isSystemCaller ? LOCK_TASK_MODE_PINNED : LOCK_TASK_MODE_LOCKED,
Benjamin Franza83859f2017-07-03 16:34:14 +0100486 "startLockTask", true);
487 }
488
489 /**
490 * Start lock task mode on the given task.
491 * @param lockTaskModeState whether fully locked or pinned mode.
492 * @param andResume whether the task should be brought to foreground as part of the operation.
493 */
494 private void setLockTaskMode(@NonNull TaskRecord task, int lockTaskModeState,
495 String reason, boolean andResume) {
496 // Should have already been checked, but do it again.
497 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
498 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
499 "setLockTaskMode: Can't lock due to auth");
500 return;
501 }
502 if (isLockTaskModeViolation(task)) {
503 Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
504 return;
505 }
506
507 if (mLockTaskModeTasks.isEmpty()) {
Charles Hed62f9652017-11-01 10:05:51 +0000508 mSupervisor.mRecentTasks.onLockTaskModeStateChanged(lockTaskModeState, task.userId);
Benjamin Franza83859f2017-07-03 16:34:14 +0100509 // Start lock task on the handler thread
510 mHandler.post(() -> performStartLockTask(
511 task.intent.getComponent().getPackageName(),
512 task.userId,
513 lockTaskModeState));
514 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100515 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskMode: Locking to " + task +
516 " Callers=" + Debug.getCallers(4));
Charles Heff9b4dff2017-09-22 10:18:37 +0100517
518 if (!mLockTaskModeTasks.contains(task)) {
519 mLockTaskModeTasks.add(task);
520 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100521
522 if (task.mLockTaskUid == -1) {
523 task.mLockTaskUid = task.effectiveUid;
524 }
525
526 if (andResume) {
Wale Ogunwale66e16852017-10-19 13:35:52 -0700527 mSupervisor.findTaskToMoveToFront(task, 0, null, reason,
Benjamin Franza83859f2017-07-03 16:34:14 +0100528 lockTaskModeState != LOCK_TASK_MODE_NONE);
529 mSupervisor.resumeFocusedStackTopActivityLocked();
530 mWindowManager.executeAppTransition();
531 } else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
Wale Ogunwale0568aed2017-09-08 13:29:37 -0700532 mSupervisor.handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED,
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -0700533 DEFAULT_DISPLAY, task.getStack(), true /* forceNonResizable */);
Benjamin Franza83859f2017-07-03 16:34:14 +0100534 }
535 }
536
537 // This method should only be called on the handler thread
538 private void performStartLockTask(String packageName, int userId, int lockTaskModeState) {
539 // When lock task starts, we disable the status bars.
540 try {
Charles Hebfe82d12017-10-20 11:59:44 +0100541 if (lockTaskModeState == LOCK_TASK_MODE_PINNED) {
542 getLockTaskNotify().showPinningStartToast();
543 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100544 mLockTaskModeState = lockTaskModeState;
Charles Hee078db72017-10-19 18:03:20 +0100545 setStatusBarState(lockTaskModeState, userId);
546 setKeyguardState(lockTaskModeState, userId);
Benjamin Franza83859f2017-07-03 16:34:14 +0100547 if (getDevicePolicyManager() != null) {
548 getDevicePolicyManager().notifyLockTaskModeChanged(true, packageName, userId);
549 }
550 } catch (RemoteException ex) {
551 throw new RuntimeException(ex);
552 }
553 }
554
555 /**
Charles He520b2832017-09-02 15:27:16 +0100556 * Update packages that are allowed to be launched in lock task mode.
557 * @param userId Which user this whitelist is associated with
558 * @param packages The whitelist of packages allowed in lock task mode
559 * @see #mLockTaskPackages
Benjamin Franza83859f2017-07-03 16:34:14 +0100560 */
Charles He520b2832017-09-02 15:27:16 +0100561 void updateLockTaskPackages(int userId, String[] packages) {
562 mLockTaskPackages.put(userId, packages);
563
564 boolean taskChanged = false;
Benjamin Franza83859f2017-07-03 16:34:14 +0100565 for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) {
566 final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx);
Charles He520b2832017-09-02 15:27:16 +0100567 final boolean wasWhitelisted = lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
568 || lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED;
Benjamin Franza83859f2017-07-03 16:34:14 +0100569 lockedTask.setLockTaskAuth();
Charles He520b2832017-09-02 15:27:16 +0100570 final boolean isWhitelisted = lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
571 || lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED;
572
573 if (mLockTaskModeState != LOCK_TASK_MODE_LOCKED
574 || lockedTask.userId != userId
575 || !wasWhitelisted || isWhitelisted) {
576 continue;
Benjamin Franza83859f2017-07-03 16:34:14 +0100577 }
Charles He520b2832017-09-02 15:27:16 +0100578
579 // Terminate locked tasks that have recently lost whitelist authorization.
580 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "onLockTaskPackagesUpdated: removing " +
581 lockedTask + " mLockTaskAuth()=" + lockedTask.lockTaskAuthToString());
582 removeLockedTask(lockedTask);
583 lockedTask.performClearTaskLocked();
584 taskChanged = true;
Benjamin Franza83859f2017-07-03 16:34:14 +0100585 }
586
587 for (int displayNdx = mSupervisor.getChildCount() - 1; displayNdx >= 0; --displayNdx) {
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -0700588 mSupervisor.getChildAt(displayNdx).onLockTaskPackagesUpdated();
Benjamin Franza83859f2017-07-03 16:34:14 +0100589 }
Charles He520b2832017-09-02 15:27:16 +0100590
Benjamin Franza83859f2017-07-03 16:34:14 +0100591 final ActivityRecord r = mSupervisor.topRunningActivityLocked();
Charles He520b2832017-09-02 15:27:16 +0100592 final TaskRecord task = (r != null) ? r.getTask() : null;
593 if (mLockTaskModeTasks.isEmpty() && task!= null
Benjamin Franza83859f2017-07-03 16:34:14 +0100594 && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) {
595 // This task must have just been authorized.
596 if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK,
597 "onLockTaskPackagesUpdated: starting new locktask task=" + task);
Charles He520b2832017-09-02 15:27:16 +0100598 setLockTaskMode(task, LOCK_TASK_MODE_LOCKED, "package updated", false);
599 taskChanged = true;
Benjamin Franza83859f2017-07-03 16:34:14 +0100600 }
Charles He520b2832017-09-02 15:27:16 +0100601
602 if (taskChanged) {
Benjamin Franza83859f2017-07-03 16:34:14 +0100603 mSupervisor.resumeFocusedStackTopActivityLocked();
604 }
605 }
606
Charles He520b2832017-09-02 15:27:16 +0100607 boolean isPackageWhitelisted(int userId, String pkg) {
608 if (pkg == null) {
609 return false;
610 }
611 String[] whitelist;
612 whitelist = mLockTaskPackages.get(userId);
613 if (whitelist == null) {
614 return false;
615 }
616 for (String whitelistedPkg : whitelist) {
617 if (pkg.equals(whitelistedPkg)) {
618 return true;
619 }
620 }
621 return false;
622 }
623
Benjamin Franza83859f2017-07-03 16:34:14 +0100624 /**
Charles Hee078db72017-10-19 18:03:20 +0100625 * Update the UI features that are enabled for LockTask mode.
626 * @param userId Which user these feature flags are associated with
627 * @param flags Bitfield of feature flags
628 * @see DevicePolicyManager#setLockTaskFeatures(ComponentName, int)
629 */
630 void updateLockTaskFeatures(int userId, int flags) {
631 int oldFlags = getLockTaskFeaturesForUser(userId);
632 if (flags == oldFlags) {
633 return;
634 }
635
636 mLockTaskFeatures.put(userId, flags);
Charles Heff9b4dff2017-09-22 10:18:37 +0100637 if (!mLockTaskModeTasks.isEmpty() && userId == mLockTaskModeTasks.get(0).userId) {
Charles Hee078db72017-10-19 18:03:20 +0100638 mHandler.post(() -> {
639 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
640 setStatusBarState(mLockTaskModeState, userId);
641 setKeyguardState(mLockTaskModeState, userId);
642 }
643 });
644 }
645 }
646
647 /**
648 * Helper method for configuring the status bar disabled state.
649 * Should only be called on the handler thread to avoid race.
650 */
651 private void setStatusBarState(int lockTaskModeState, int userId) {
652 IStatusBarService statusBar = getStatusBarService();
653 if (statusBar == null) {
654 Slog.e(TAG, "Can't find StatusBarService");
655 return;
656 }
657
658 // Default state, when lockTaskModeState == LOCK_TASK_MODE_NONE
659 int flags1 = StatusBarManager.DISABLE_NONE;
660 int flags2 = StatusBarManager.DISABLE2_NONE;
661
662 if (lockTaskModeState == LOCK_TASK_MODE_PINNED) {
663 flags1 = STATUS_BAR_MASK_PINNED;
664
665 } else if (lockTaskModeState == LOCK_TASK_MODE_LOCKED) {
666 int lockTaskFeatures = getLockTaskFeaturesForUser(userId);
667 Pair<Integer, Integer> statusBarFlags = getStatusBarDisableFlags(lockTaskFeatures);
668 flags1 = statusBarFlags.first;
669 flags2 = statusBarFlags.second;
670 }
671
672 try {
673 statusBar.disable(flags1, mToken, mContext.getPackageName());
674 statusBar.disable2(flags2, mToken, mContext.getPackageName());
675 } catch (RemoteException e) {
676 Slog.e(TAG, "Failed to set status bar flags", e);
677 }
678 }
679
680 /**
681 * Helper method for configuring the keyguard disabled state.
682 * Should only be called on the handler thread to avoid race.
683 */
684 private void setKeyguardState(int lockTaskModeState, int userId) {
685 if (lockTaskModeState == LOCK_TASK_MODE_NONE) {
686 mWindowManager.reenableKeyguard(mToken);
687
688 } else if (lockTaskModeState == LOCK_TASK_MODE_LOCKED) {
689 int lockTaskFeatures = getLockTaskFeaturesForUser(userId);
690 if ((DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD & lockTaskFeatures) == 0) {
691 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
692 } else {
693 mWindowManager.reenableKeyguard(mToken);
694 }
695
696 } else { // lockTaskModeState == LOCK_TASK_MODE_PINNED
697 mWindowManager.disableKeyguard(mToken, LOCK_TASK_TAG);
698 }
699 }
700
701 /**
702 * Helper method for locking the device immediately. This may be necessary when the device
703 * leaves the pinned mode.
704 */
705 private void lockKeyguardIfNeeded() {
706 try {
707 boolean shouldLockKeyguard = Settings.Secure.getIntForUser(
708 mContext.getContentResolver(),
709 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED,
710 USER_CURRENT) != 0;
711 if (shouldLockKeyguard) {
712 mWindowManager.lockNow(null);
713 mWindowManager.dismissKeyguard(null /* callback */);
714 getLockPatternUtils().requireCredentialEntry(USER_ALL);
715 }
716 } catch (Settings.SettingNotFoundException e) {
717 // No setting, don't lock.
718 }
719 }
720
721 /**
722 * Translates from LockTask feature flags to StatusBarManager disable and disable2 flags.
723 * @param lockTaskFlags Bitfield of flags as per
724 * {@link DevicePolicyManager#setLockTaskFeatures(ComponentName, int)}
725 * @return A {@link Pair} of {@link StatusBarManager#disable(int)} and
726 * {@link StatusBarManager#disable2(int)} flags
727 */
728 @VisibleForTesting
729 Pair<Integer, Integer> getStatusBarDisableFlags(int lockTaskFlags) {
730 // Everything is disabled by default
731 int flags1 = StatusBarManager.DISABLE_MASK;
732 int flags2 = StatusBarManager.DISABLE2_MASK;
733 for (int i = STATUS_BAR_FLAG_MAP_LOCKED.size() - 1; i >= 0; i--) {
734 Pair<Integer, Integer> statusBarFlags = STATUS_BAR_FLAG_MAP_LOCKED.valueAt(i);
735 if ((STATUS_BAR_FLAG_MAP_LOCKED.keyAt(i) & lockTaskFlags) != 0) {
736 flags1 &= ~statusBarFlags.first;
737 flags2 &= ~statusBarFlags.second;
738 }
739 }
740 // Some flags are not used for LockTask purposes, so we mask them
741 flags1 &= STATUS_BAR_MASK_LOCKED;
742 return new Pair<>(flags1, flags2);
743 }
744
745 /**
746 * Gets the cached value of LockTask feature flags for a specific user.
747 */
748 private int getLockTaskFeaturesForUser(int userId) {
749 return mLockTaskFeatures.get(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
750 }
751
Benjamin Franza83859f2017-07-03 16:34:14 +0100752 // Should only be called on the handler thread
753 @Nullable
754 private IStatusBarService getStatusBarService() {
755 if (mStatusBarService == null) {
756 mStatusBarService = IStatusBarService.Stub.asInterface(
757 ServiceManager.checkService(STATUS_BAR_SERVICE));
758 if (mStatusBarService == null) {
759 Slog.w("StatusBarManager", "warning: no STATUS_BAR_SERVICE");
760 }
761 }
762 return mStatusBarService;
763 }
764
765 // Should only be called on the handler thread
766 @Nullable
767 private IDevicePolicyManager getDevicePolicyManager() {
768 if (mDevicePolicyManager == null) {
769 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
770 ServiceManager.checkService(DEVICE_POLICY_SERVICE));
771 if (mDevicePolicyManager == null) {
772 Slog.w(TAG, "warning: no DEVICE_POLICY_SERVICE");
773 }
774 }
775 return mDevicePolicyManager;
776 }
777
778 @NonNull
779 private LockPatternUtils getLockPatternUtils() {
780 if (mLockPatternUtils == null) {
781 // We don't preserve the LPU object to save memory
782 return new LockPatternUtils(mContext);
783 }
784 return mLockPatternUtils;
785 }
786
787 // Should only be called on the handler thread
788 @NonNull
789 private LockTaskNotify getLockTaskNotify() {
790 if (mLockTaskNotify == null) {
791 mLockTaskNotify = new LockTaskNotify(mContext);
792 }
793 return mLockTaskNotify;
794 }
795
796 public void dump(PrintWriter pw, String prefix) {
Charles He520b2832017-09-02 15:27:16 +0100797 pw.println(prefix + "LockTaskController");
798 prefix = prefix + " ";
799 pw.println(prefix + "mLockTaskModeState=" + lockTaskModeToString());
800 pw.println(prefix + "mLockTaskModeTasks=");
801 for (int i = 0; i < mLockTaskModeTasks.size(); ++i) {
802 pw.println(prefix + " #" + i + " " + mLockTaskModeTasks.get(i));
803 }
804 pw.println(prefix + "mLockTaskPackages (userId:packages)=");
805 for (int i = 0; i < mLockTaskPackages.size(); ++i) {
806 pw.println(prefix + " u" + mLockTaskPackages.keyAt(i)
807 + ":" + Arrays.toString(mLockTaskPackages.valueAt(i)));
808 }
Benjamin Franza83859f2017-07-03 16:34:14 +0100809 }
810
811 private String lockTaskModeToString() {
812 switch (mLockTaskModeState) {
813 case LOCK_TASK_MODE_LOCKED:
814 return "LOCKED";
815 case LOCK_TASK_MODE_PINNED:
816 return "PINNED";
817 case LOCK_TASK_MODE_NONE:
818 return "NONE";
819 default: return "unknown=" + mLockTaskModeState;
820 }
821 }
822}