2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 package com.android.server.am;
19 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
21 import static android.app.ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED;
22 import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
23 import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
24 import static android.app.ActivityManager.USER_OP_IS_CURRENT;
25 import static android.app.ActivityManager.USER_OP_SUCCESS;
26 import static android.content.Context.KEYGUARD_SERVICE;
27 import static android.os.Process.SYSTEM_UID;
29 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
30 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
31 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
32 import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
33 import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
34 import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
35 import static com.android.server.am.ActivityManagerService.MY_PID;
36 import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
37 import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
38 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
39 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
40 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
41 import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
42 import static com.android.server.am.UserState.STATE_BOOTING;
43 import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
44 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
45 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
47 import android.annotation.NonNull;
48 import android.annotation.UserIdInt;
49 import android.app.ActivityManager;
50 import android.app.AppOpsManager;
51 import android.app.Dialog;
52 import android.app.IStopUserCallback;
53 import android.app.IUserSwitchObserver;
54 import android.app.KeyguardManager;
55 import android.content.Context;
56 import android.content.IIntentReceiver;
57 import android.content.Intent;
58 import android.content.pm.PackageManager;
59 import android.content.pm.UserInfo;
60 import android.os.BatteryStats;
61 import android.os.Binder;
62 import android.os.Build;
63 import android.os.Bundle;
64 import android.os.Debug;
65 import android.os.Handler;
66 import android.os.IBinder;
67 import android.os.IProgressListener;
68 import android.os.IRemoteCallback;
69 import android.os.IUserManager;
70 import android.os.Process;
71 import android.os.RemoteCallbackList;
72 import android.os.RemoteException;
73 import android.os.ServiceManager;
74 import android.os.UserHandle;
75 import android.os.UserManager;
76 import android.os.UserManagerInternal;
77 import android.os.storage.IMountService;
78 import android.os.storage.StorageManager;
79 import android.util.IntArray;
80 import android.util.Pair;
81 import android.util.Slog;
82 import android.util.SparseArray;
83 import android.util.SparseIntArray;
85 import com.android.internal.R;
86 import com.android.internal.annotations.GuardedBy;
87 import com.android.internal.util.ArrayUtils;
88 import com.android.internal.widget.LockPatternUtils;
89 import com.android.server.LocalServices;
90 import com.android.server.pm.UserManagerService;
92 import java.io.PrintWriter;
93 import java.util.ArrayList;
94 import java.util.Arrays;
95 import java.util.HashSet;
96 import java.util.List;
97 import java.util.Objects;
101 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
103 final class UserController {
104 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
106 // Maximum number of users we allow to be running at a time.
107 static final int MAX_RUNNING_USERS = 3;
109 // Amount of time we wait for observers to handle a user switch before
110 // giving up on them and unfreezing the screen.
111 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
113 private final ActivityManagerService mService;
114 private final Handler mHandler;
116 // Holds the current foreground user's id
117 private int mCurrentUserId = UserHandle.USER_SYSTEM;
118 // Holds the target user's id during a user switch
119 private int mTargetUserId = UserHandle.USER_NULL;
122 * Which users have been started, so are allowed to run code.
124 @GuardedBy("mService")
125 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
128 * LRU list of history of current users. Most recently current is at the end.
130 private final ArrayList<Integer> mUserLru = new ArrayList<>();
133 * Constant array of the users that are currently started.
135 private int[] mStartedUserArray = new int[] { 0 };
137 // If there are multiple profiles for the current user, their ids are here
138 // Currently only the primary user can have managed profiles
139 private int[] mCurrentProfileIds = new int[] {};
142 * Mapping from each known user ID to the profile group ID it is associated with.
144 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
147 * Registered observers of the user switching mechanics.
149 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
150 = new RemoteCallbackList<>();
153 * Currently active user switch.
155 Object mCurUserSwitchCallback;
157 private volatile UserManagerService mUserManager;
159 private final LockPatternUtils mLockPatternUtils;
161 private UserManagerInternal mUserManagerInternal;
163 UserController(ActivityManagerService service) {
165 mHandler = mService.mHandler;
166 // User 0 is the first and only user that runs at boot.
167 final UserState uss = new UserState(UserHandle.SYSTEM);
168 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
169 mUserLru.add(UserHandle.USER_SYSTEM);
170 mLockPatternUtils = new LockPatternUtils(mService.mContext);
171 updateStartedUserArrayLocked();
174 void finishUserSwitch(UserState uss) {
175 synchronized (mService) {
178 startProfilesLocked();
179 stopRunningUsersLocked(MAX_RUNNING_USERS);
183 void stopRunningUsersLocked(int maxRunningUsers) {
184 int num = mUserLru.size();
186 while (num > maxRunningUsers && i < mUserLru.size()) {
187 Integer oldUserId = mUserLru.get(i);
188 UserState oldUss = mStartedUsers.get(oldUserId);
189 if (oldUss == null) {
190 // Shouldn't happen, but be sane if it does.
195 if (oldUss.state == UserState.STATE_STOPPING
196 || oldUss.state == UserState.STATE_SHUTDOWN) {
197 // This user is already stopping, doesn't count.
202 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
203 // Owner/System user and current user can't be stopped. We count it as running
204 // when it is not a pure system user.
205 if (UserInfo.isSystemOnly(oldUserId)) {
211 // This is a user to be stopped.
212 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
220 private void finishUserBoot(UserState uss) {
221 finishUserBoot(uss, null);
224 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
225 final int userId = uss.mHandle.getIdentifier();
226 Slog.d(TAG, "Finishing user boot " + userId);
227 synchronized (mService) {
228 // Bail if we ended up with a stale user
229 if (mStartedUsers.get(userId) != uss) return;
231 // We always walk through all the user lifecycle states to send
232 // consistent developer events. We step into RUNNING_LOCKED here,
233 // but we might immediately step into RUNNING below if the user
234 // storage is already unlocked.
235 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
236 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
237 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
238 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
239 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
240 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
241 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
242 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
245 // We need to delay unlocking managed profiles until the parent user
247 if (getUserManager().isManagedProfile(userId)) {
248 final UserInfo parent = getUserManager().getProfileParent(userId);
250 && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
251 Slog.d(TAG, "User " + userId + " (parent " + parent.id
252 + "): attempting unlock because parent is unlocked");
253 maybeUnlockUser(userId);
255 String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
256 Slog.d(TAG, "User " + userId + " (parent " + parentId
257 + "): delaying unlock because parent is locked");
260 maybeUnlockUser(userId);
266 * Step from {@link UserState#STATE_RUNNING_LOCKED} to
267 * {@link UserState#STATE_RUNNING_UNLOCKING}.
269 private void finishUserUnlocking(final UserState uss) {
270 final int userId = uss.mHandle.getIdentifier();
271 synchronized (mService) {
272 // Bail if we ended up with a stale user
273 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
275 // Only keep marching forward if user is actually unlocked
276 if (!StorageManager.isUserKeyUnlocked(userId)) return;
278 if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
279 getUserManagerInternal().setUserUnlockingOrUnlocked(userId, true);
280 uss.mUnlockProgress.start();
282 // Prepare app storage before we go any further
283 uss.mUnlockProgress.setProgress(5,
284 mService.mContext.getString(R.string.android_start_title));
285 mUserManager.onBeforeUnlockUser(userId);
286 uss.mUnlockProgress.setProgress(20);
288 // Dispatch unlocked to system services; when fully dispatched,
289 // that calls through to the next "unlocked" phase
290 mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
297 * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
298 * {@link UserState#STATE_RUNNING_UNLOCKED}.
300 void finishUserUnlocked(final UserState uss) {
301 final int userId = uss.mHandle.getIdentifier();
302 synchronized (mService) {
303 // Bail if we ended up with a stale user
304 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
306 // Only keep marching forward if user is actually unlocked
307 if (!StorageManager.isUserKeyUnlocked(userId)) return;
309 if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
310 getUserManagerInternal().setUserUnlockingOrUnlocked(userId, true);
311 uss.mUnlockProgress.finish();
313 // Dispatch unlocked to external apps
314 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
315 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
316 unlockedIntent.addFlags(
317 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
318 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
319 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
322 if (getUserInfo(userId).isManagedProfile()) {
323 UserInfo parent = getUserManager().getProfileParent(userId);
324 if (parent != null) {
325 final Intent profileUnlockedIntent = new Intent(
326 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
327 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
328 profileUnlockedIntent.addFlags(
329 Intent.FLAG_RECEIVER_REGISTERED_ONLY
330 | Intent.FLAG_RECEIVER_FOREGROUND);
331 mService.broadcastIntentLocked(null, null, profileUnlockedIntent,
332 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
333 null, false, false, MY_PID, SYSTEM_UID,
338 // Send PRE_BOOT broadcasts if user fingerprint changed; we
339 // purposefully block sending BOOT_COMPLETED until after all
340 // PRE_BOOT receivers are finished to avoid ANR'ing apps
341 final UserInfo info = getUserInfo(userId);
342 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
343 new PreBootBroadcaster(mService, userId, null) {
345 public void onFinished() {
346 finishUserUnlockedCompleted(uss);
350 finishUserUnlockedCompleted(uss);
356 private void finishUserUnlockedCompleted(UserState uss) {
357 final int userId = uss.mHandle.getIdentifier();
358 synchronized (mService) {
359 // Bail if we ended up with a stale user
360 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
361 final UserInfo userInfo = getUserInfo(userId);
362 if (userInfo == null) {
366 // Only keep marching forward if user is actually unlocked
367 if (!StorageManager.isUserKeyUnlocked(userId)) return;
369 // Remember that we logged in
370 mUserManager.onUserLoggedIn(userId);
372 if (!userInfo.isInitialized()) {
373 if (userId != UserHandle.USER_SYSTEM) {
374 Slog.d(TAG, "Initializing user #" + userId);
375 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
376 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
377 mService.broadcastIntentLocked(null, null, intent, null,
378 new IIntentReceiver.Stub() {
380 public void performReceive(Intent intent, int resultCode,
381 String data, Bundle extras, boolean ordered,
382 boolean sticky, int sendingUser) {
383 // Note: performReceive is called with mService lock held
384 getUserManager().makeInitialized(userInfo.id);
386 }, 0, null, null, null, AppOpsManager.OP_NONE,
387 null, true, false, MY_PID, SYSTEM_UID, userId);
391 Slog.d(TAG, "Sending BOOT_COMPLETE user #" + userId);
392 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
393 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
394 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
395 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
396 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
397 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
398 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
402 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
403 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
404 != PackageManager.PERMISSION_GRANTED) {
405 String msg = "Permission Denial: switchUser() from pid="
406 + Binder.getCallingPid()
407 + ", uid=" + Binder.getCallingUid()
408 + " requires " + INTERACT_ACROSS_USERS_FULL;
410 throw new SecurityException(msg);
412 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
413 throw new IllegalArgumentException("Can't stop system user " + userId);
415 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
417 synchronized (mService) {
418 return stopUsersLocked(userId, force, callback);
423 * Stops the user along with its related users. The method calls
424 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
426 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
427 if (userId == UserHandle.USER_SYSTEM) {
428 return USER_OP_ERROR_IS_SYSTEM;
430 if (isCurrentUserLocked(userId)) {
431 return USER_OP_IS_CURRENT;
433 int[] usersToStop = getUsersToStopLocked(userId);
434 // If one of related users is system or current, no related users should be stopped
435 for (int i = 0; i < usersToStop.length; i++) {
436 int relatedUserId = usersToStop[i];
437 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
438 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
440 // We still need to stop the requested user if it's a force stop.
443 "Force stop user " + userId + ". Related users will not be stopped");
444 stopSingleUserLocked(userId, callback);
445 return USER_OP_SUCCESS;
447 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
450 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
451 for (int userIdToStop : usersToStop) {
452 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
454 return USER_OP_SUCCESS;
457 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
458 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
459 final UserState uss = mStartedUsers.get(userId);
461 // User is not started, nothing to do... but we do need to
462 // callback if requested.
463 if (callback != null) {
464 mHandler.post(new Runnable() {
468 callback.userStopped(userId);
469 } catch (RemoteException e) {
477 if (callback != null) {
478 uss.mStopCallbacks.add(callback);
481 if (uss.state != UserState.STATE_STOPPING
482 && uss.state != UserState.STATE_SHUTDOWN) {
483 uss.setState(UserState.STATE_STOPPING);
484 getUserManagerInternal().setUserUnlockingOrUnlocked(userId, false);
485 updateStartedUserArrayLocked();
487 long ident = Binder.clearCallingIdentity();
489 // We are going to broadcast ACTION_USER_STOPPING and then
490 // once that is done send a final ACTION_SHUTDOWN and then
492 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
493 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
494 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
495 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
496 // This is the result receiver for the initial stopping broadcast.
497 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
499 public void performReceive(Intent intent, int resultCode, String data,
500 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
501 mHandler.post(new Runnable() {
504 finishUserStopping(userId, uss);
509 // Clear broadcast queue for the user to avoid delivering stale broadcasts
510 mService.clearBroadcastQueueForUserLocked(userId);
512 mService.broadcastIntentLocked(null, null, stoppingIntent,
513 null, stoppingReceiver, 0, null, null,
514 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
515 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
517 Binder.restoreCallingIdentity(ident);
522 void finishUserStopping(final int userId, final UserState uss) {
524 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
525 // This is the result receiver for the final shutdown broadcast.
526 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
528 public void performReceive(Intent intent, int resultCode, String data,
529 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
530 mHandler.post(new Runnable() {
533 finishUserStopped(uss);
539 synchronized (mService) {
540 if (uss.state != UserState.STATE_STOPPING) {
541 // Whoops, we are being started back up. Abort, abort!
544 uss.setState(UserState.STATE_SHUTDOWN);
546 getUserManagerInternal().setUserUnlockingOrUnlocked(userId, false);
548 mService.mBatteryStatsService.noteEvent(
549 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
550 Integer.toString(userId), userId);
551 mService.mSystemServiceManager.stopUser(userId);
553 synchronized (mService) {
554 mService.broadcastIntentLocked(null, null, shutdownIntent,
555 null, shutdownReceiver, 0, null, null, null,
556 AppOpsManager.OP_NONE,
557 null, true, false, MY_PID, SYSTEM_UID, userId);
561 void finishUserStopped(UserState uss) {
562 final int userId = uss.mHandle.getIdentifier();
564 ArrayList<IStopUserCallback> callbacks;
565 synchronized (mService) {
566 callbacks = new ArrayList<>(uss.mStopCallbacks);
567 if (mStartedUsers.get(userId) != uss) {
569 } else if (uss.state != UserState.STATE_SHUTDOWN) {
573 // User can no longer run.
574 mStartedUsers.remove(userId);
575 mUserLru.remove(Integer.valueOf(userId));
576 updateStartedUserArrayLocked();
578 mService.onUserStoppedLocked(userId);
579 // Clean up all state and processes associated with the user.
580 // Kill all the processes for the user.
581 forceStopUserLocked(userId, "finish user");
585 for (int i = 0; i < callbacks.size(); i++) {
587 if (stopped) callbacks.get(i).userStopped(userId);
588 else callbacks.get(i).userStopAborted(userId);
589 } catch (RemoteException e) {
594 mService.mSystemServiceManager.cleanupUser(userId);
595 synchronized (mService) {
596 mService.mStackSupervisor.removeUserLocked(userId);
598 // Remove the user if it is ephemeral.
599 if (getUserInfo(userId).isEphemeral()) {
600 mUserManager.removeUser(userId);
606 * Determines the list of users that should be stopped together with the specified
607 * {@code userId}. The returned list includes {@code userId}.
609 private @NonNull int[] getUsersToStopLocked(int userId) {
610 int startedUsersSize = mStartedUsers.size();
611 IntArray userIds = new IntArray();
613 synchronized (mUserProfileGroupIdsSelfLocked) {
614 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
615 UserInfo.NO_PROFILE_GROUP_ID);
616 for (int i = 0; i < startedUsersSize; i++) {
617 UserState uss = mStartedUsers.valueAt(i);
618 int startedUserId = uss.mHandle.getIdentifier();
619 // Skip unrelated users (profileGroupId mismatch)
620 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
621 UserInfo.NO_PROFILE_GROUP_ID);
622 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
623 && (userGroupId == startedUserGroupId);
624 // userId has already been added
625 boolean sameUserId = startedUserId == userId;
626 if (!sameGroup || sameUserId) {
629 userIds.add(startedUserId);
632 return userIds.toArray();
635 private void forceStopUserLocked(int userId, String reason) {
636 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
638 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
639 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
640 | Intent.FLAG_RECEIVER_FOREGROUND);
641 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
642 mService.broadcastIntentLocked(null, null, intent,
643 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
644 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
648 * Stops the guest or ephemeral user if it has gone to the background.
650 private void stopGuestOrEphemeralUserIfBackground() {
651 synchronized (mService) {
652 final int num = mUserLru.size();
653 for (int i = 0; i < num; i++) {
654 Integer oldUserId = mUserLru.get(i);
655 UserState oldUss = mStartedUsers.get(oldUserId);
656 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
657 || oldUss.state == UserState.STATE_STOPPING
658 || oldUss.state == UserState.STATE_SHUTDOWN) {
661 UserInfo userInfo = getUserInfo(oldUserId);
662 if (userInfo.isEphemeral()) {
663 LocalServices.getService(UserManagerInternal.class)
664 .onEphemeralUserStop(oldUserId);
666 if (userInfo.isGuest() || userInfo.isEphemeral()) {
667 // This is a user to be stopped.
668 stopUsersLocked(oldUserId, true, null);
675 void startProfilesLocked() {
676 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
677 List<UserInfo> profiles = getUserManager().getProfiles(
678 mCurrentUserId, false /* enabledOnly */);
679 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
680 for (UserInfo user : profiles) {
681 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
682 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
683 profilesToStart.add(user);
686 final int profilesToStartSize = profilesToStart.size();
688 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
689 startUser(profilesToStart.get(i).id, /* foreground= */ false);
691 if (i < profilesToStartSize) {
692 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
696 private UserManagerService getUserManager() {
697 UserManagerService userManager = mUserManager;
698 if (userManager == null) {
699 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
700 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
705 private IMountService getMountService() {
706 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
710 * Start user, if its not already running.
711 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
712 * When starting the user, multiple intents will be broadcast in the following order:</p>
714 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
715 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
716 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
717 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
718 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
719 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
720 * Sent only if {@code foreground} parameter is true
721 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
723 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
725 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
726 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
727 * new user. Sent only when the user is booting after a system update.
728 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
729 * new user. Sent only the first time a user is starting.
730 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
731 * user. Indicates that the user has finished booting.
734 * @param userId ID of the user to start
735 * @param foreground true if user should be brought to the foreground
736 * @return true if the user has been successfully started
738 boolean startUser(final int userId, final boolean foreground) {
739 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
740 != PackageManager.PERMISSION_GRANTED) {
741 String msg = "Permission Denial: switchUser() from pid="
742 + Binder.getCallingPid()
743 + ", uid=" + Binder.getCallingUid()
744 + " requires " + INTERACT_ACROSS_USERS_FULL;
746 throw new SecurityException(msg);
749 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
751 final long ident = Binder.clearCallingIdentity();
753 synchronized (mService) {
754 final int oldUserId = mCurrentUserId;
755 if (oldUserId == userId) {
759 mService.mStackSupervisor.setLockTaskModeLocked(null,
760 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
762 final UserInfo userInfo = getUserInfo(userId);
763 if (userInfo == null) {
764 Slog.w(TAG, "No user info for user #" + userId);
767 if (foreground && userInfo.isManagedProfile()) {
768 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
773 mService.mWindowManager.startFreezingScreen(
774 R.anim.screen_user_exit, R.anim.screen_user_enter);
777 boolean needStart = false;
779 // If the user we are switching to is not currently started, then
780 // we need to start it now.
781 if (mStartedUsers.get(userId) == null) {
782 mStartedUsers.put(userId, new UserState(UserHandle.of(userId)));
783 updateStartedUserArrayLocked();
787 final UserState uss = mStartedUsers.get(userId);
788 final Integer userIdInt = userId;
789 mUserLru.remove(userIdInt);
790 mUserLru.add(userIdInt);
793 mCurrentUserId = userId;
794 mService.updateUserConfigurationLocked();
795 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
796 updateCurrentProfileIdsLocked();
797 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
798 // Once the internal notion of the active user has switched, we lock the device
799 // with the option to show the user switcher on the keyguard.
800 mService.mWindowManager.lockNow(null);
802 final Integer currentUserIdInt = mCurrentUserId;
803 updateCurrentProfileIdsLocked();
804 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
805 mUserLru.remove(currentUserIdInt);
806 mUserLru.add(currentUserIdInt);
809 // Make sure user is in the started state. If it is currently
810 // stopping, we need to knock that off.
811 if (uss.state == UserState.STATE_STOPPING) {
812 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
813 // so we can just fairly silently bring the user back from
815 uss.setState(uss.lastState);
816 if (isUserRunningLocked(userId, FLAG_AND_UNLOCKING_OR_UNLOCKED)) {
817 getUserManagerInternal().setUserUnlockingOrUnlocked(userId, true);
819 updateStartedUserArrayLocked();
821 } else if (uss.state == UserState.STATE_SHUTDOWN) {
822 // This means ACTION_SHUTDOWN has been sent, so we will
823 // need to treat this as a new boot of the user.
824 uss.setState(UserState.STATE_BOOTING);
825 updateStartedUserArrayLocked();
829 if (uss.state == UserState.STATE_BOOTING) {
830 // Give user manager a chance to propagate user restrictions
831 // to other services and prepare app storage
832 getUserManager().onBeforeStartUser(userId);
834 // Booting up a new user, need to tell system services about it.
835 // Note that this is on the same handler as scheduling of broadcasts,
836 // which is important because it needs to go first.
837 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
841 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
843 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
844 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
845 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
846 oldUserId, userId, uss));
847 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
848 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
852 // Send USER_STARTED broadcast
853 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
854 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
855 | Intent.FLAG_RECEIVER_FOREGROUND);
856 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
857 mService.broadcastIntentLocked(null, null, intent,
858 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
859 null, false, false, MY_PID, SYSTEM_UID, userId);
863 moveUserToForegroundLocked(uss, oldUserId, userId);
865 mService.mUserController.finishUserBoot(uss);
869 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
870 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
871 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
872 mService.broadcastIntentLocked(null, null, intent,
873 null, new IIntentReceiver.Stub() {
875 public void performReceive(Intent intent, int resultCode,
876 String data, Bundle extras, boolean ordered, boolean sticky,
877 int sendingUser) throws RemoteException {
880 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
881 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
885 Binder.restoreCallingIdentity(ident);
892 * Start user, if its not already running, and bring it to foreground.
894 boolean startUserInForeground(final int userId, Dialog dlg) {
895 boolean result = startUser(userId, /* foreground */ true);
900 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
901 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
902 != PackageManager.PERMISSION_GRANTED) {
903 String msg = "Permission Denial: unlockUser() from pid="
904 + Binder.getCallingPid()
905 + ", uid=" + Binder.getCallingUid()
906 + " requires " + INTERACT_ACROSS_USERS_FULL;
908 throw new SecurityException(msg);
911 final long binderToken = Binder.clearCallingIdentity();
913 return unlockUserCleared(userId, token, secret, listener);
915 Binder.restoreCallingIdentity(binderToken);
920 * Attempt to unlock user without a credential token. This typically
921 * succeeds when the device doesn't have credential-encrypted storage, or
922 * when the the credential-encrypted storage isn't tied to a user-provided
925 boolean maybeUnlockUser(final int userId) {
926 // Try unlocking storage using empty token
927 return unlockUserCleared(userId, null, null, null);
930 private static void notifyFinished(int userId, IProgressListener listener) {
931 if (listener == null) return;
933 listener.onFinished(userId, null);
934 } catch (RemoteException ignored) {
938 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
939 IProgressListener listener) {
940 synchronized (mService) {
941 // Bail if user isn't actually running, otherwise register the given
942 // listener to watch for unlock progress
943 final UserState uss = mStartedUsers.get(userId);
945 notifyFinished(userId, listener);
948 uss.mUnlockProgress.addListener(listener);
951 // TODO Move this block outside of synchronized if it causes lock contention
952 if (!StorageManager.isUserKeyUnlocked(userId)) {
953 final UserInfo userInfo = getUserInfo(userId);
954 final IMountService mountService = getMountService();
956 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
957 } catch (RemoteException | RuntimeException e) {
958 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
959 notifyFinished(userId, listener);
964 finishUserUnlocking(uss);
966 // We just unlocked a user, so let's now attempt to unlock any
967 // managed profiles under that user.
968 for (int i = 0; i < mStartedUsers.size(); i++) {
969 final int testUserId = mStartedUsers.keyAt(i);
970 final UserInfo parent = getUserManager().getProfileParent(testUserId);
971 if (parent != null && parent.id == userId && testUserId != userId) {
972 Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
973 + "): attempting unlock because parent was just unlocked");
974 maybeUnlockUser(testUserId);
982 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
983 // The dialog will show and then initiate the user switch by calling startUserInForeground
984 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
985 fromToUserPair.second, true /* above system */);
989 void dispatchForegroundProfileChanged(int userId) {
990 final int observerCount = mUserSwitchObservers.beginBroadcast();
991 for (int i = 0; i < observerCount; i++) {
993 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
994 } catch (RemoteException e) {
998 mUserSwitchObservers.finishBroadcast();
1001 /** Called on handler thread */
1002 void dispatchUserSwitchComplete(int userId) {
1003 final int observerCount = mUserSwitchObservers.beginBroadcast();
1004 for (int i = 0; i < observerCount; i++) {
1006 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
1007 } catch (RemoteException e) {
1010 mUserSwitchObservers.finishBroadcast();
1013 private void stopBackgroundUsersIfEnforced(int oldUserId) {
1014 // Never stop system user
1015 if (oldUserId == UserHandle.USER_SYSTEM) {
1018 // For now, only check for user restriction. Additional checks can be added here
1019 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
1021 if (!disallowRunInBg) {
1024 synchronized (mService) {
1025 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
1026 + " and related users");
1027 stopUsersLocked(oldUserId, false, null);
1031 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
1032 synchronized (mService) {
1033 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
1034 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1038 void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
1039 Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
1040 final int observerCount = mUserSwitchObservers.beginBroadcast();
1041 if (observerCount > 0) {
1042 final IRemoteCallback callback = new IRemoteCallback.Stub() {
1045 public void sendResult(Bundle data) throws RemoteException {
1046 synchronized (mService) {
1047 if (mCurUserSwitchCallback == this) {
1049 if (mCount == observerCount) {
1050 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1056 synchronized (mService) {
1057 uss.switching = true;
1058 mCurUserSwitchCallback = callback;
1060 for (int i = 0; i < observerCount; i++) {
1062 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
1063 newUserId, callback);
1064 } catch (RemoteException e) {
1068 synchronized (mService) {
1069 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1072 mUserSwitchObservers.finishBroadcast();
1075 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1076 mCurUserSwitchCallback = null;
1077 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1078 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1079 oldUserId, newUserId, uss));
1082 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
1083 Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
1084 synchronized (mService) {
1085 mService.mWindowManager.stopFreezingScreen();
1087 uss.switching = false;
1088 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1089 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1091 stopGuestOrEphemeralUserIfBackground();
1092 stopBackgroundUsersIfEnforced(oldUserId);
1095 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1096 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
1098 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
1100 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
1102 EventLogTags.writeAmSwitchUser(newUserId);
1103 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1106 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1107 long ident = Binder.clearCallingIdentity();
1110 if (oldUserId >= 0) {
1111 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1112 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1113 int count = profiles.size();
1114 for (int i = 0; i < count; i++) {
1115 int profileUserId = profiles.get(i).id;
1116 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1117 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1118 | Intent.FLAG_RECEIVER_FOREGROUND);
1119 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1120 mService.broadcastIntentLocked(null, null, intent,
1121 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1122 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1125 if (newUserId >= 0) {
1126 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1127 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1128 int count = profiles.size();
1129 for (int i = 0; i < count; i++) {
1130 int profileUserId = profiles.get(i).id;
1131 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1132 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1133 | Intent.FLAG_RECEIVER_FOREGROUND);
1134 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1135 mService.broadcastIntentLocked(null, null, intent,
1136 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1137 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1139 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1140 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1141 | Intent.FLAG_RECEIVER_FOREGROUND);
1142 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1143 mService.broadcastIntentLocked(null, null, intent,
1144 null, null, 0, null, null,
1145 new String[] {android.Manifest.permission.MANAGE_USERS},
1146 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1147 UserHandle.USER_ALL);
1150 Binder.restoreCallingIdentity(ident);
1155 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1156 int allowMode, String name, String callerPackage) {
1157 final int callingUserId = UserHandle.getUserId(callingUid);
1158 if (callingUserId == userId) {
1162 // Note that we may be accessing mCurrentUserId outside of a lock...
1163 // shouldn't be a big deal, if this is being called outside
1164 // of a locked context there is intrinsically a race with
1165 // the value the caller will receive and someone else changing it.
1166 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1167 // we will switch to the calling user if access to the current user fails.
1168 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1170 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1171 final boolean allow;
1172 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1173 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1174 // If the caller has this permission, they always pass go. And collect $200.
1176 } else if (allowMode == ALLOW_FULL_ONLY) {
1177 // We require full access, sucks to be you.
1179 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1180 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1181 // If the caller does not have either permission, they are always doomed.
1183 } else if (allowMode == ALLOW_NON_FULL) {
1184 // We are blanket allowing non-full access, you lucky caller!
1186 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1187 // We may or may not allow this depending on whether the two users are
1188 // in the same profile.
1189 allow = isSameProfileGroup(callingUserId, targetUserId);
1191 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1194 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1195 // In this case, they would like to just execute as their
1196 // owner user instead of failing.
1197 targetUserId = callingUserId;
1199 StringBuilder builder = new StringBuilder(128);
1200 builder.append("Permission Denial: ");
1201 builder.append(name);
1202 if (callerPackage != null) {
1203 builder.append(" from ");
1204 builder.append(callerPackage);
1206 builder.append(" asks to run as user ");
1207 builder.append(userId);
1208 builder.append(" but is calling from user ");
1209 builder.append(UserHandle.getUserId(callingUid));
1210 builder.append("; this requires ");
1211 builder.append(INTERACT_ACROSS_USERS_FULL);
1212 if (allowMode != ALLOW_FULL_ONLY) {
1213 builder.append(" or ");
1214 builder.append(INTERACT_ACROSS_USERS);
1216 String msg = builder.toString();
1218 throw new SecurityException(msg);
1222 if (!allowAll && targetUserId < 0) {
1223 throw new IllegalArgumentException(
1224 "Call does not support special user #" + targetUserId);
1226 // Check shell permission
1227 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1228 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1229 throw new SecurityException("Shell does not have permission to access user "
1230 + targetUserId + "\n " + Debug.getCallers(3));
1233 return targetUserId;
1236 int unsafeConvertIncomingUserLocked(int userId) {
1237 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1238 ? getCurrentUserIdLocked(): userId;
1241 void registerUserSwitchObserver(IUserSwitchObserver observer) {
1242 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1243 != PackageManager.PERMISSION_GRANTED) {
1244 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1245 + Binder.getCallingPid()
1246 + ", uid=" + Binder.getCallingUid()
1247 + " requires " + INTERACT_ACROSS_USERS_FULL;
1249 throw new SecurityException(msg);
1252 mUserSwitchObservers.register(observer);
1255 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1256 mUserSwitchObservers.unregister(observer);
1259 UserState getStartedUserStateLocked(int userId) {
1260 return mStartedUsers.get(userId);
1263 boolean hasStartedUserState(int userId) {
1264 return mStartedUsers.get(userId) != null;
1267 private void updateStartedUserArrayLocked() {
1269 for (int i = 0; i < mStartedUsers.size(); i++) {
1270 UserState uss = mStartedUsers.valueAt(i);
1271 // This list does not include stopping users.
1272 if (uss.state != UserState.STATE_STOPPING
1273 && uss.state != UserState.STATE_SHUTDOWN) {
1277 mStartedUserArray = new int[num];
1279 for (int i = 0; i < mStartedUsers.size(); i++) {
1280 UserState uss = mStartedUsers.valueAt(i);
1281 if (uss.state != UserState.STATE_STOPPING
1282 && uss.state != UserState.STATE_SHUTDOWN) {
1283 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
1288 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1289 for (int i = 0; i < mStartedUsers.size(); i++) {
1290 UserState uss = mStartedUsers.valueAt(i);
1291 finishUserBoot(uss, resultTo);
1295 void onSystemReady() {
1296 updateCurrentProfileIdsLocked();
1300 * Refreshes the list of users related to the current user when either a
1301 * user switch happens or when a new related user is started in the
1304 private void updateCurrentProfileIdsLocked() {
1305 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
1306 false /* enabledOnly */);
1307 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1308 for (int i = 0; i < currentProfileIds.length; i++) {
1309 currentProfileIds[i] = profiles.get(i).id;
1311 mCurrentProfileIds = currentProfileIds;
1313 synchronized (mUserProfileGroupIdsSelfLocked) {
1314 mUserProfileGroupIdsSelfLocked.clear();
1315 final List<UserInfo> users = getUserManager().getUsers(false);
1316 for (int i = 0; i < users.size(); i++) {
1317 UserInfo user = users.get(i);
1318 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1319 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1325 int[] getStartedUserArrayLocked() {
1326 return mStartedUserArray;
1329 boolean isUserRunningLocked(int userId, int flags) {
1330 UserState state = getStartedUserStateLocked(userId);
1331 if (state == null) {
1334 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
1337 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1338 switch (state.state) {
1339 case UserState.STATE_BOOTING:
1340 case UserState.STATE_RUNNING_LOCKED:
1346 if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
1347 switch (state.state) {
1348 case UserState.STATE_RUNNING_UNLOCKING:
1349 case UserState.STATE_RUNNING_UNLOCKED:
1355 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1356 switch (state.state) {
1357 case UserState.STATE_RUNNING_UNLOCKED:
1364 // One way or another, we're running!
1368 UserInfo getCurrentUser() {
1369 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1370 != PackageManager.PERMISSION_GRANTED) && (
1371 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1372 != PackageManager.PERMISSION_GRANTED)) {
1373 String msg = "Permission Denial: getCurrentUser() from pid="
1374 + Binder.getCallingPid()
1375 + ", uid=" + Binder.getCallingUid()
1376 + " requires " + INTERACT_ACROSS_USERS;
1378 throw new SecurityException(msg);
1380 synchronized (mService) {
1381 return getCurrentUserLocked();
1385 UserInfo getCurrentUserLocked() {
1386 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1387 return getUserInfo(userId);
1390 int getCurrentOrTargetUserIdLocked() {
1391 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1394 int getCurrentUserIdLocked() {
1395 return mCurrentUserId;
1398 private boolean isCurrentUserLocked(int userId) {
1399 return userId == getCurrentOrTargetUserIdLocked();
1402 int setTargetUserIdLocked(int targetUserId) {
1403 return mTargetUserId = targetUserId;
1407 UserManagerService ums = getUserManager();
1408 return ums != null ? ums.getUserIds() : new int[] { 0 };
1411 UserInfo getUserInfo(int userId) {
1412 return getUserManager().getUserInfo(userId);
1415 int[] getUserIds() {
1416 return getUserManager().getUserIds();
1419 boolean exists(int userId) {
1420 return getUserManager().exists(userId);
1423 boolean hasUserRestriction(String restriction, int userId) {
1424 return getUserManager().hasUserRestriction(restriction, userId);
1427 Set<Integer> getProfileIds(int userId) {
1428 Set<Integer> userIds = new HashSet<>();
1429 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1430 false /* enabledOnly */);
1431 for (UserInfo user : profiles) {
1432 userIds.add(user.id);
1437 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1438 synchronized (mUserProfileGroupIdsSelfLocked) {
1439 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1440 UserInfo.NO_PROFILE_GROUP_ID);
1441 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1442 UserInfo.NO_PROFILE_GROUP_ID);
1443 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1444 && callingProfile == targetProfile;
1448 boolean isCurrentProfileLocked(int userId) {
1449 return ArrayUtils.contains(mCurrentProfileIds, userId);
1452 int[] getCurrentProfileIdsLocked() {
1453 return mCurrentProfileIds;
1457 * Returns whether the given user requires credential entry at this time. This is used to
1458 * intercept activity launches for work apps when the Work Challenge is present.
1460 boolean shouldConfirmCredentials(int userId) {
1461 synchronized (mService) {
1462 if (mStartedUsers.get(userId) == null) {
1466 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1469 final KeyguardManager km = (KeyguardManager) mService.mContext
1470 .getSystemService(KEYGUARD_SERVICE);
1471 return km.isDeviceLocked(userId);
1474 boolean isLockScreenDisabled(@UserIdInt int userId) {
1475 return mLockPatternUtils.isLockScreenDisabled(userId);
1478 private UserManagerInternal getUserManagerInternal() {
1479 if (mUserManagerInternal == null) {
1480 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
1482 return mUserManagerInternal;
1485 void dump(PrintWriter pw, boolean dumpAll) {
1486 pw.println(" mStartedUsers:");
1487 for (int i = 0; i < mStartedUsers.size(); i++) {
1488 UserState uss = mStartedUsers.valueAt(i);
1489 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1490 pw.print(": "); uss.dump("", pw);
1492 pw.print(" mStartedUserArray: [");
1493 for (int i = 0; i < mStartedUserArray.length; i++) {
1494 if (i > 0) pw.print(", ");
1495 pw.print(mStartedUserArray[i]);
1498 pw.print(" mUserLru: [");
1499 for (int i = 0; i < mUserLru.size(); i++) {
1500 if (i > 0) pw.print(", ");
1501 pw.print(mUserLru.get(i));
1505 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1507 synchronized (mUserProfileGroupIdsSelfLocked) {
1508 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1509 pw.println(" mUserProfileGroupIds:");
1510 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1511 pw.print(" User #");
1512 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1513 pw.print(" -> profile #");
1514 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));