类android.content.pm.UserInfo源码实例Demo

下面列出了怎么用android.content.pm.UserInfo的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android_9.0.0_r45   文件: UserController.java
/**
 * Stops the guest or ephemeral user if it has gone to the background.
 */
private void stopGuestOrEphemeralUserIfBackground(int oldUserId) {
    if (DEBUG_MU) Slog.i(TAG, "Stop guest or ephemeral user if background: " + oldUserId);
    synchronized(mLock) {
        UserState oldUss = mStartedUsers.get(oldUserId);
        if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId || oldUss == null
                || oldUss.state == UserState.STATE_STOPPING
                || oldUss.state == UserState.STATE_SHUTDOWN) {
            return;
        }
    }

    UserInfo userInfo = getUserInfo(oldUserId);
    if (userInfo.isEphemeral()) {
        LocalServices.getService(UserManagerInternal.class).onEphemeralUserStop(oldUserId);
    }
    if (userInfo.isGuest() || userInfo.isEphemeral()) {
        // This is a user to be stopped.
        synchronized (mLock) {
            stopUsersLU(oldUserId, true, null);
        }
    }
}
 
源代码2 项目: android_9.0.0_r45   文件: OverlayManagerService.java
private void initIfNeeded() {
    final UserManager um = getContext().getSystemService(UserManager.class);
    final List<UserInfo> users = um.getUsers(true /*excludeDying*/);
    synchronized (mLock) {
        final int userCount = users.size();
        for (int i = 0; i < userCount; i++) {
            final UserInfo userInfo = users.get(i);
            if (!userInfo.supportsSwitchTo() && userInfo.id != UserHandle.USER_SYSTEM) {
                // Initialize any users that can't be switched to, as there state would
                // never be setup in onSwitchUser(). We will switch to the system user right
                // after this, and its state will be setup there.
                final List<String> targets = mImpl.updateOverlaysForUser(users.get(i).id);
                updateOverlayPaths(users.get(i).id, targets);
            }
        }
    }
}
 
private boolean checkIfCallerIsForegroundUser() {
    int foregroundUser;
    int callingUser = UserHandle.getCallingUserId();
    int callingUid = Binder.getCallingUid();
    long callingIdentity = Binder.clearCallingIdentity();
    UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
    UserInfo ui = um.getProfileParent(callingUser);
    int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
    int callingAppId = UserHandle.getAppId(callingUid);
    boolean valid = false;
    try {
        foregroundUser = ActivityManager.getCurrentUser();
        valid = (callingUser == foregroundUser) || parentUser == foregroundUser
                || callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
        if (DBG && !valid) {
            Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
                    + callingUser + " parentUser=" + parentUser + " foregroundUser="
                    + foregroundUser);
        }
    } finally {
        Binder.restoreCallingIdentity(callingIdentity);
    }
    return valid;
}
 
源代码4 项目: android_9.0.0_r45   文件: TrustManagerService.java
@Override
protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) {
    if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
    if (isSafeMode()) {
        fout.println("disabled because the system is in safe mode.");
        return;
    }
    if (!mTrustAgentsCanRun) {
        fout.println("disabled because the third-party apps can't run yet.");
        return;
    }
    final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
    mHandler.runWithScissors(new Runnable() {
        @Override
        public void run() {
            fout.println("Trust manager state:");
            for (UserInfo user : userInfos) {
                dumpUser(fout, user, user.id == mCurrentUser);
            }
        }
    }, 1500);
}
 
源代码5 项目: android_9.0.0_r45   文件: ManagedServices.java
private void loadAllowedComponentsFromSettings() {
    for (UserInfo user : mUm.getUsers()) {
        final ContentResolver cr = mContext.getContentResolver();
        addApprovedList(Settings.Secure.getStringForUser(
                cr,
                getConfig().secureSettingName,
                user.id), user.id, true);
        if (!TextUtils.isEmpty(getConfig().secondarySettingName)) {
            addApprovedList(Settings.Secure.getStringForUser(
                    cr,
                    getConfig().secondarySettingName,
                    user.id), user.id, false);
        }
    }
    Slog.d(TAG, "Done loading approved values from settings");
}
 
