android.os.UserManager Java Examples

The following examples show how to use android.os.UserManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Taskbar   Author: farmerbb   File: TaskbarController.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source Project: android_9.0.0_r45   Author: lulululbj   File: Vpn.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #3
Source Project: AndroidComponentPlugin   Author: androidmalin   File: ApplicationPackageManager.java    License: Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #4
Source Project: android-testdpc   Author: googlesamples   File: PolicyManagementFragment.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source Project: Indic-Keyboard   Author: smc   File: UserManagerCompatUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source Project: Study_Android_Demo   Author: RealMoMo   File: BaseSettingsProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source Project: android_9.0.0_r45   Author: lulululbj   File: StorageManagerService.java    License: Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example #8
Source Project: android_9.0.0_r45   Author: lulululbj   File: StorageManagerService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source Project: android_9.0.0_r45   Author: lulululbj   File: TextServicesManagerService.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source Project: android_9.0.0_r45   Author: lulululbj   File: CameraServiceProxy.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source Project: Taskbar   Author: farmerbb   File: IconCache.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source Project: Shelter   Author: PeterCxy   File: Utility.java    License: Do What The F*ck You Want To Public License 6 votes vote down vote up
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);
}
 
Example #13
Source Project: android_9.0.0_r45   Author: lulululbj   File: EventConditionProvider.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #14
Source Project: android_9.0.0_r45   Author: lulululbj   File: Tethering.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #15
Source Project: Study_Android_Demo   Author: RealMoMo   File: SettingsProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #16
Source Project: appauth-android-codelab   Author: googlecodelabs   File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
  }
}
 
Example #17
Source Project: android-testdpc   Author: googlesamples   File: UserRestrictionsDisplayFragment.java    License: Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example #18
Source Project: AndroidComponentPlugin   Author: androidmalin   File: ContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #19
Source Project: AndroidComponentPlugin   Author: androidmalin   File: ApplicationPackageManager.java    License: Apache License 2.0 5 votes vote down vote up
UserManager getUserManager() {
    synchronized (mLock) {
        if (mUserManager == null) {
            mUserManager = UserManager.get(mContext);
        }
        return mUserManager;
    }
}
 
Example #20
Source Project: android_9.0.0_r45   Author: lulululbj   File: MediaResourceMonitorService.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #21
Source Project: android_9.0.0_r45   Author: lulululbj   File: CallLog.java    License: Apache License 2.0 5 votes vote down vote up
/** @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();
}
 
Example #22
Source Project: android_9.0.0_r45   Author: lulululbj   File: ActivityStartInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #23
Source Project: android_9.0.0_r45   Author: lulululbj   File: AppCollector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #24
Source Project: HgLauncher   Author: F4uzan   File: LauncherIconHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #25
Source Project: android_9.0.0_r45   Author: lulululbj   File: Vpn.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #26
Source Project: AndroidComponentPlugin   Author: androidmalin   File: ApplicationPackageManager.java    License: Apache License 2.0 5 votes vote down vote up
UserManager getUserManager() {
    synchronized (mLock) {
        if (mUserManager == null) {
            mUserManager = UserManager.get(mContext);
        }
        return mUserManager;
    }
}
 
Example #27
Source Project: LB-Launcher   Author: AndroidDeveloperLB   File: LauncherClings.java    License: Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example #28
Source Project: android_9.0.0_r45   Author: lulululbj   File: ActivityManagerShellCommand.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #29
Source Project: android_9.0.0_r45   Author: lulululbj   File: UserInfo.java    License: Apache License 2.0 5 votes vote down vote up
public boolean canHaveProfile() {
    if (isManagedProfile() || isGuest() || isRestricted()) {
        return false;
    }
    if (UserManager.isSplitSystemUser()) {
        return id != UserHandle.USER_SYSTEM;
    } else {
        return id == UserHandle.USER_SYSTEM;
    }
}
 
Example #30
Source Project: android_9.0.0_r45   Author: lulululbj   File: BrightnessTracker.java    License: Apache License 2.0 5 votes vote down vote up
public int[] getProfileIds(UserManager userManager, int userId) {
    if (userManager != null) {
        return userManager.getProfileIds(userId, false);
    } else {
        return new int[]{userId};
    }
}