Java Code Examples for android.app.admin.DevicePolicyManager#isAdminActive()

The following examples show how to use android.app.admin.DevicePolicyManager#isAdminActive() . 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: U.java    From SecondScreen with Apache License 2.0 6 votes vote down vote up
public static void lockDevice(Context context) {
    if(isInNonRootMode(context)) {
        ComponentName component = new ComponentName(context, LockDeviceReceiver.class);
        context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        if(mDevicePolicyManager.isAdminActive(component))
            mDevicePolicyManager.lockNow();
        else {
            Intent intent = new Intent(context, LockDeviceActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

            if(context instanceof Activity)
                ((Activity) context).overridePendingTransition(0, 0);
        }
    } else
        runCommand(context, "input keyevent 26");
}
 
Example 2
Source File: ScreenOffActivity.java    From android-screen-off with MIT License 6 votes vote down vote up
/**
 * Turns the screen off and locks the device, provided that proper rights
 * are given.
 * 
 * @param context
 *            - The application context
 */
static void turnScreenOff(final Context context) {
	DevicePolicyManager policyManager = (DevicePolicyManager) context
			.getSystemService(Context.DEVICE_POLICY_SERVICE);
	ComponentName adminReceiver = new ComponentName(context,
			ScreenOffAdminReceiver.class);
	boolean admin = policyManager.isAdminActive(adminReceiver);
	if (admin) {
		Log.i(LOG_TAG, "Going to sleep now.");
		policyManager.lockNow();
	} else {
		Log.i(LOG_TAG, "Not an admin");
		Toast.makeText(context, R.string.device_admin_not_enabled,
				Toast.LENGTH_LONG).show();
	}
}
 
Example 3
Source File: MainActivity.java    From product-emm with Apache License 2.0 6 votes vote down vote up
/**
 * Start device admin activation request.
 *
 * @param cdmDeviceAdmin - Device admin component.
 */
private void startDeviceAdminPrompt(ComponentName cdmDeviceAdmin) {
    DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        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);
    } else {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
 
Example 4
Source File: MainActivity.java    From android-kiosk-example with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    ComponentName deviceAdmin = new ComponentName(this, AdminReceiver.class);
    mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    if (!mDpm.isAdminActive(deviceAdmin)) {
        Toast.makeText(this, getString(R.string.not_device_admin), Toast.LENGTH_SHORT).show();
    }

    if (mDpm.isDeviceOwnerApp(getPackageName())) {
        mDpm.setLockTaskPackages(deviceAdmin, new String[]{getPackageName()});
    } else {
        Toast.makeText(this, getString(R.string.not_device_owner), Toast.LENGTH_SHORT).show();
    }

    mDecorView = getWindow().getDecorView();

    mWebView.loadUrl("http://www.vicarasolutions.com/");
}
 
Example 5
Source File: DevicePolicyManagerUtils.java    From FreezeYou with Apache License 2.0 5 votes vote down vote up
/**
 * 优先 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);
        }
    }
}
 
Example 6
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
/**
  * wipe
  */
 private void wipe() {
 	
 	Util.logDebug("wipe()");
 	
 	DevicePolicyManager mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
 	ComponentName mDeviceAdmin = new ComponentName(this, MdmDeviceAdminReceiver.class);        
     if (mDPM.isAdminActive(mDeviceAdmin)) {
mDPM.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
     }
 	
 }
 
Example 7
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
/**
  * lock
  */
 private void lock() {
 	
 	Util.logDebug("lock()");

 	DevicePolicyManager mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
 	ComponentName mDeviceAdmin = new ComponentName(this, MdmDeviceAdminReceiver.class);        
     if (mDPM.isAdminActive(mDeviceAdmin)) {
mDPM.lockNow();
     }
 	
 }
 
