1.创建创建一类继承DeviceAdminReceiver
public class Admin extends DeviceAdminReceiver {
}
2.清单文件配置
<receiver
android:name="com.example.locknow.Admin"
android:description="@string/sample_device_admin_description"
android:label="@string/sample_device_admin"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin_sample" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
3.在res->xml->device_admin_sample.xml,同时修改描述信息,标题等信息
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
</uses-policies>
</device-admin>
4.激活 setting -> security -> device admin...
5.代码激活超级管理员
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
componentName = new ComponentName(this, admin.class);
if (devicePolicyManager.isAdminActive(componentName)) {
devicePolicyManager.lockNow();
finish();
}
}
public void register(View v){
//代码激活超级管理员
//设置激活超级管理员
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//设置激活那个超级管理员
//mDeviceAdminSample : 超级管理员的标示
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
//设置描述信息
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"一键锁屏,非常好用");
startActivity(intent);
}
6.代码注销超级管理员
public void delete(View v){
//注销超级管理员
//判断超级管理员是否激活
if (devicePolicyManager.isAdminActive(componentName)) {
//注销超级管理员
devicePolicyManager.removeActiveAdmin(componentName);
}
}
7.锁屏操作
public void locknow(View v){
//锁屏的操作
devicePolicyManager.lockNow();//锁屏
}