Android动态添加Device Admin权限

/**********************************************************************
 *                 Android动态添加Device Admin权限
 * 说明:
 *     Tony在Android 5上研究的怎么动态添加设备管理员权限。
 *
 *                                2018-6-20 深圳 宝安西乡 曾剑锋
 *********************************************************************/

private void enableDeviceAdmin() {

    ComponentName deviceAdmin = new ComponentName(this, AdminReceiver.class);
    DevicePolicyManager mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

    // First of all, to access anything you must be device owner
    if (mDpm.isDeviceOwnerApp(getPackageName())) {

        // If not device admin, ask to become one
        if (!mDpm.isAdminActive(deviceAdmin) &&
                mDpm.isDeviceOwnerApp(getPackageName())) {

            Log.v(TAG, "Not device admin. Asking device owner to become one.");

            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                    "You need to be a device admin to enable device admin.");

            startActivity(intent);
        }

        // Device owner and admin : enter device admin
        else {
            mDpm.setLockTaskPackages(deviceAdmin, new String[]{
                    getPackageName(), /* PUT OTHER PACKAGE NAMES HERE! /
            });
            startLockTask();
        }
    }

    // Not device owner - can't access anything
    else {
        Log.v(TAG, "Not device owner");
        Toast.makeText(this, "Not device owner", Toast.LENGTH_SHORT).show();
    }
}

 

posted on 2018-06-20 15:44  zengjf  阅读(2545)  评论(0编辑  收藏  举报

导航