Example 8
Source File: LocalReceiverActivity.java    From AcDisplay with GNU General Public License v2.0 5 votes vote down vote up
private void removeDeviceAdminRights() {
    ComponentName component = AdminReceiver.newComponentName(this);
    DevicePolicyManager dpm = (DevicePolicyManager)
            getSystemService(Context.DEVICE_POLICY_SERVICE);

    if (dpm.isAdminActive(component)) {
        try {
            dpm.removeActiveAdmin(component);
            ToastUtils.showShort(this, R.string.permissions_device_admin_removed);
        } catch (SecurityException ignored) {
        }
    }
}
 
Example 9
Source File: FloatingBallUtils.java    From RelaxFinger with GNU General Public License v2.0 5 votes vote down vote up
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 10
Source File: DeviceAdminReceiverLock.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * スクリーンロックを行う
 * @return スクリーンロックできればtrue
 */
private static boolean checkScreenLock(@NonNull final Activity activity, final boolean finish) {
	final ComponentName cn = new ComponentName(activity, DeviceAdminReceiverLock.class);
	final DevicePolicyManager dpm = ContextUtils.requireSystemService(activity, DevicePolicyManager.class);
	if (dpm.isAdminActive(cn)){
		// デバイス管理者が有効ならスクリーンをロック
		dpm.lockNow();
		if (finish) {
			activity.finish();
		}
		return true;
	}
	return false;
}
 
Example 11
Source File: Utils.java    From always-on-amoled with GNU General Public License v3.0 4 votes vote down vote up
public static boolean hasDeviceAdminPermission(Context context) {
    ComponentName mAdminName = new ComponentName(context, DAReceiver.class);
    DevicePolicyManager mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
    return mDPM != null && mDPM.isAdminActive(mAdminName);
}
 
Example 12
Source File: OperationProcessor.java    From product-emm with Apache License 2.0 4 votes vote down vote up
private boolean isDeviceAdminActive() {
	DevicePolicyManager devicePolicyManager =
			(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
	ComponentName cdmDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class);
	return devicePolicyManager.isAdminActive(cdmDeviceAdmin);
}
 
Example 13
Source File: EnrollmentService.java    From product-emm with Apache License 2.0 4 votes vote down vote up
private boolean isDeviceAdminActive() {
    DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    return devicePolicyManager.isAdminActive(cdmDeviceAdmin);
}
 
Example 14
Source File: AlreadyRegisteredActivity.java    From product-emm with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_already_registered);
	getSupportActionBar().setDisplayShowCustomEnabled(true);
	getSupportActionBar().setCustomView(R.layout.custom_sherlock_bar);
	getSupportActionBar().setTitle(R.string.empty_app_title);

	DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
	ComponentName cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class);
	context = this;
	resources = context.getResources();
	Bundle extras = getIntent().getExtras();
	
	if (extras != null) {
		if (extras.
				containsKey(getResources().getString(R.string.intent_extra_fresh_reg_flag))) {
			freshRegFlag = extras.getBoolean(
                                getResources().getString(R.string.intent_extra_fresh_reg_flag));
		}

	}

	String registrationId =
			Preference.getString(context, resources.
			                     			getString(R.string.shared_pref_regId));
	
	if (!registrationId.isEmpty()) {
		regId = registrationId;
	}

	if (freshRegFlag) {
		Preference.putString(context, resources.getString(R.string.shared_pref_registered),
		                     			resources.getString(R.string.shared_pref_reg_success));

		if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
			startDeviceAdminPrompt(cdmDeviceAdmin);
		}

		freshRegFlag = false;
	}
	
	txtRegText = (TextView) findViewById(R.id.txtRegText);
	btnUnregister = (Button) findViewById(R.id.btnUnreg);
	btnUnregister.setTag(TAG_BTN_UNREGISTER);
	btnUnregister.setOnClickListener(onClickListenerButtonClicked);
	LocalNotification.startPolling(context);

}
 
