android.os.UserManager源码实例Demo

android.content.IIntentSender#android.os.UserManager源码实例Demo

下面列出了android.content.IIntentSender#android.os.UserManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Taskbar   文件: TaskbarController.java
@VisibleForTesting
int filterRealPinnedApps(Context context,
                         List<AppEntry> pinnedApps,
                         List<AppEntry> entries,
                         List<String> applicationIdsToRemove) {
    int realNumOfPinnedApps = 0;
    if(pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);

        for(AppEntry entry : pinnedApps) {
            boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(),
                    userManager.getUserForSerialNumber(entry.getUserId(context)));

            if(packageEnabled)
                entries.add(entry);
            else
                realNumOfPinnedApps--;

            applicationIdsToRemove.add(entry.getPackageName());
        }

        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }
    return realNumOfPinnedApps;
}
 
源代码2 项目: android_9.0.0_r45   文件: Vpn.java
/**
 * Updates UID ranges for this VPN and also updates its capabilities.
 *
 * <p>Should be called on primary ConnectivityService thread.
 */
public void onUserRemoved(int userHandle) {
    // clean up if restricted
    UserInfo user = UserManager.get(mContext).getUserInfo(userHandle);
    if (user.isRestricted() && user.restrictedProfileParentId == mUserHandle) {
        synchronized(Vpn.this) {
            final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
            if (existingRanges != null) {
                try {
                    final List<UidRange> removedRanges =
                        uidRangesForUser(userHandle, existingRanges);
                    existingRanges.removeAll(removedRanges);
                    // ConnectivityService will call {@link #updateCapabilities} and
                    // apply those for VPN network.
                    mNetworkCapabilities.setUids(existingRanges);
                } catch (Exception e) {
                    Log.wtf(TAG, "Failed to remove restricted user to owner", e);
                }
            }
            setVpnForcedLocked(mLockdown);
        }
    }
}
 
private void onImplicitDirectBoot(int userId) {
    // Only report if someone is relying on implicit behavior while the user
    // is locked; code running when unlocked is going to see both aware and
    // unaware components.
    if (StrictMode.vmImplicitDirectBootEnabled()) {
        // We can cache the unlocked state for the userId we're running as,
        // since any relocking of that user will always result in our
        // process being killed to release any CE FDs we're holding onto.
        if (userId == UserHandle.myUserId()) {
            if (mUserUnlocked) {
                return;
            } else if (mContext.getSystemService(UserManager.class)
                    .isUserUnlockingOrUnlocked(userId)) {
                mUserUnlocked = true;
            } else {
                StrictMode.onImplicitDirectBoot();
            }
        } else if (!mContext.getSystemService(UserManager.class)
                .isUserUnlockingOrUnlocked(userId)) {
            StrictMode.onImplicitDirectBoot();
        }
    }
}
 
@Override
public void onCreate(Bundle savedInstanceState) {
    if (isDelegatedApp()) {
        mAdminComponentName = null;
    } else {
        mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
    }
    mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
            Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
    mTelephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    mAccountManager = AccountManager.get(getActivity());
    mPackageManager = getActivity().getPackageManager();
    mPackageName = getActivity().getPackageName();

    mImageUri = getStorageUri("image.jpg");
    mVideoUri = getStorageUri("video.mp4");

    super.onCreate(savedInstanceState);
}
 
源代码5 项目: Indic-Keyboard   文件: UserManagerCompatUtils.java
/**
 * Check if the calling user is running in an "unlocked" state. A user is unlocked only after
 * they've entered their credentials (such as a lock pattern or PIN), and credential-encrypted
 * private app data storage is available.
 * @param context context from which {@link UserManager} should be obtained.
 * @return One of {@link LockState}.
 */
