android.app.admin.DevicePolicyManager Java Examples
The following examples show how to use
android.app.admin.DevicePolicyManager.
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 File: PolicyManagementFragment.java From android-testdpc with Apache License 2.0 | 6 votes |
@TargetApi(VERSION_CODES.N) private void loadPasswordCompliant() { Preference passwordCompliantPreference = findPreference(PASSWORD_COMPLIANT_KEY); if (!passwordCompliantPreference.isEnabled()) { return; } String summary; boolean compliant = mDevicePolicyManager.isActivePasswordSufficient(); if (Util.isManagedProfileOwner(getActivity())) { DevicePolicyManager parentDpm = mDevicePolicyManager.getParentProfileInstance(mAdminComponentName); boolean parentCompliant = parentDpm.isActivePasswordSufficient(); summary = String.format(getString(R.string.password_compliant_profile_summary), Boolean.toString(parentCompliant), Boolean.toString(compliant)); } else { summary = String.format(getString(R.string.password_compliant_summary), Boolean.toString(compliant)); } passwordCompliantPreference.setSummary(summary); }
Example #2
Source File: DeviceAdminSample.java From codeexamples-android with Eclipse Public License 1.0 | 6 votes |
private String statusCodeToString(int newStatusCode) { int newStatus = R.string.encryption_status_unknown; switch (newStatusCode) { case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: newStatus = R.string.encryption_status_unsupported; break; case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: newStatus = R.string.encryption_status_inactive; break; case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: newStatus = R.string.encryption_status_activating; break; case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: newStatus = R.string.encryption_status_active; break; } return mActivity.getString(newStatus); }
Example #3
Source File: BasicManagedProfileFragment.java From enterprise-samples with Apache License 2.0 | 6 votes |
/** * Enables forwarding of share intent between private account and managed profile. */ private void enableForwarding() { Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } DevicePolicyManager manager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); try { IntentFilter filter = new IntentFilter(Intent.ACTION_SEND); filter.addDataType("text/plain"); filter.addDataType("image/jpeg"); // This is how you can register an IntentFilter as allowed pattern of Intent forwarding manager.addCrossProfileIntentFilter(BasicDeviceAdminReceiver.getComponentName(activity), filter, FLAG_MANAGED_CAN_ACCESS_PARENT | FLAG_PARENT_CAN_ACCESS_MANAGED); } catch (IntentFilter.MalformedMimeTypeException e) { e.printStackTrace(); } }
Example #4
Source File: GetAdminActivity.java From odm with GNU General Public License v3.0 | 6 votes |
@Override public void onClick(View v) { /* if (v == lock) { boolean active = deviceManger.isAdminActive(compName); if (active) { deviceManger.lockNow(); } } */ if (v == enable) { Logd(TAG, "Attempting to enable admin"); Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "ODM requires admin access for locking and wiping the device."); startActivityForResult(intent, RESULT_ENABLE); } }
Example #5
Source File: BasicManagedProfileFragment.java From android-BasicManagedProfile with Apache License 2.0 | 6 votes |
/** * Enables forwarding of share intent between private account and managed profile. */ private void enableForwarding() { Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } DevicePolicyManager manager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); try { IntentFilter filter = new IntentFilter(Intent.ACTION_SEND); filter.addDataType("text/plain"); filter.addDataType("image/jpeg"); // This is how you can register an IntentFilter as allowed pattern of Intent forwarding manager.addCrossProfileIntentFilter(BasicDeviceAdminReceiver.getComponentName(activity), filter, FLAG_MANAGED_CAN_ACCESS_PARENT | FLAG_PARENT_CAN_ACCESS_MANAGED); } catch (IntentFilter.MalformedMimeTypeException e) { e.printStackTrace(); } }
Example #6
Source File: ProvisioningValuesLoader.java From enterprise-samples with Apache License 2.0 | 6 votes |
private void gatherAdminExtras(HashMap<String, String> values) { Properties props = new Properties(); Set<String> keys = new HashSet<>(values.keySet()); for (String key : keys) { if (key.startsWith("android.app.extra")) { continue; } props.put(key, values.get(key)); values.remove(key); } StringWriter sw = new StringWriter(); try{ props.store(sw, "admin extras bundle"); values.put(DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE, sw.toString()); Log.d(TAG, "Admin extras bundle=" + values.get( DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE)); } catch (IOException e) { Log.e(TAG, "Unable to build admin extras bundle"); } }
Example #7
Source File: UserManager.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Returns true if the user switcher should be shown, this will be if device supports multi-user * and there are at least 2 users available that are not managed profiles. * @hide * @return true if user switcher should be shown. */ public boolean isUserSwitcherEnabled() { if (!supportsMultipleUsers()) { return false; } if (hasUserRestriction(DISALLOW_USER_SWITCH)) { return false; } // If Demo Mode is on, don't show user switcher if (isDeviceInDemoMode(mContext)) { return false; } List<UserInfo> users = getUsers(true); if (users == null) { return false; } int switchableUserCount = 0; for (UserInfo user : users) { if (user.supportsSwitchToByUser()) { ++switchableUserCount; } } final boolean guestEnabled = !mContext.getSystemService(DevicePolicyManager.class) .getGuestUserDisabled(null); return switchableUserCount > 1 || guestEnabled; }
Example #8
Source File: KeyguardActivity.java From AcDisplay with GNU General Public License v2.0 | 6 votes |
/** * Locks the device (and turns screen off). * * @return {@code true} if successful, {@code false} otherwise. * @see DevicePolicyManager#lockNow() */ public boolean lock() { DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); try { // TODO: Respect secure lock timeout settings. mUnlockingTime = 0; dpm.lockNow(); return true; } catch (SecurityException e) { String errorMessage = "Failed to lock the screen due to a security exception."; ToastUtils.showLong(this, errorMessage); Log.e(TAG, errorMessage); // Clear the FLAG_KEEP_SCREEN_ON flag to prevent the situation when // AcDisplay stays forever on. Normally this should never happen. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); return false; // Screw you owner! } }
Example #9
Source File: Util.java From android-testdpc with Apache License 2.0 | 6 votes |
/** * @return If the certificate was successfully installed. */ public static boolean installCaCertificate(InputStream certificateInputStream, DevicePolicyManager dpm, ComponentName admin) { try { if (certificateInputStream != null) { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int len = 0; while ((len = certificateInputStream.read(buffer)) > 0) { byteBuffer.write(buffer, 0, len); } return dpm.installCaCert(admin, byteBuffer.toByteArray()); } } catch (IOException e) { Log.e(TAG, "installCaCertificate: ", e); } return false; }
Example #10
Source File: OperationManagerOlderSdk.java From product-emm with Apache License 2.0 | 6 votes |
@Override public void clearPassword(Operation operation) { operation.setStatus(getContextResources().getString(R.string.operation_value_completed)); getResultBuilder().build(operation); getDevicePolicyManager().setPasswordQuality(getCdmDeviceAdmin(), DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); getDevicePolicyManager().setPasswordMinimumLength(getCdmDeviceAdmin(), getDefaultPasswordLength()); getDevicePolicyManager().resetPassword(getContextResources().getString(R.string.shared_pref_default_string), DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); getDevicePolicyManager().lockNow(); getDevicePolicyManager().setPasswordQuality(getCdmDeviceAdmin(), DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); if (Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "Password cleared"); } }
Example #11
Source File: SetupManagementFragment.java From android-testdpc with Apache License 2.0 | 6 votes |
private void specifyDefaultDisclaimers(Intent intent) { if (Util.SDK_INT >= VERSION_CODES.O) { Bundle emmBundle = new Bundle(); emmBundle.putString(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_HEADER, getString(R.string.default_disclaimer_emm_name)); emmBundle.putParcelable(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_CONTENT, resourceToUri(getActivity(), R.raw.emm_disclaimer)); Bundle companyBundle = new Bundle(); companyBundle.putString(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_HEADER, getString(R.string.default_disclaimer_company_name)); companyBundle.putParcelable(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_CONTENT, resourceToUri(getActivity(), R.raw.company_disclaimer)); intent.putExtra(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMERS, new Bundle[] { emmBundle, companyBundle }); } }
Example #12
Source File: Util.java From android-testdpc with Apache License 2.0 | 6 votes |
/** * Sets the persistent device owner state by setting a special app restriction on GmsCore and * notifies GmsCore about the change by sending a broadcast. * * @param state The device owner state to be preserved across factory resets. If null, the * persistent device owner state and the corresponding restiction are cleared. */ @TargetApi(VERSION_CODES.O) public static void setPersistentDoStateWithApplicationRestriction( Context context, DevicePolicyManager dpm, ComponentName admin, String state) { Bundle restrictions = dpm.getApplicationRestrictions(admin, GMSCORE_PACKAGE); if (state == null) { // Clear the restriction restrictions.remove(PERSISTENT_DEVICE_OWNER_STATE); } else { // Set the restriction restrictions.putString(PERSISTENT_DEVICE_OWNER_STATE, state); } dpm.setApplicationRestrictions(admin, GMSCORE_PACKAGE, restrictions); Intent broadcastIntent = new Intent(BROADCAST_ACTION_FRP_CONFIG_CHANGED); broadcastIntent.setPackage(GMSCORE_PACKAGE); broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); context.sendBroadcast(broadcastIntent); }
Example #13
Source File: NfcProvisioningFragment.java From android-NfcProvisioning with Apache License 2.0 | 6 votes |
@Override public void onLoadFinished(Loader<Map<String, String>> loader, Map<String, String> values) { if (loader.getId() == LOADER_PROVISIONING_VALUES) { mProvisioningValues = values; //noinspection deprecation mEditPackageName.setText(values.get( DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME)); if (Build.VERSION.SDK_INT >= 23) { ComponentName name = ComponentName.unflattenFromString(values.get( DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME)); mEditClassName.setText(name.getClassName()); } mEditLocale.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_LOCALE)); mEditTimezone.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE)); mEditWifiSsid.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)); mEditWifiSecurityType.setText(values.get( DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SECURITY_TYPE)); mEditWifiPassword.setText(values.get( DevicePolicyManager.EXTRA_PROVISIONING_WIFI_PASSWORD)); } }
Example #14
Source File: PermissionsHelper.java From android-testdpc with Apache License 2.0 | 6 votes |
/** * Attempts to grant a permission automatically if it is considered dangerous - this only happens * for PO/DO devices. */ @RequiresApi(VERSION_CODES.M) private static boolean maybeGrantDangerousPermission(String permission, ComponentName admin, Context context) { if (!isPermissionDangerous(permission, context)) { return true; } if (!ProvisioningStateUtil.isManagedByTestDPC(context)) { return false; } if (hasPermissionGranted(admin, context, permission)) { return true; } DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context .getSystemService(Context.DEVICE_POLICY_SERVICE); return devicePolicyManager.setPermissionGrantState( admin, context.getPackageName(), permission, DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); }
Example #15
Source File: DelegationFragment.java From android-testdpc with Apache License 2.0 | 6 votes |
@TargetApi(VERSION_CODES.O) static List<DelegationScope> defaultDelegationScopes(boolean showDoOnlyDelegations) { List<DelegationScope> defaultDelegations = new ArrayList<>(); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_CERT_INSTALL)); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_APP_RESTRICTIONS)); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL)); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_PERMISSION_GRANT)); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_PACKAGE_ACCESS)); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP)); defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_CERT_SELECTION)); if (showDoOnlyDelegations) { defaultDelegations.add( new DelegationScope(DevicePolicyManager.DELEGATION_NETWORK_LOGGING)); } return defaultDelegations; }
Example #16
Source File: ProvisioningValuesLoader.java From android-NfcProvisioning with Apache License 2.0 | 6 votes |
private void loadSystemValues(HashMap<String, String> values) { Context context = getContext(); //noinspection deprecation putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME, "com.example.android.deviceowner"); if (Build.VERSION.SDK_INT >= 23) { putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME, "com.example.android.deviceowner/.DeviceOwnerReceiver"); } putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_LOCALE, CompatUtils.getPrimaryLocale(context.getResources().getConfiguration()).toString()); putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE, TimeZone.getDefault().getID()); if (!values.containsKey(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)) { WifiManager wifiManager = (WifiManager) context .getSystemService(Activity.WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); if (info.getNetworkId() != -1) { // Connected to network values.put(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID, trimSsid(info.getSSID())); } } }
Example #17
Source File: KeyguardFeaturesTest.java From AdminControl with GNU General Public License v3.0 | 5 votes |
/** * One keyguard features disabled, no request to disable fingerprint. * @throws Exception any failure. */ @Test public void test_noChangeOneKeyguardFeaturesDisabled() throws Exception { int result = KeyguardFeatures.setFingerprintDisabled( DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS, false); assertEquals(DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS, result); }
Example #18
Source File: ControlYourDeviceActivity.java From AdminControl with GNU General Public License v3.0 | 5 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE); mDeviceOwnerComponent = new ControlDeviceAdminReceiver().getWho(this); setupActionBar(); }
Example #19
Source File: PermissionsHelper.java From android-testdpc with Apache License 2.0 | 5 votes |
@RequiresApi(VERSION_CODES.M) private static boolean hasPermissionGranted( ComponentName componentName, Context context, String permission) { DevicePolicyManager devicePolicyManager = context.getSystemService(DevicePolicyManager.class); return devicePolicyManager .getPermissionGrantState(componentName, context.getPackageName(), permission) == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED; }
Example #20
Source File: KeyguardFeaturesTest.java From AdminControl with GNU General Public License v3.0 | 5 votes |
/** * One keyguard features disabled, request to disable fingerprint. * @throws Exception any failure. */ @Test public void test_changeOneKeyguardFeaturesDisabled() throws Exception { int expected = DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS + DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT; int result = KeyguardFeatures.setFingerprintDisabled( DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS, true); assertEquals(expected, result); }
Example #21
Source File: FloatingBallUtils.java From RelaxFinger with GNU General Public License v2.0 | 5 votes |
public static void lockScreen(){ DevicePolicyManager policyManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName adminReceiver = new ComponentName(context, ScreenOffAdminReceiver.class); boolean admin = policyManager.isAdminActive(adminReceiver); if (admin) { policyManager.lockNow(); } }
Example #22
Source File: IslandManager.java From island with Apache License 2.0 | 5 votes |
@OwnerUser @ProfileUser public static boolean ensureAppHiddenState(final Context context, final String pkg, final boolean state) { final DevicePolicies policies = new DevicePolicies(context); if (policies.invoke(DevicePolicyManager::setApplicationHidden, pkg, state)) return true; // Since setApplicationHidden() return false if already in that state, also check the current state. final boolean hidden = policies.invoke(DevicePolicyManager::isApplicationHidden, pkg); return state == hidden; }
Example #23
Source File: MainActivity.java From AcDisplay with GNU General Public License v2.0 | 5 votes |
/** * Turns screen off and sends a test notification. * * @param cheat {@code true} if it simply starts {@link AcDisplayActivity}, * {@code false} if it turns device off and then uses notification * to wake it up. */ private void startAcDisplayTest(boolean cheat) { if (cheat) { startActivity(new Intent(this, AcDisplayActivity.class)); NotificationHelper.sendNotification(this, App.ID_NOTIFY_TEST); return; } int delay = getResources().getInteger(R.integer.config_test_notification_delay); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Test notification."); wakeLock.acquire(delay); try { // Go sleep DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); dpm.lockNow(); new Handler().postDelayed(new Runnable() { private final Context context = getApplicationContext(); @Override public void run() { NotificationHelper.sendNotification(context, App.ID_NOTIFY_TEST); } }, delay); } catch (SecurityException e) { Log.wtf(TAG, "Failed to turn screen off!"); wakeLock.release(); } }
Example #24
Source File: KeyguardFeaturesTest.java From AdminControl with GNU General Public License v3.0 | 5 votes |
/** * No keyguard features disabled, request to disable fingerprint. * @throws Exception any failure. */ @Test public void test_changeNoKeyguardFeaturesDisabled() throws Exception { int result = KeyguardFeatures.setFingerprintDisabled( DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE, true); assertEquals(DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT, result); }
Example #25
Source File: EnableProfileActivity.java From product-emm with Apache License 2.0 | 5 votes |
private void enableProfile() { DevicePolicyManager manager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = AgentDeviceAdminReceiver.getComponentName(this); // This is the name for the newly created managed profile. manager.setProfileName(componentName, Constants.TAG); // Enable the profile. manager.setProfileEnabled(componentName); }
Example #26
Source File: CommonReceiverOperations.java From android-testdpc with Apache License 2.0 | 5 votes |
@TargetApi(VERSION_CODES.O) public static void onNetworkLogsAvailable(Context context, ComponentName admin, long batchToken, int networkLogsCount) { Log.i(TAG, "onNetworkLogsAvailable(), batchToken: " + batchToken + ", event count: " + networkLogsCount); DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); List<NetworkEvent> events = null; try { events = dpm.retrieveNetworkLogs(admin, batchToken); } catch (SecurityException e) { Log.e(TAG, "Exception while retrieving network logs batch with batchToken: " + batchToken , e); } if (events == null) { Log.e(TAG, "Failed to retrieve network logs batch with batchToken: " + batchToken); showToast(context, context.getString( R.string.on_network_logs_available_token_failure, batchToken)); return; } showToast(context, context.getString(R.string.on_network_logs_available_success, batchToken)); ArrayList<String> loggedEvents = new ArrayList<>(); if (Util.SDK_INT >= VERSION_CODES.P) { for (NetworkEvent event : events) { loggedEvents.add(event.toString()); } } else { events.forEach(event -> loggedEvents.add(event.toString())); } new EventSavingTask(context, batchToken, loggedEvents).execute(); }
Example #27
Source File: SetupViewModel.java From island with Apache License 2.0 | 5 votes |
private static boolean isDeviceEncrypted(final Context context) { final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); if (dpm == null) return false; final int status = dpm.getStorageEncryptionStatus(); return status == ENCRYPTION_STATUS_ACTIVE // TODO: || (SDK_INT >= N && StorageManager.isEncrypted()) || (SDK_INT >= M && status == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY); }
Example #28
Source File: PermissionsHelperTest.java From android-testdpc with Apache License 2.0 | 5 votes |
@Test public void ensureRequiredPermissions_ifPermissionIsDangerousAndDpcIsProfileOwner_shouldReturnTrueAndSetPermissionGrantState() { addPermissionInfo(DANGEROUS_PERMISSION, PermissionInfo.PROTECTION_DANGEROUS); shadowOf(mDevicePolicyManager).setProfileOwner(TESTDPC_ADMIN); boolean requiredPermissionsGranted = PermissionsHelper .ensureRequiredPermissions(new String[]{DANGEROUS_PERMISSION}, TESTDPC_ADMIN, mContext); assertTrue(requiredPermissionsGranted); assertThat(mDevicePolicyManager .getPermissionGrantState(TESTDPC_ADMIN, mContext.getPackageName(), DANGEROUS_PERMISSION)) .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); }
Example #29
Source File: EnableDeviceAdminActivity.java From product-emm with Apache License 2.0 | 5 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class); EnableDeviceAdminActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Intent deviceAdminIntent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); deviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cdmDeviceAdmin); deviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getResources().getString(R.string.device_admin_enable_alert)); startActivityForResult(deviceAdminIntent, ACTIVATION_REQUEST); } }); }
Example #30
Source File: DevicePolicyManagerUtils.java From FreezeYou with Apache License 2.0 | 5 votes |
/** * 优先 ROOT 模式锁屏,失败则尝试 免ROOT 模式锁屏 * * @param context Context */ public static void doLockScreen(Context context) { //先走ROOT,有权限的话就可以不影响SmartLock之类的了 try { Process process = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(process.getOutputStream()); outputStream.writeBytes("input keyevent KEYCODE_POWER" + "\n"); outputStream.writeBytes("exit\n"); outputStream.flush(); process.waitFor(); ProcessUtils.destroyProcess(outputStream, process); } catch (Exception e) { e.printStackTrace(); } PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (pm == null || pm.isScreenOn()) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, DeviceAdminReceiver.class); if (devicePolicyManager != null) { if (devicePolicyManager.isAdminActive(componentName)) { devicePolicyManager.lockNow(); } else { openDevicePolicyManager(context); } } else { showToast(context, R.string.devicePolicyManagerNotFound); } } }