Example 15
Source File: SettingsFragment.java    From always-on-amoled with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean onPreferenceChange(final Preference preference, Object o) {
    prefs.apply();
    Utils.logDebug("Preference change", preference.getKey() + " Value:" + o.toString());

    if (preference.getKey().equals("notifications_alerts")) {
        if ((boolean) o)
            return checkNotificationsPermission(context, true);
        return true;
    }
    if (preference.getKey().equals("raise_to_wake")) {
        if (!Utils.hasFingerprintSensor(context))
            askDeviceAdmin(R.string.settings_raise_to_wake_device_admin);
        restartService();
    }
    if (preference.getKey().equals("stop_delay"))
        if (!Utils.hasFingerprintSensor(context))
            askDeviceAdmin(R.string.settings_raise_to_wake_device_admin);
    if (preference.getKey().equals("persistent_notification") && !(boolean) o) {
        Snackbar.make(rootView, R.string.warning_1_harm_performance, 10000).setAction(R.string.action_revert, v -> {
            ((CheckBoxPreference) preference).setChecked(true);
            restartService();
        }).show();
        restartService();
    }
    if (preference.getKey().equals("enabled")) {
        context.sendBroadcast(new Intent(TOGGLED));
        restartService();
    }
    if (preference.getKey().equals("proximity_to_lock")) {
        if (Shell.SU.available() || (Utils.isAndroidNewerThanL() && !Build.MANUFACTURER.equalsIgnoreCase("samsung")))
            return true;
        else {
            DevicePolicyManager mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            if ((mDPM != null && mDPM.isAdminActive(mAdminName))) {
                return true;
            }
            new AlertDialog.Builder(getActivity()).setTitle(getString(android.R.string.dialog_alert_title) + "!")
                    .setMessage(getString(R.string.warning_7_disable_fingerprint))
                    .setPositiveButton(getString(android.R.string.yes), (dialogInterface, i) -> {
                        askDeviceAdmin(R.string.settings_raise_to_wake_device_admin);
                    })
                    .setNegativeButton(getString(android.R.string.no), (dialogInterface, i) -> {
                        dialogInterface.dismiss();
                    })
                    .show();
            return false;
        }
    }
    if (preference.getKey().equals("startafterlock") && !(boolean) o)
        Snackbar.make(rootView, R.string.warning_4_device_not_secured, 10000).setAction(R.string.action_revert, v -> ((CheckBoxPreference) preference).setChecked(true)).show();
    if (preference.getKey().equals("doze_mode") && (boolean) o) {
        if (Shell.SU.available()) {
            if (!DozeManager.isDumpPermissionGranted(context))
                DozeManager.grantPermission(context, "android.permission.DUMP");
            if (!DozeManager.isDevicePowerPermissionGranted(context))
                DozeManager.grantPermission(context, "android.permission.DEVICE_POWER");
            return true;
        }
        Snackbar.make(rootView, R.string.warning_11_no_root, Snackbar.LENGTH_LONG).show();
        return false;
    }
    if (preference.getKey().equals("greenify_enabled") && (boolean) o) {
        if (!isPackageInstalled("com.oasisfeng.greenify")) {
            openPlayStoreUrl("com.oasisfeng.greenify", context);
            return false;
        }
    }
    if (preference.getKey().equals("camera_shortcut") || preference.getKey().equals("google_now_shortcut")) {
        try {
            if (!hasUsageAccess()) {
                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                PackageManager packageManager = getActivity().getPackageManager();
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(context, "Please grant usage access permission manually for the app, your device can't do it automatically.", Toast.LENGTH_LONG).show();
                }
                return false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    if (preference.getKey().equals("battery_saver"))
        if ((boolean) o) {
            ((TwoStatePreference) findPreference("doze_mode")).setChecked(true);
            setUpBatterySaverPermission();
        }
    return true;
}
 
Example 16
Source File: URMUtils.java    From rebootmenu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 用辅助功能锁屏
 *
 * @param activity            1
 * @param componentName       2
 * @param requestCode         3
 * @param devicePolicyManager 4
 * @param needConfig          是否需要 配置管理员
 */

public static void lockScreen(@NonNull Activity activity, ComponentName componentName, int requestCode, DevicePolicyManager devicePolicyManager, boolean needConfig) {
    new DebugLog("lockScreen", DebugLog.LogLevel.V);
    //设备管理器是否启用
    boolean active = devicePolicyManager.isAdminActive(componentName);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        //自动移除不必要的管理员,避免在卸载时造成困扰
        if (active) devicePolicyManager.removeActiveAdmin(componentName);
        //请求打开辅助服务设置
        if (!isAccessibilitySettingsOn(activity.getApplicationContext())) {
            new TextToast(activity.getApplicationContext(), activity.getString(R.string.service_disabled));
            try {
                activity.startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
            } catch (Throwable t) {
                t.printStackTrace();
                UIUtils.visibleHint(activity, R.string.accessibility_settings_not_found);
            }
        } else
            LocalBroadcastManager.getInstance(activity).sendBroadcast(new Intent(UnRootAccessibility.LOCK_SCREEN_ACTION));
        activity.finish();
    } else {
        if (!active) {
            //请求启用
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, activity.getString(R.string.service_explanation));
            try {
                activity.startActivityForResult(intent, requestCode);
            } catch (ActivityNotFoundException e) {
                UIUtils.visibleHint(activity, R.string.hint_add_dev_admin_activity_not_found);
            }
        } else {
            devicePolicyManager.lockNow();
            if (needConfig)
                //如果需要二次确认,禁用设备管理器。(这里的策略和root模式的锁屏无需确认不同)
                if (!ConfigManager.get(ConfigManager.NO_NEED_TO_CONFIRM)) {
                    devicePolicyManager.removeActiveAdmin(componentName);
                }
            activity.finish();
        }
    }
}
 