@LockState
public static int getUserLockState(final Context context) {
    if (METHOD_isUserUnlocked == null) {
        return LOCK_STATE_UNKNOWN;
    }
    final UserManager userManager = context.getSystemService(UserManager.class);
    if (userManager == null) {
        return LOCK_STATE_UNKNOWN;
    }
    final Boolean result =
            (Boolean) CompatUtils.invoke(userManager, null, METHOD_isUserUnlocked);
    if (result == null) {
        return LOCK_STATE_UNKNOWN;
    }
    return result ? LOCK_STATE_UNLOCKED : LOCK_STATE_LOCKED;
}
 
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;
}
 
源代码7 项目: android_9.0.0_r45   文件: StorageManagerService.java
private void initIfReadyAndConnected() {
    Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
            + ", mDaemonConnected=" + mDaemonConnected);
    if (mSystemReady && mDaemonConnected
            && !StorageManager.isFileEncryptedNativeOnly()) {
        // When booting a device without native support, make sure that our
        // user directories are locked or unlocked based on the current
        // emulation status.
        final boolean initLocked = StorageManager.isFileEncryptedEmulatedOnly();
        Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
        final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
        for (UserInfo user : users) {
            try {
                if (initLocked) {
                    mVold.lockUserKey(user.id);
                } else {
                    mVold.unlockUserKey(user.id, user.serialNumber, encodeBytes(null),
                            encodeBytes(null));
                }
            } catch (Exception e) {
                Slog.wtf(TAG, e);
            }
        }
    }
}
 
源代码8 项目: android_9.0.0_r45   文件: StorageManagerService.java
/**
 * Decide if volume is mountable per device policies.
 */
private boolean isMountDisallowed(VolumeInfo vol) {
    UserManager userManager = mContext.getSystemService(UserManager.class);

    boolean isUsbRestricted = false;
    if (vol.disk != null && vol.disk.isUsb()) {
        isUsbRestricted = userManager.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER,
                Binder.getCallingUserHandle());
    }

    boolean isTypeRestricted = false;
    if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE) {
        isTypeRestricted = userManager
                .hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
                Binder.getCallingUserHandle());
    }

    return isUsbRestricted || isTypeRestricted;
}
 
public TextServicesManagerService(Context context) {
    mContext = context;
    mUserManager = mContext.getSystemService(UserManager.class);
    mSpellCheckerOwnerUserIdMap = new LazyIntToIntMap(callingUserId -> {
        if (DISABLE_PER_PROFILE_SPELL_CHECKER) {
            final long token = Binder.clearCallingIdentity();
            try {
                final UserInfo parent = mUserManager.getProfileParent(callingUserId);
                return (parent != null) ? parent.id : callingUserId;
            } finally {
                Binder.restoreCallingIdentity(token);
            }
        } else {
            return callingUserId;
        }
    });

    mMonitor = new TextServicesMonitor();
    mMonitor.register(context, null, UserHandle.ALL, true);
}
 
源代码10 项目: android_9.0.0_r45   文件: CameraServiceProxy.java
@Override
public void onStart() {
    mUserManager = UserManager.get(mContext);
    if (mUserManager == null) {
        // Should never see this unless someone messes up the SystemServer service boot order.
        throw new IllegalStateException("UserManagerService must start before" +
                " CameraServiceProxy!");
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_USER_ADDED);
    filter.addAction(Intent.ACTION_USER_REMOVED);
    filter.addAction(Intent.ACTION_USER_INFO_CHANGED);
    filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
    filter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
    mContext.registerReceiver(mIntentReceiver, filter);

    publishBinderService(CAMERA_SERVICE_PROXY_BINDER_NAME, mCameraServiceProxy);
    publishLocalService(CameraServiceProxy.class, this);

    CameraStatsJobService.schedule(mContext);
}
 
源代码11 项目: Taskbar   文件: IconCache.java
public BitmapDrawable getIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
    UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
    String name = appInfo.getComponentName().flattenToString() + ":" + userManager.getSerialNumberForUser(appInfo.getUser());

    BitmapDrawable drawable;

    synchronized (drawables) {
        drawable = drawables.get(name);
        if(drawable == null) {
            Drawable loadedIcon = loadIcon(context, pm, appInfo);
            drawable = U.convertToBitmapDrawable(context, loadedIcon);

            drawables.put(name, drawable);
        }
    }

    return drawable;
}
 
