1. 创建一个广播,这个获取权限是一个广播操作
<receiver android:name=".activity.DeviceAdminSample" android:label="@string/sample_device_admin" android:description="@string/sample_device_admin_description" android:permission="android.permission.BIND_DEVICE_ADMIN"> <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin_sample" /> //这个xml文件是规定了这个超级权限包含哪些内容,这里需要再创建的一个xml文件夹下面去定义 <intent-filter> <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver>
然后是定义那个 @xml/device_admin_sample文件
<device-admin xmlns:android="http://schemas.android.com/apk/res/android"> <uses-policies> <limit-password /> <watch-login /> <reset-password /> <force-lock /> <wipe-data /> <expire-password /> <encrypted-storage /> <disable-camera /> </uses-policies> </device-admin>
前面的文件定义好了,下面这个DeviceAdminSample是继承自一个系统定义的一个广播类 DeviceAdminReceiver,通过这个广播来获取超级权限
public class DeviceAdminSample extends DeviceAdminReceiver{ void showToast(Context context, String msg) { String status = context.getString(R.string.admin_receiver_status, msg); Toast.makeText(context, status, Toast.LENGTH_SHORT).show(); } @Override public void onEnabled(Context context, Intent intent) { showToast(context, context.getString(R.string.admin_receiver_status_enabled)); } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return context.getString(R.string.admin_receiver_status_disable_warning); } @Override public void onDisabled(Context context, Intent intent) { showToast(context, context.getString(R.string.admin_receiver_status_disabled)); } @Override public void onPasswordChanged(Context context, Intent intent) { showToast(context, context.getString(R.string.admin_receiver_status_pw_changed)); } }
获取权限的代码,通过打开一个 Intent 对象,这个对象通过系统的 DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN 意图,打开获取系统权限那个界面让用户确定是否授予这些权限
public void activeSuperuser(View view) {
ComponentName mDeviceAdminSample = new ComponentName(this, DeviceAdminSample.class); // 那个DeviceAdminSample就是前面我们定义的广播类
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample); // mDeviceAdminSample是 intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, R.string.add_admin_extra_app_text); startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN); // 开启授予权限的那个activity }
接下来就是在获取权限之后通过 DevicePolicyManager来具体操作那些需要权限的操作了
DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); // 获取系统服务
if(dpm.isAdminActive(mDeviceAdminSample)){ // 判断是否已经获取了超级权限
dpm.lockNow(); // 锁屏
}