源代码6 项目: android_9.0.0_r45   文件: LockSettingsService.java
/**
 * Migrate the credential for the FRP credential owner user if the following are satisfied:
 * - the user has a secure credential
 * - the FRP credential is not set up
 * - the credential is based on a synthetic password.
 */
private void migrateFrpCredential() throws RemoteException {
    if (mStorage.readPersistentDataBlock() != PersistentData.NONE) {
        return;
    }
    for (UserInfo userInfo : mUserManager.getUsers()) {
        if (userOwnsFrpCredential(mContext, userInfo) && isUserSecure(userInfo.id)) {
            synchronized (mSpManager) {
                if (isSyntheticPasswordBasedCredentialLocked(userInfo.id)) {
                    int actualQuality = (int) getLong(LockPatternUtils.PASSWORD_TYPE_KEY,
                            DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userInfo.id);

                    mSpManager.migrateFrpPasswordLocked(
                            getSyntheticPasswordHandleLocked(userInfo.id),
                            userInfo,
                            redactActualQualityToMostLenientEquivalentQuality(actualQuality));
                }
            }
            return;
        }
    }
}
 
protected int getSecondaryUserId() {
    if (mSecondaryUserId == Integer.MIN_VALUE) {
        UserManager userManager = (UserManager) getContext()
                .getSystemService(Context.USER_SERVICE);
        List<UserInfo> users = userManager.getUsers();
        final int userCount = users.size();
        for (int i = 0; i < userCount; i++) {
            UserInfo user = users.get(i);
            if (!user.isPrimary() && !user.isManagedProfile()) {
                mSecondaryUserId = user.id;
                return mSecondaryUserId;
            }
        }
    }
    if (mSecondaryUserId == Integer.MIN_VALUE) {
        mSecondaryUserId =  UserHandle.USER_SYSTEM;
    }
    return mSecondaryUserId;
}
 
private boolean interceptSuspendedByAdminPackage() {
    DevicePolicyManagerInternal devicePolicyManager = LocalServices
            .getService(DevicePolicyManagerInternal.class);
    if (devicePolicyManager == null) {
        return false;
    }
    mIntent = devicePolicyManager.createShowAdminSupportIntent(mUserId, true);
    mIntent.putExtra(EXTRA_RESTRICTION, POLICY_SUSPEND_PACKAGES);

    mCallingPid = mRealCallingPid;
    mCallingUid = mRealCallingUid;
    mResolvedType = null;

    final UserInfo parent = mUserManager.getProfileParent(mUserId);
    if (parent != null) {
        mRInfo = mSupervisor.resolveIntent(mIntent, mResolvedType, parent.id, 0,
                mRealCallingUid);
    } else {
        mRInfo = mSupervisor.resolveIntent(mIntent, mResolvedType, mUserId, 0,
                mRealCallingUid);
    }
    mAInfo = mSupervisor.resolveActivity(mIntent, mRInfo, mStartFlags, null /*profilerInfo*/);
    return true;
}
 
源代码9 项目: android_9.0.0_r45   文件: SyncManager.java
private void whiteListExistingSyncAdaptersIfNeeded() {
    if (!mSyncStorageEngine.shouldGrantSyncAdaptersAccountAccess()) {
        return;
    }
    List<UserInfo> users = mUserManager.getUsers(true);
    final int userCount = users.size();
    for (int i = 0; i < userCount; i++) {
        UserHandle userHandle = users.get(i).getUserHandle();
        final int userId = userHandle.getIdentifier();
        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> service
                : mSyncAdapters.getAllServices(userId)) {
            String packageName = service.componentName.getPackageName();
            for (Account account : mAccountManager.getAccountsByTypeAsUser(
                    service.type.accountType, userHandle)) {
                if (!canAccessAccount(account, packageName, userId)) {
                    mAccountManager.updateAppPermission(account,
                            AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, service.uid, true);
                }
            }
        }
    }
}
 
源代码10 项目: android_9.0.0_r45   文件: UserManagerService.java
@Override
public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
    checkManageOrCreateUsersPermission("query users");
    synchronized (mUsersLock) {
        ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
        final int userSize = mUsers.size();
        for (int i = 0; i < userSize; i++) {
            UserInfo ui = mUsers.valueAt(i).info;
            if (ui.partial) {
                continue;
            }
            if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
                users.add(userWithName(ui));
            }
        }
        return users;
    }
}
 
