/**
*
* 设备管理器的创建步骤:
* 1.创建一个类实现DeviceAdminReceiver
* 2.在清单文件中注册这个广播接收者
* <receiver
* android:name="com.xxc.lockscreen.MyAdmin"
* 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文件夹,在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>
*/
public class MainActivity extends Activity {
private DevicePolicyManager dpm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
}
public void lockScreen(View view){
ComponentName who = new ComponentName(this, MyAdmin.class);
if(dpm.isAdminActive(who)){
dpm.lockNow();
dpm.resetPassword("", 0);//设置锁屏密码 第一个参数:密码,空字符串则表示取消密码 第二个参数:写0就行
//dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//清除SD卡内容
//dpm.wipeData(0);//恢复出厂设置
}else{
Toast.makeText(getApplicationContext(), "请先激活设备管理器", Toast.LENGTH_SHORT).show();
}
}
/**
* 4.直接跳转到激活设备管理器页面
*/
public void open(View view){
//创建一个添加设备管理的意图
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//激活哪个设备管理器
ComponentName mDeviceAdminSample = new ComponentName(this, MyAdmin.class);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);
//开启设备管理器时的提示信息
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "开启后可一键锁屏...");
startActivity(intent);
}
/**
* 卸载这个注册成设备管理器的APP
*/
public void uninstall(View view){
//1.先取消设备管理器的激活状态
ComponentName mDeviceAdminSample = new ComponentName(this, MyAdmin.class);
dpm.removeActiveAdmin(mDeviceAdminSample);
//2.卸载APP
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse("package:"+getPackageName()));
startActivity(intent);
}
}
/**
* 一个特殊的广播接收者
* @author Administrator
*
*/
public class MyAdmin extends DeviceAdminReceiver {
}
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">一键锁屏</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="sample_device_admin_description">设备管理器的描述信息</string>
<string name="sample_device_admin">设备管理器的标签(描述信息的简化)</string>
</resources>