源代码12 项目: Shelter   文件: Utility.java
public static void enforceUserRestrictions(Context context) {
    DevicePolicyManager manager = context.getSystemService(DevicePolicyManager.class);
    ComponentName adminComponent = new ComponentName(context.getApplicationContext(), ShelterDeviceAdminReceiver.class);
    manager.clearUserRestriction(adminComponent, UserManager.DISALLOW_INSTALL_APPS);
    manager.clearUserRestriction(adminComponent, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
    manager.clearUserRestriction(adminComponent, UserManager.DISALLOW_UNINSTALL_APPS);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        // Polyfill for UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
        // Don't use this on Android Oreo and later, it will crash
        manager.setSecureSetting(adminComponent, Settings.Secure.INSTALL_NON_MARKET_APPS, "1");
    }

    // TODO: This should be configured by the user, instead of being enforced each time Shelter starts
    // TODO: But we should also have some default restrictions that are set the first time Shelter starts
    manager.addUserRestriction(adminComponent, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
}
 
源代码13 项目: android_9.0.0_r45   文件: EventConditionProvider.java
private void reloadTrackers() {
    if (DEBUG) Slog.d(TAG, "reloadTrackers");
    for (int i = 0; i < mTrackers.size(); i++) {
        mTrackers.valueAt(i).setCallback(null);
    }
    mTrackers.clear();
    for (UserHandle user : UserManager.get(mContext).getUserProfiles()) {
        final Context context = user.isSystem() ? mContext : getContextForUser(mContext, user);
        if (context == null) {
            Slog.w(TAG, "Unable to create context for user " + user.getIdentifier());
            continue;
        }
        mTrackers.put(user.getIdentifier(), new CalendarTracker(mContext, context));
    }
    evaluateSubscriptions();
}
 
源代码14 项目: Taskbar   文件: ContextMenuActivity.java
@TargetApi(Build.VERSION_CODES.N_MR1)
private int getLauncherShortcuts() {
    LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
    if(launcherApps.hasShortcutHostPermission()) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);

        LauncherApps.ShortcutQuery query = new LauncherApps.ShortcutQuery();
        query.setActivity(ComponentName.unflattenFromString(entry.getComponentName()));
        query.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
                | LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST
                | LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED);

        shortcuts = launcherApps.getShortcuts(query, userManager.getUserForSerialNumber(entry.getUserId(this)));
        if(shortcuts != null)
            return shortcuts.size();
    }

    return 0;
}
 
源代码15 项目: android_9.0.0_r45   文件: Tethering.java
public void onUserRestrictionsChanged(int userId,
                                      Bundle newRestrictions,
                                      Bundle prevRestrictions) {
    final boolean newlyDisallowed =
            newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING);
    final boolean previouslyDisallowed =
            prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING);
    final boolean tetheringDisallowedChanged = (newlyDisallowed != previouslyDisallowed);

    if (!tetheringDisallowedChanged) {
        return;
    }

    mWrapper.clearTetheredNotification();
    final boolean isTetheringActiveOnDevice = (mWrapper.getTetheredIfaces().length != 0);

    if (newlyDisallowed && isTetheringActiveOnDevice) {
        mWrapper.showTetheredNotification(
                com.android.internal.R.drawable.stat_sys_tether_general, false);
        mWrapper.untetherAll();
    }
}
 
