1) 注册成为系统组件
–> 定义广播接收器DeviceAdminReceiver,重写onEnable(); onDisable()
public class DeviceAdminRC extends DeviceAdminReceiver {
@Override
public void onEnabled(Context context, Intent intent) {
Toast.makeText(context,"Registered",Toast.LENGTH_SHORT).show();
super.onEnabled(context, intent);
}
@Override
public void onDisabled(Context context, Intent intent) {
Toast.makeText(context,"Unregistered",Toast.LENGTH_SHORT).show();
super.onDisabled(context, intent);
}
}
–>manifest 定义receiver
<receiver android:name=".DeviceAdminRC">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin" />
<intent-filter>
<action android:name="android.app.ation.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.ation.DEVICE_ADMIN_DISABLED" />
</intent-filter>
</receiver>
–> 添加device_admin.xml文件
<?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>
–> MainActivity 定义DevicePolicyManager
private DevicePolicyManager devicePolicyManager;
–> 初始化DevicePolicyManager
devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
–> 注册成设备管理者
case R.id.btnRegisterDeviceAdmin:
Intent i = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,new ComponentName(this,DeviceAdminRC.class));
startActivity(i);
break;
–> 取消注册设备管理者
case R.id.btnUnregisterDeviceAdmin:
devicePolicyManager.removeActiveAdmin(new ComponentName(this,DeviceAdminRC.class));
break;
–>锁屏
case R.id.btnLockSreen:
devicePolicyManager.lockNow();
break;