1.activity里的代码 获取设备管理器
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//setContentView(R.layout.main);registerReceiver();devicePolicyManager =(DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE);//若未注册设备管理器,跳转到配置界面//若已注册设备管理器,显示取消设备管理器页面if(devicePolicyManager.isAdminActive(new ComponentName(this, DeviceMangerBroadCast.class))){devicePolicyManager.lockNow();finish();}else{Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, new ComponentName(this, DeviceMangerBroadCast.class));startActivityForResult(intent, 1);}}
2.动态注册设备管理器的授权广播
public void registerReceiver(){IntentFilter intentFilter = new IntentFilter();intentFilter.addAction("android.app.action.DEVICE_ADMIN_ENABLED");intentFilter.addAction("android.app.action.DEVICE_ADMIN_DISABLED");registerReceiver(deviceMangerBroadCast,intentFilter);}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(deviceMangerBroadCast);}
3.广播接收器
public class DeviceMangerBroadCast extends DeviceAdminReceiver {@Overridepublic void onEnabled(Context context, Intent intent) {super.onEnabled(context, intent);Toast.makeText(context, "已获取设备管理者权限", Toast.LENGTH_SHORT).show();}@Overridepublic void onDisabled(Context context, Intent intent) {super.onDisabled(context, intent);Toast.makeText(context, "已取消设备管理者权限", Toast.LENGTH_SHORT).show();}
}
4.menifest文件
<receiver android:name=".DeviceMangerBroadCast"android:exported="true" android:permission="android.permission.BIND_DEVICE_ADMIN" > 很关键<meta-dataandroid: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><activity android:name=".MainActivity" android:exported="true" android:enabled="true" android:theme="@style/TransparentTheme"><intent-filter><category android:name="android.intent.category.LAUNCHER"/><action android:name="android.intent.action.MAIN"/></intent-filter></activity>
5.device_admin 文件
<?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>
android一键锁屏代码-CSDN博客