private State getCurrentState() { ComponentName componentName = componentName(); DevicePolicyManager policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); if (!policyManager.isAdminActive(componentName)) { return State.NEEDS_PERMISSIONS; } if (!policyManager.getCameraDisabled(componentName)) { return State.HAS_PERMISSIONS; } if (!policyManager.isDeviceOwnerApp(BuildConfig.APPLICATION_ID)) { return State.CAMERA_DISABLED; } // Apparently we can't query for user restrictions, so just always set them if they're not // already set. We know that we're allowed to because we're the device owner. policyManager.addUserRestriction(componentName, UserManager.DISALLOW_ADD_USER); policyManager.addUserRestriction(componentName, UserManager.DISALLOW_FACTORY_RESET); return State.IS_DEVICE_OWNER; }
@Override public void onResume() { super.onResume(); refreshNotificationListeners(); lookupRingtoneNames(); updateNotificationPreferenceState(); mSettingsObserver.register(true); mReceiver.register(true); updateRingPreference(); updateEffectsSuppressor(); for (VolumeSeekBarPreference volumePref : mVolumePrefs) { volumePref.onActivityResume(); } if (mIncreasingRingVolume != null) { mIncreasingRingVolume.onActivityResume(); } boolean isRestricted = mUserManager.hasUserRestriction(UserManager.DISALLOW_ADJUST_VOLUME); for (String key : RESTRICTED_KEYS) { Preference pref = findPreference(key); if (pref != null) { pref.setEnabled(!isRestricted); } } }
/** * Creates workspace loader from an XML resource listed in the app restrictions. * * @return the loader if the restrictions are set and the resource exists; null otherwise. */ private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) { Context ctx = getContext(); UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE); Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName()); if (bundle == null) { return null; } String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME); if (packageName != null) { try { Resources targetResources = ctx.getPackageManager() .getResourcesForApplication(packageName); return AutoInstallsLayout.get(ctx, packageName, targetResources, widgetHost, mOpenHelper); } catch (NameNotFoundException e) { e.printStackTrace(); return null; } } return null; }
@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(componentName)); query.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC | LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST | LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED); shortcuts = launcherApps.getShortcuts(query, userManager.getUserForSerialNumber(userId)); if(shortcuts != null) return shortcuts.size(); } return 0; }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static boolean isRestrictedProfile(Context context) { if (Versions.preJBMR2) { // Early versions don't support restrictions at all return false; } final UserManager mgr = (UserManager) context.getSystemService(Context.USER_SERVICE); final Bundle restrictions = new Bundle(); restrictions.putAll(mgr.getApplicationRestrictions(context.getPackageName())); restrictions.putAll(mgr.getUserRestrictions()); for (String key : restrictions.keySet()) { if (restrictions.getBoolean(key)) { // At least one restriction is enabled -> We are a restricted profile return true; } } return false; }
@Override public int onStartCommand(Intent intent, int flags, int startId) { createNotificationChannel(); startForeground(); if (getSystemService(UserManager.class).isUserUnlocked() || getActiveResetPasswordToken() == null) { stopSelf(); mNm.cancel(NOTIFICATION_FOREGROUND); return START_NOT_STICKY; } IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_USER_UNLOCKED); filter.addAction(ACTION_RESET_PASSWORD); registerReceiver(receiver, filter); showNotification(); return START_REDELIVER_INTENT; }
private static List<CalendarInfo> getCalendars(Context context) { final List<CalendarInfo> calendars = new ArrayList<>(); for (UserHandle user : UserManager.get(context).getUserProfiles()) { final Context userContext = getContextForUser(context, user); if (userContext != null) { addCalendars(userContext, calendars); } } Collections.sort(calendars, CALENDAR_NAME); return calendars; }
public static boolean supportsDrop(Context context, Object info) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); Bundle restrictions = userManager.getUserRestrictions(); if (restrictions.getBoolean(UserManager.DISALLOW_APPS_CONTROL, false) || restrictions.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS, false)) { return false; } return getUninstallTarget(context, info) != null; }
/** * 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; }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private void updateEnabledState() { // This method uses AppRestrictions directly, rather than using the Policy interface, // because it must be callable in contexts in which the native library hasn't been // loaded. It will always be called from a background thread (except possibly in tests) // so can get the App Restrictions synchronously. UserManager userManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE); Bundle appRestrictions = userManager .getApplicationRestrictions(getContext().getPackageName()); setEnabled(appRestrictions.getBoolean(SUPERVISED_USER_CONTENT_PROVIDER_ENABLED)); }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static boolean supportsDrop(Context context, Object info) { if (Utilities.ATLEAST_JB_MR2) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); Bundle restrictions = userManager.getUserRestrictions(); if (restrictions.getBoolean(UserManager.DISALLOW_APPS_CONTROL, false) || restrictions.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS, false)) { return false; } } Pair<ComponentName, Integer> componentInfo = getAppInfoFlags(info); return componentInfo != null && (componentInfo.second & AppInfo.DOWNLOADED_FLAG) != 0; }
/** * Creates workspace loader from an XML resource listed in the app restrictions. * * @return the loader if the restrictions are set and the resource exists; null otherwise. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) { // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18 if (!Utilities.ATLEAST_JB_MR2) { return null; } Context ctx = getContext(); UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE); Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName()); if (bundle == null) { return null; } String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME); if (packageName != null) { try { Resources targetResources = ctx.getPackageManager() .getResourcesForApplication(packageName); return AutoInstallsLayout.get(ctx, packageName, targetResources, widgetHost, mOpenHelper); } catch (NameNotFoundException e) { Log.e(TAG, "Target package for restricted profile not found", e); return null; } } return null; }
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(); } } }
/** * Dirty fix, since the UserManager.get() method is marked as hidden and can't be * accessed directly, the current solution it's to use reflection to invoke the get method. * * @param app - the Application instance where UserManager.get() will be triggered */ @TargetApi(17) public static void fixLeakInGetMethod(Application app) { try { final Method m = UserManager.class.getMethod(GET_METHOD, Context.class); m.setAccessible(true); m.invoke(null, app); //above is reflection for below... //UserManager.get(); } catch (Throwable e) { Log.e(TAG, e.getLocalizedMessage(), e.getCause()); } }
private static void launchAndroidForWork(Context context, ComponentName componentName, Bundle bundle, long userId) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE); try { launcherApps.startMainActivity(componentName, userManager.getUserForSerialNumber(userId), null, bundle); } catch (ActivityNotFoundException | NullPointerException e) { /* Gracefully fail */ } }
public long getUserId(Context context) { if(userId == null) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); return userManager.getSerialNumberForUser(Process.myUserHandle()); } else return userId; }
public Drawable 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); if(loadedIcon instanceof BitmapDrawable) drawable = (BitmapDrawable) loadedIcon; else { int width = Math.max(loadedIcon.getIntrinsicWidth(), 1); int height = Math.max(loadedIcon.getIntrinsicHeight(), 1); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); loadedIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); loadedIcon.draw(canvas); drawable = new BitmapDrawable(context.getResources(), bitmap); } drawables.put(name, drawable); } } return drawable; }
/** Returns whether the clings are enabled or should be shown */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private boolean areClingsEnabled() { // 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 if (Utilities.ATLEAST_JB_MR2) { 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; }
/** * Creates workspace loader from an XML resource listed in the app restrictions. * * @return the loader if the restrictions are set and the resource exists; null otherwise. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction() { // UserManager.getApplicationRestrictions() requires minSdkVersion >= 18 if (!Utilities.ATLEAST_JB_MR2) { return null; } Context ctx = getContext(); UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE); Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName()); if (bundle == null) { return null; } String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME); if (packageName != null) { try { Resources targetResources = ctx.getPackageManager() .getResourcesForApplication(packageName); return AutoInstallsLayout.get(ctx, packageName, targetResources, mOpenHelper.mAppWidgetHost, mOpenHelper); } catch (NameNotFoundException e) { Log.e(TAG, "Target package for restricted profile not found", e); return null; } } return null; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean canAddAccounts() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return true; UserManager userManager = (UserManager) getActivity() .getSystemService(Context.USER_SERVICE); return !userManager.hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS); }
@SuppressLint("InlinedApi") @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private static boolean hasSyncPermissions(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) return true; UserManager manager = (UserManager) context.getSystemService(Context.USER_SERVICE); Bundle userRestrictions = manager.getUserRestrictions(); return !userRestrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false); }
@SuppressLint("NewApi") public static boolean isAdminUser(Context context) { final UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE); try { Method getUserHandle = UserManager.class.getMethod("getUserHandle"); int userHandle = (Integer)getUserHandle.invoke(um); return userHandle == 0; } catch (Exception ex) { return true; } }
public AppRestrictionsProvider(Context context) { super(context); // getApplicationRestrictions method of UserManager was introduced in JELLY_BEAN_MR2. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); } else { mUserManager = null; } }
@TargetApi(Build.VERSION_CODES.O) @Override public void onUserAdded(Context context, Intent intent, UserHandle newUser) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); String message = context.getString(R.string.on_user_added_message, userManager.getSerialNumberForUser(newUser)); Log.i(TAG, message); NotificationUtil.showNotification(context, R.string.on_user_added_title, message, NotificationUtil.USER_ADDED_NOTIFICATION_ID); }
@TargetApi(Build.VERSION_CODES.O) @Override public void onUserRemoved(Context context, Intent intent, UserHandle removedUser) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); String message = context.getString(R.string.on_user_removed_message, userManager.getSerialNumberForUser(removedUser)); Log.i(TAG, message); NotificationUtil.showNotification(context, R.string.on_user_removed_title, message, NotificationUtil.USER_REMOVED_NOTIFICATION_ID); }
@Override public void onCreate(Bundle savedInstanceState) { 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); mPackageManager = getActivity().getPackageManager(); mPackageName = getActivity().getPackageName(); mImageUri = getStorageUri("image.jpg"); mVideoUri = getStorageUri("video.mp4"); super.onCreate(savedInstanceState); }
@Override public void onCreate(Bundle savedInstanceState) { mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService( Context.DEVICE_POLICY_SERVICE); mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE); mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity()); super.onCreate(savedInstanceState); getActivity().getActionBar().setTitle(R.string.user_restrictions_management_title); }
private void disableUserRestrictions() { if (BuildCompat.isAtLeastN()) { // DPC is allowed to bypass DISALLOW_MODIFY_ACCOUNTS on N or above. Log.v(TAG, "skip disabling user restriction on N or above"); return; } Log.v(TAG, "disabling user restrictions"); mDisallowModifyAccounts = mUserManager.hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS); mDevicePolicyManager .clearUserRestriction(mAdminComponentName, UserManager.DISALLOW_MODIFY_ACCOUNTS); }
private void restoreUserRestrictions() { if (BuildCompat.isAtLeastN()) { // DPC is allowed to bypass DISALLOW_MODIFY_ACCOUNTS on N or above. Log.v(TAG, "skip restoring user restrictions on N or above"); return; } Log.v(TAG, "restoring user restrictions"); if (mDisallowModifyAccounts) { mDevicePolicyManager .addUserRestriction(mAdminComponentName, UserManager.DISALLOW_MODIFY_ACCOUNTS); } }
@TargetApi(VERSION_CODES.M) public static boolean isPrimaryUser(Context context) { if (isAtLeastM()) { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); return userManager.isSystemUser(); } else { // Assume only DO can be primary user. This is not perfect but the cases in which it is // wrong are uncommon and require adb to set up. return isDeviceOwner(context); } }
@Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(R.xml.bind_device_admin_policies); mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE); mHideLauncherIconPreference = (DpcSwitchPreference) findPreference(KEY_HIDE_PO_LAUNCHER_ICON); mHideLauncherIconPreference.setOnPreferenceChangeListener(this); mInstallCaCertificatePreference = (DpcPreference) findPreference( KEY_INSTALL_CA_CERTIFICATE); mInstallCaCertificatePreference.setOnPreferenceClickListener( preference -> { Util.showFileViewerForImportingCertificate(this, INSTALL_CA_CERTIFICATE_REQUEST_CODE); return true; } ); // Hiding the launcher icon doesn't make sense for secondary users, so we disable the option mHideLauncherIconPreference.setCustomConstraint( getCustomConstraint(R.string.po_user_is_secondary)); // Installing certificates makes sense for managed profile and secondary users. mInstallCaCertificatePreference.setCustomConstraint( getCustomConstraint(NO_CUSTOM_CONSTRIANT)); }