Android 通过设备管理器成为管理员进行锁屏

来源:互联网 发布:国产sql注入工具 编辑:程序博客网 时间:2024/05/17 22:49

大多数情况下,大家在网络上能够找到很多通过DevicePolicyManager去获取DEVICE_POLICY_SERVICE 服务,然后通过startActivity去激活。但是这种有个弊端就是要跳出deviceAdmin 界面去激活。

笔者今天为大家分享一个不用通过startActivity 去激活管理员的方法,但是前提是你要有system 权限。

1、首先获取DevicePolicyManager 服务,创建ComponentName。

mDpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);mComponentName = new ComponentName(mContext, XXX.class);

2、在AndroidManifest.xml 中添加标签

<receiver android:name="XXXXXX"       android:label="@string/app_name"       android:description="@string/app_name"       android:permission="android.permission.BIND_DEVICE_ADMIN">       <meta-data android:name="android.app.device_admin"             android:resource="@xml/lock_screen" />       <intent-filter>          <action          android:name="android.app.action.DEVICE_ADMIN_ENABLED" />       </intent-filter>   </receiver>

在res/xml 中添加lock_screen.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> 

3、最后通过调用系统hide 类型的接口setActiveAdmin激活管理员,这个时候你就可以操作设备,控制锁屏密码

private void lockScreen(String passWord){        boolean bActive = mDpm.isAdminActive(mComponentName);        if (bActive) {            mDpm.resetPassword(passWord, 0);            mDpm.lockNow();        } else {            setActiveAdmin();            mDpm.resetPassword(passWord, 0);            mDpm.lockNow();        }}private void setActiveAdmin() {    try {        mDpm.setActiveAdmin(mComponentName, true);    } catch (RuntimeException e) {       // Something bad happened...  could be that it was       // already set, though.       Log.w(TAG, "Exception trying to activate admin "            + mComponentName, e);   }}