先写一个继承DeviceAdminReceiver的子类:
public class MyDeviceAdminReceiver extends DeviceAdminReceiver {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
}
在res目录下新建子目录xml,创建一个xml资源文件,例devices.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<!-- 强行锁定 在里仅这个是需要的-->
<force-lock />
<!-- 清除所有数据(恢复出厂设置) -->
<wipe-data />
<!-- 重置密码 -->
<reset-password />
<!-- 限制密码选择 -->
<limit-password />
<!-- 监控登录尝试 -->
<watch-login />
</uses-policies>
</device-admin>
现在需要去清单文件去注册啦:
<receiver
android:name=".MyDevicesAdminReceiver"
android:description="@string/app_name"
android:label="@string/app_name"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/devices" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
准备工作完毕啦,现在开始去写锁屏的相关代码了:
//定义两个全局变量先
private DevicePolicyManager policyManager;
private ComponentName componentName;
// 获取设备管理服务
policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// AdminReceiver 继承自 DeviceAdminReceiver
componentName = new ComponentName(this, AdminReceiver.class);
判断是否已经激活设备:
private void activeManage() {
// 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
// 权限列表
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
// 描述(additional explanation)
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"激活后才能使用锁屏功能");
startActivityForResult(intent, MY_REQUEST_CODE);
}
再回调的方法中判断是否已经激活过设备了:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 获取权限成功,立即锁屏并finish自己,否则继续获取权限
if (requestCode == MY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
policyManager.lockNow();
finish();
} else {
activeManage();
}
super.onActivityResult(requestCode, resultCode, data);
}
这样子就大功告成了。