权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DEVICE_POWER"/>
代码:
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName adminComponent = new ComponentName(this, WDeviceAdminReceiver.class);
if (devicePolicyManager.isAdminActive(adminComponent)) {
devicePolicyManager.lockNow();
} else {
// 如果设备管理器未激活,请提示用户激活设备管理器
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminComponent);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "请激活设备管理器以使用锁屏功能");
startActivity(intent);
}
广播:
public class WDeviceAdminReceiver extends DeviceAdminReceiver {
//空的就行
}
<receiver
android:name=".WDeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN"
android:exported="true">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
</intent-filter>
</receiver>
res下创建XML文件夹创建device_admin::
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>