源代码16 项目: Study_Android_Demo   文件: SettingsProvider.java
@Override
public boolean onCreate() {
    Settings.setInSystemServer();
    synchronized (mLock) {
        mUserManager = UserManager.get(getContext());
        mPackageManager = AppGlobals.getPackageManager();
        mHandlerThread = new HandlerThread(LOG_TAG,
                Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
        mSettingsRegistry = new SettingsRegistry();
    }
    mHandler.post(() -> {
        registerBroadcastReceivers();
        startWatchingUserRestrictionChanges();
    });
    ServiceManager.addService("settings", new SettingsService(this));
    return true;
}
 
源代码17 项目: appauth-android-codelab   文件: MainActivity.java
private void getAppRestrictions(){
  RestrictionsManager restrictionsManager =
          (RestrictionsManager) this
                  .getSystemService(Context.RESTRICTIONS_SERVICE);

  Bundle appRestrictions = restrictionsManager.getApplicationRestrictions();

  // Block user if KEY_RESTRICTIONS_PENDING is true, and save login hint if available
  if(!appRestrictions.isEmpty()){
    if(appRestrictions.getBoolean(UserManager.
            KEY_RESTRICTIONS_PENDING)!=true){
      mLoginHint = appRestrictions.getString(LOGIN_HINT);
    }
    else {
      Toast.makeText(this,R.string.restrictions_pending_block_user,
              Toast.LENGTH_LONG).show();
      finish();
    }
  }
}
 
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    String restriction = preference.getKey();
    try {
        if (newValue.equals(true)) {
            mDevicePolicyManager.addUserRestriction(mAdminComponentName, restriction);
        } else {
            mDevicePolicyManager.clearUserRestriction(mAdminComponentName, restriction);
            if (DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(restriction) ||
                    UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY.equals(
                            restriction)) {
                new AlertDialog.Builder(getActivity())
                        .setMessage(R.string.check_setting_disallow_install_unknown_sources)
                        .setPositiveButton(R.string.check_setting_ok, null)
                        .show();
            }
        }
        updateUserRestriction(restriction);
        if (UserManager.DISALLOW_UNIFIED_PASSWORD.equals(restriction)) {
            DeviceAdminReceiver.sendPasswordRequirementsChanged(getActivity());
        }
        return true;
    } catch (SecurityException e) {
        Toast.makeText(getActivity(), R.string.user_restriction_error_msg,
                Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Error occurred while updating user restriction: " + restriction, e);
        return false;
    }
}
 
源代码19 项目: AndroidComponentPlugin   文件: ContextImpl.java
@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
    SharedPreferencesImpl sp;
    synchronized (ContextImpl.class) {
        final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
        sp = cache.get(file);
        if (sp == null) {
            checkMode(mode);
            if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
                if (isCredentialProtectedStorage()
                        && !getSystemService(UserManager.class)
                                .isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
                    throw new IllegalStateException("SharedPreferences in credential encrypted "
                            + "storage are not available until after user is unlocked");
                }
            }
            sp = new SharedPreferencesImpl(file, mode);
            cache.put(file, sp);
            return sp;
        }
    }
    if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
        getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
        // If somebody else (some other process) changed the prefs
        // file behind our back, we reload it.  This has been the
        // historical (if undocumented) behavior.
        sp.startReloadIfChangedUnexpectedly();
    }
    return sp;
}
 
UserManager getUserManager() {
    synchronized (mLock) {
        if (mUserManager == null) {
            mUserManager = UserManager.get(mContext);
        }
        return mUserManager;
    }
}
 
@Override
public void notifyResourceGranted(int pid, int type)
        throws RemoteException {
    if (DEBUG) {
        Slog.d(TAG, "notifyResourceGranted(pid=" + pid + ", type=" + type + ")");
    }
    final long identity = Binder.clearCallingIdentity();
    try {
        String pkgNames[] = getPackageNamesFromPid(pid);
        if (pkgNames == null) {
            return;
        }
        UserManager manager = (UserManager) getContext().getSystemService(
                Context.USER_SERVICE);
        int[] userIds = manager.getEnabledProfileIds(ActivityManager.getCurrentUser());
        if (userIds == null || userIds.length == 0) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_RESOURCE_GRANTED);
        intent.putExtra(Intent.EXTRA_PACKAGES, pkgNames);
        intent.putExtra(Intent.EXTRA_MEDIA_RESOURCE_TYPE, type);
        for (int userId : userIds) {
            getContext().sendBroadcastAsUser(intent, UserHandle.of(userId),
                    android.Manifest.permission.RECEIVE_MEDIA_RESOURCE_USAGE);
        }
    } finally {
        Binder.restoreCallingIdentity(identity);
    }
}
 