Example 17
Source File: Lock.java    From Pi-Locker with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("static-access")
public void CreateTheLayout() {

	context = this;

	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	twifi = (WifiManager) getSystemService(Lock.WIFI_SERVICE);
	cm = (ConnectivityManager) context
			.getSystemService(context.CONNECTIVITY_SERVICE);
	am = (AudioManager) getSystemService(context.AUDIO_SERVICE);

	manager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
	carrierName = manager.getNetworkOperatorName();
	carrier = (TextView) findViewById(R.id.textView2);
	carrier.setText(carrierName.toUpperCase());

	pm = context.getPackageManager();

	gLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
	gOverlay = (GestureOverlayView) findViewById(R.id.gestureOverlayView1);
	gOverlay.addOnGesturePerformedListener(this);

	battery = (TextView) findViewById(R.id.battery);
	Date = (TextView) findViewById(R.id.date);
	Time = (TextView) findViewById(R.id.time);
	text = (TextView) findViewById(R.id.texts);
	data = (TextView) findViewById(R.id.textView4);
	msgs = (TextView) findViewById(R.id.textView7);
	calls = (TextView) findViewById(R.id.textView5);
	bluetooth = (TextView) findViewById(R.id.textView3);
	wifi = (TextView) findViewById(R.id.textView1);
	sound = (TextView) findViewById(R.id.textView6);
	whats = (TextView) findViewById(R.id.textView8);
	pmm = (TextView) findViewById(R.id.pm);


	policyManager = (DevicePolicyManager) context
			.getSystemService(Context.DEVICE_POLICY_SERVICE);
	adminReceiver = new ComponentName(context, DeviceAdmin.class);
	admin = policyManager.isAdminActive(adminReceiver);

	r0 = (TableLayout) findViewById(R.id.r0);
	r0.setDrawingCacheEnabled(true);
	r0.buildDrawingCache();

	v1 = (View)findViewById(R.id.v1);
	v2 = (View)findViewById(R.id.v2);
}
 
Example 18
Source File: OBSystemsManager.java    From GLEXP-Team-onebillion with Apache License 2.0 4 votes vote down vote up
public boolean hasAdministratorPrivileges()
{
    DevicePolicyManager devicePolicyManager = (DevicePolicyManager) MainActivity.mainActivity.getSystemService(Context.DEVICE_POLICY_SERVICE);
    return devicePolicyManager.isAdminActive(AdministratorReceiver());
}