//获取设备管理Manager
DevicePolicyManager policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
//创建MyAdminReceiver,并获取到该类的ComponentName,
ComponentName adminReceiver = new ComponentName(context, MyAdminReceiver.class);
//判断设备管理是否已激活
boolean isActive = policyManager.isAdminActive(adminReceiver);
if(isActive){
//如果该应用的设备管理权限已激活,则熄灭屏幕
policyManager.lockNow();
} else {
openAdmin();
}
//打开设备管理器设置,需用户手动激活
private void openAdmin(){
//创建一个添加设备管理的意图
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//激活哪个设备管理器
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminReceiver);
startActivity(intent);
}
public class MyAdminReceiver extends DeviceAdminReceiver {
//收到设备管理器激活的广播
@Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
}
//收到设备管理器取消激活的广播
@Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
}
}
<receiver
android:name=".receiver.MyAdminReceiver"
android:label="@string/app_name"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<!-- 强制锁定 -->
<force-lock />
<!-- 该文件中也可以配置其他信息 -->
<limit-password />
<watch-login />
<reset-password />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
</uses-policies>
</device-admin>
<!-- 权限 -->
<uses-permission android:name="android.permission.USES_POLICY_FORCE_LOCK" />
|