源代码22 项目: android_9.0.0_r45   文件: CallLog.java
/** @hide */
public static boolean shouldHaveSharedCallLogEntries(Context context,
        UserManager userManager, int userId) {
    if (userManager.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS,
            UserHandle.of(userId))) {
        return false;
    }
    final UserInfo userInfo = userManager.getUserInfo(userId);
    return userInfo != null && !userInfo.isManagedProfile();
}
 
/**
 * Intercept the launch intent based on various signals. If an interception happened the
 * internal variables get assigned and need to be read explicitly by the caller.
 *
 * @return true if an interception occurred
 */
boolean intercept(Intent intent, ResolveInfo rInfo, ActivityInfo aInfo, String resolvedType,
        TaskRecord inTask, int callingPid, int callingUid, ActivityOptions activityOptions) {
    mUserManager = UserManager.get(mServiceContext);

    mIntent = intent;
    mCallingPid = callingPid;
    mCallingUid = callingUid;
    mRInfo = rInfo;
    mAInfo = aInfo;
    mResolvedType = resolvedType;
    mInTask = inTask;
    mActivityOptions = activityOptions;

    if (interceptSuspendedPackageIfNeeded()) {
        // Skip the rest of interceptions as the package is suspended by device admin so
        // no user action can undo this.
        return true;
    }
    if (interceptQuietProfileIfNeeded()) {
        // If work profile is turned off, skip the work challenge since the profile can only
        // be unlocked when profile's user is running.
        return true;
    }
    if (interceptHarmfulAppIfNeeded()) {
        // If the app has a "harmful app" warning associated with it, we should ask to uninstall
        // before issuing the work challenge.
        return true;
    }
    return interceptWorkProfileChallengeIfNeeded();
}
 
源代码24 项目: android_9.0.0_r45   文件: AppCollector.java
/**
 * Constrcuts a new AppCollector which runs on the provided volume.
 * @param context Android context used to get
 * @param volume Volume to check for apps.
 */
public AppCollector(Context context, @NonNull VolumeInfo volume) {
    Preconditions.checkNotNull(volume);

    mBackgroundHandler = new BackgroundHandler(BackgroundThread.get().getLooper(),
            volume,
            context.getPackageManager(),
            (UserManager) context.getSystemService(Context.USER_SERVICE),
            (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE));
}
 
源代码25 项目: HgLauncher   文件: LauncherIconHelper.java
/**
 * Loads an icon from the icon pack based on the received package name.
 *
 * @param activity       where LauncherApps service can be retrieved.
 * @param appPackageName Package name of the app whose icon is to be loaded.
 *
 * @return Drawable Will return null if there is no icon associated with the package name,
 * otherwise an associated icon from the icon pack will be returned.
 */
private static Drawable getIconDrawable(Activity activity, String appPackageName, long user) {
    PackageManager packageManager = activity.getPackageManager();
    String componentName = "ComponentInfo{" + appPackageName + "}";
    Resources iconRes = null;
    Drawable defaultIcon = null;

    try {
        if (Utils.atLeastLollipop()) {
            LauncherApps launcher = (LauncherApps) activity.getSystemService(
                    Context.LAUNCHER_APPS_SERVICE);
            UserManager userManager = (UserManager) activity.getSystemService(
                    Context.USER_SERVICE);

            if (userManager != null && launcher != null) {
                defaultIcon = launcher.getActivityList(AppUtils.getPackageName(appPackageName),
                        userManager.getUserForSerialNumber(user))
                                      .get(0).getBadgedIcon(0);
            }
        } else {
            defaultIcon = packageManager.getActivityIcon(
                    ComponentName.unflattenFromString(appPackageName));
        }

        if (!"default".equals(iconPackageName)) {
            iconRes = packageManager.getResourcesForApplication(iconPackageName);
        } else {
            return defaultIcon;
        }
    } catch (PackageManager.NameNotFoundException e) {
        Utils.sendLog(Utils.LogLevel.ERROR, e.toString());
    }

    String drawable = mPackagesDrawables.get(componentName);
    if (drawable != null && iconRes != null) {
        return loadDrawable(iconRes, drawable, iconPackageName);
    } else {
        return defaultIcon;
    }
}
 