源代码11 项目: android_9.0.0_r45   文件: UserManagerService.java
@Override
public void setUserAdmin(int userId) {
    checkManageUserAndAcrossUsersFullPermission("set user admin");

    synchronized (mPackagesLock) {
        UserInfo info;
        synchronized (mUsersLock) {
            info = getUserInfoLU(userId);
        }
        if (info == null || info.isAdmin()) {
            // Exit if no user found with that id, or the user is already an Admin.
            return;
        }

        info.flags ^= UserInfo.FLAG_ADMIN;
        writeUserLP(getUserDataLU(info.id));
    }

    // Remove non-admin restrictions.
    // Keep synchronized with createUserEvenWhenDisallowed.
    setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
    setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
}
 
源代码12 项目: android_9.0.0_r45   文件: UserManagerService.java
@VisibleForTesting
int getFreeProfileBadgeLU(int parentUserId) {
    int maxManagedProfiles = getMaxManagedProfiles();
    boolean[] usedBadges = new boolean[maxManagedProfiles];
    final int userSize = mUsers.size();
    for (int i = 0; i < userSize; i++) {
        UserInfo ui = mUsers.valueAt(i).info;
        // Check which badge indexes are already used by this profile group.
        if (ui.isManagedProfile()
                && ui.profileGroupId == parentUserId
                && !mRemovingUserIds.get(ui.id)
                && ui.profileBadge < maxManagedProfiles) {
            usedBadges[ui.profileBadge] = true;
        }
    }
    for (int i = 0; i < maxManagedProfiles; i++) {
        if (!usedBadges[i]) {
            return i;
        }
    }
    return 0;
}
 
源代码13 项目: android_9.0.0_r45   文件: UserPackage.java
/**
 * Returns a list of (User,PackageInfo) pairs corresponding to the PackageInfos for all
 * device users for the package named {@param packageName}.
 */
public static List<UserPackage> getPackageInfosAllUsers(Context context,
        String packageName, int packageFlags) {
    List<UserInfo> users = getAllUsers(context);
    List<UserPackage> userPackages = new ArrayList<UserPackage>(users.size());
    for (UserInfo user : users) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfoAsUser(
                    packageName, packageFlags, user.id);
        } catch (NameNotFoundException e) {
        }
        userPackages.add(new UserPackage(user, packageInfo));
    }
    return userPackages;
}
 
源代码14 项目: android_9.0.0_r45   文件: UserManagerService.java
@Override
public boolean hasRestrictedProfiles() {
    checkManageUsersPermission("hasRestrictedProfiles");
    final int callingUserId = UserHandle.getCallingUserId();
    synchronized (mUsersLock) {
        final int userSize = mUsers.size();
        for (int i = 0; i < userSize; i++) {
            UserInfo profile = mUsers.valueAt(i).info;
            if (callingUserId != profile.id
                    && profile.restrictedProfileParentId == callingUserId) {
                return true;
            }
        }
        return false;
    }
}
 
源代码15 项目: android_9.0.0_r45   文件: UserManagerService.java
public void makeInitialized(int userId) {
    checkManageUsersPermission("makeInitialized");
    boolean scheduleWriteUser = false;
    UserData userData;
    synchronized (mUsersLock) {
        userData = mUsers.get(userId);
        if (userData == null || userData.info.partial) {
            Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
            return;
        }
        if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
            userData.info.flags |= UserInfo.FLAG_INITIALIZED;
            scheduleWriteUser = true;
        }
    }
    if (scheduleWriteUser) {
        scheduleWriteUser(userData);
    }
}
 
源代码16 项目: android_9.0.0_r45   文件: UserManagerService.java
/** @return if any user has the given restriction. */
@Override
public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
    if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
        return false;
    }
    final List<UserInfo> users = getUsers(/* excludeDying= */ true);
    for (int i = 0; i < users.size(); i++) {
        final int userId = users.get(i).id;
        Bundle restrictions = getEffectiveUserRestrictions(userId);
        if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
            return true;
        }
    }
    return false;
}
 
源代码17 项目: android_9.0.0_r45   文件: UserManagerService.java
/**
 * @hide
 */
@Override
public UserInfo createRestrictedProfile(String name, int parentUserId) {
    checkManageOrCreateUsersPermission("setupRestrictedProfile");
    final UserInfo user = createProfileForUser(
            name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
    if (user == null) {
        return null;
    }
    long identity = Binder.clearCallingIdentity();
    try {
        setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
        // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
        // the putIntForUser() will fail.
        android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
                android.provider.Settings.Secure.LOCATION_MODE,
                android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
        setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
    } finally {
        Binder.restoreCallingIdentity(identity);
    }
    return user;
}
 
源代码18 项目: AppOpsX   文件: MainActivity.java
private void loadUsers(){
  Helper.getUsers(getApplicationContext(),true).subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new SingleObserver<List<UserInfo>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onSuccess(List<UserInfo> userInfos) {

          Users.getInstance().updateUsers(userInfos);
          invalidateOptionsMenu();
        }

        @Override
        public void onError(Throwable e) {

        }
      });
}
 
源代码19 项目: android_9.0.0_r45   文件: UserManagerService.java
/**
 * Called right before a user is started. This gives us a chance to prepare
 * app storage and apply any user restrictions.
 */
public void onBeforeStartUser(int userId) {
    UserInfo userInfo = getUserInfo(userId);
    if (userInfo == null) {
        return;
    }
    final int userSerial = userInfo.serialNumber;
    // Migrate only if build fingerprints mismatch
    boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
    mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
    mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);

    if (userId != UserHandle.USER_SYSTEM) {
        synchronized (mRestrictionsLock) {
            applyUserRestrictionsLR(userId);
        }
    }
}
 
@Override
public CharSequence getUserBadgedLabel(CharSequence label, UserHandle user) {
    UserInfo userInfo = getUserIfProfile(user.getIdentifier());
    if (userInfo != null && userInfo.isManagedProfile()) {
        return Resources.getSystem().getString(
                com.android.internal.R.string.managed_profile_label_badge, label);
    }
    return label;
}
 
private int getBadgeResIdForUser(int userHandle) {
    // Return the framework-provided badge.
    UserInfo userInfo = getUserIfProfile(userHandle);
    if (userInfo != null && userInfo.isManagedProfile()) {
        return com.android.internal.R.drawable.ic_corp_icon_badge;
    }
    return 0;
}
 
private UserInfo getUserIfProfile(int userHandle) {
    List<UserInfo> userProfiles = getUserManager().getProfiles(UserHandle.myUserId());
    for (UserInfo user : userProfiles) {
        if (user.id == userHandle) {
            return user;
        }
    }
    return null;
}
 
/**
 * @hide
 */
@Override
public UserInfo createUser(String name, int flags) {
    try {
        return mPM.createUser(name, flags);
    } catch (RemoteException e) {
        // Should never happen!
    }
    return null;
}
 
源代码24 项目: android_9.0.0_r45   文件: OverlayManagerService.java
private void restoreSettings() {
    synchronized (mLock) {
        if (!mSettingsFile.getBaseFile().exists()) {
            return;
        }
        try (final FileInputStream stream = mSettingsFile.openRead()) {
            mSettings.restore(stream);

            // We might have data for dying users if the device was
            // restarted before we received USER_REMOVED. Remove data for
            // users that will not exist after the system is ready.

            final List<UserInfo> liveUsers = mUserManager.getUsers(true /*excludeDying*/);
            final int[] liveUserIds = new int[liveUsers.size()];
            for (int i = 0; i < liveUsers.size(); i++) {
                liveUserIds[i] = liveUsers.get(i).getUserHandle().getIdentifier();
            }
            Arrays.sort(liveUserIds);

            for (int userId : mSettings.getUsers()) {
                if (Arrays.binarySearch(liveUserIds, userId) < 0) {
                    mSettings.removeUser(userId);
                }
            }
        } catch (IOException | XmlPullParserException e) {
            Slog.e(TAG, "failed to restore overlay state", e);
        }
    }
}
 