源代码26 项目: android_9.0.0_r45   文件: Vpn.java
/**
 * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
 * associated with one user, and any restricted profiles attached to that user.
 *
 * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
 * the UID ranges will match the app whitelist or blacklist specified there. Otherwise, all UIDs
 * in each user and profile will be included.
 *
 * @param userHandle The userId to create UID ranges for along with any of its restricted
 *                   profiles.
 * @param allowedApplications (optional) whitelist of applications to include.
 * @param disallowedApplications (optional) blacklist of applications to exclude.
 */
@VisibleForTesting
Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userHandle,
        @Nullable List<String> allowedApplications,
        @Nullable List<String> disallowedApplications) {
    final Set<UidRange> ranges = new ArraySet<>();

    // Assign the top-level user to the set of ranges
    addUserToRanges(ranges, userHandle, allowedApplications, disallowedApplications);

    // If the user can have restricted profiles, assign all its restricted profiles too
    if (canHaveRestrictedProfile(userHandle)) {
        final long token = Binder.clearCallingIdentity();
        List<UserInfo> users;
        try {
            users = UserManager.get(mContext).getUsers(true);
        } finally {
            Binder.restoreCallingIdentity(token);
        }
        for (UserInfo user : users) {
            if (user.isRestricted() && (user.restrictedProfileParentId == userHandle)) {
                addUserToRanges(ranges, user.id, allowedApplications, disallowedApplications);
            }
        }
    }
    return ranges;
}
 
UserManager getUserManager() {
    synchronized (mLock) {
        if (mUserManager == null) {
            mUserManager = UserManager.get(mContext);
        }
        return mUserManager;
    }
}
 
源代码28 项目: LB-Launcher   文件: LauncherClings.java
/** Returns whether the clings are enabled or should be shown */
private boolean areClingsEnabled() {
    if (DISABLE_CLINGS) {
        return false;
    }

    // disable clings when running in a test harness
    if(ActivityManager.isRunningInTestHarness()) return false;

    // Disable clings for accessibility when explore by touch is enabled
    final AccessibilityManager a11yManager = (AccessibilityManager) mLauncher.getSystemService(
            Launcher.ACCESSIBILITY_SERVICE);
    if (a11yManager.isTouchExplorationEnabled()) {
        return false;
    }

    // Restricted secondary users (child mode) will potentially have very few apps
    // seeded when they start up for the first time. Clings won't work well with that
    boolean supportsLimitedUsers =
            android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
    Account[] accounts = AccountManager.get(mLauncher).getAccounts();
    if (supportsLimitedUsers && accounts.length == 0) {
        UserManager um = (UserManager) mLauncher.getSystemService(Context.USER_SERVICE);
        Bundle restrictions = um.getUserRestrictions();
        if (restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false)) {
            return false;
        }
    }
    if (Settings.Secure.getInt(mLauncher.getContentResolver(), SKIP_FIRST_USE_HINTS, 0)
            == 1) {
        return false;
    }
    return true;
}
 
int runSwitchUser(PrintWriter pw) throws RemoteException {
    UserManager userManager = mInternal.mContext.getSystemService(UserManager.class);
    if (!userManager.canSwitchUsers()) {
        getErrPrintWriter().println("Error: disallowed switching user");
        return -1;
    }
    String user = getNextArgRequired();
    mInterface.switchUser(Integer.parseInt(user));
    return 0;
}
 
源代码30 项目: android_9.0.0_r45   文件: UserInfo.java
public boolean canHaveProfile() {
    if (isManagedProfile() || isGuest() || isRestricted()) {
        return false;
    }
    if (UserManager.isSplitSystemUser()) {
        return id != UserHandle.USER_SYSTEM;
    } else {
        return id == UserHandle.USER_SYSTEM;
    }
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。