private boolean interceptWorkProfileChallengeIfNeeded() {
    final Intent interceptingIntent = interceptWithConfirmCredentialsIfNeeded(mAInfo, mUserId);
    if (interceptingIntent == null) {
        return false;
    }
    mIntent = interceptingIntent;
    mCallingPid = mRealCallingPid;
    mCallingUid = mRealCallingUid;
    mResolvedType = null;
    // If we are intercepting and there was a task, convert it into an extra for the
    // ConfirmCredentials intent and unassign it, as otherwise the task will move to
    // front even if ConfirmCredentials is cancelled.
    if (mInTask != null) {
        mIntent.putExtra(EXTRA_TASK_ID, mInTask.taskId);
        mInTask = null;
    }
    if (mActivityOptions == null) {
        mActivityOptions = ActivityOptions.makeBasic();
    }

    ActivityRecord homeActivityRecord = mSupervisor.getHomeActivity();
    if (homeActivityRecord != null && homeActivityRecord.getTask() != null) {
        // Showing credential confirmation activity in home task to avoid stopping multi-windowed
        // mode after showing the full-screen credential confirmation activity.
        mActivityOptions.setLaunchTaskId(homeActivityRecord.getTask().taskId);
    }

    final UserInfo parent = mUserManager.getProfileParent(mUserId);
    mRInfo = mSupervisor.resolveIntent(mIntent, mResolvedType, parent.id, 0, mRealCallingUid);
    mAInfo = mSupervisor.resolveActivity(mIntent, mRInfo, mStartFlags, null /*profilerInfo*/);
    return true;
}
 
private int getBadgeResIdForUser(int userHandle) {
    // Return the framework-provided badge.
    UserInfo userInfo = getUserIfProfile(userHandle);
    if (userInfo != null && userInfo.isManagedProfile()) {
        return com.android.internal.R.drawable.ic_corp_icon_badge;
    }
    return 0;
}
 
private UserInfo getUserIfProfile(int userHandle) {
    List<UserInfo> userProfiles = getUserManager().getProfiles(UserHandle.myUserId());
    for (UserInfo user : userProfiles) {
        if (user.id == userHandle) {
            return user;
        }
    }
    return null;
}
 
源代码28 项目: AndroidComponentPlugin   文件: ActivityManager.java
/**
 * Gets the userId of the current foreground user. Requires system permissions.
 * @hide
 */
@SystemApi
@RequiresPermission(anyOf = {
        "android.permission.INTERACT_ACROSS_USERS",
        "android.permission.INTERACT_ACROSS_USERS_FULL"
})
public static int getCurrentUser() {
    UserInfo ui;
    try {
        ui = getService().getCurrentUser();
        return ui != null ? ui.id : 0;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
源代码29 项目: android_9.0.0_r45   文件: SystemImpl.java
@Override
public void enablePackageForAllUsers(Context context, String packageName, boolean enable) {
    UserManager userManager = (UserManager)context.getSystemService(Context.USER_SERVICE);
    for(UserInfo userInfo : userManager.getUsers()) {
        enablePackageForUser(packageName, enable, userInfo.id);
    }
}
 
源代码30 项目: android_9.0.0_r45   文件: StorageManagerService.java
/**
 * MediaProvider has a ton of code that makes assumptions about storage
 * paths never changing, so we outright kill them to pick up new state.
 */
@Deprecated
private void killMediaProvider(List<UserInfo> users) {
    if (users == null) return;

    final long token = Binder.clearCallingIdentity();
    try {
        for (UserInfo user : users) {
            // System user does not have media provider, so skip.
            if (user.isSystemOnly()) continue;

            final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY,
                    PackageManager.MATCH_DIRECT_BOOT_AWARE
                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                    user.id);
            if (provider != null) {
                final IActivityManager am = ActivityManager.getService();
                try {
                    am.killApplication(provider.applicationInfo.packageName,
                            UserHandle.getAppId(provider.applicationInfo.uid),
                            UserHandle.USER_ALL, "vold reset");
                    // We only need to run this once. It will kill all users' media processes.
                    break;
                } catch (RemoteException e) {
                }
            }
        }
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
 类所在包
 同包方法