一、项目简介:
项目:《Android 一键锁屏》
开发周期:4天
代码量:100行
————————————————————————
二、项目流程:
三、项目代码
1、主程序代码:
Java代码
private DevicePolicyManager policyManager;
private ComponentName componentName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locklayout);
//获取设备管理服务
policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
//AdminReceiver 继承自 DeviceAdminReceiver
componentName = new ComponentName(this, AdminReceiver.class);
mylock();
// killMyself ,锁屏之后就立即kill掉我们的Activity,避免资源的浪费;
android.os.Process.killProcess(android.os.Process.myPid());
}
2、其中,mylock()为:
Java代码
private void mylock(){
boolean active = policyManager.isAdminActive(componentName);
if(!active){//若无权限
activeManage();//去获得权限
policyManager.lockNow();//并锁屏
}
if (active) {
policyManager.lockNow();//直接锁屏
}
}
3、activeManage()代码为:
Java代码
private void activeManage() {
// 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//权限列表
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
//描述(additional explanation)
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "------ 其他描述 ------");
startActivityForResult(intent, 0);
}
4、AndroidManifest.xml
Java代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.hnu"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".LockFirst"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 设备管理 -->
<receiver android:name=".AdminReceiver"
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>
</application>
</manifest>
5、其中lock_screen.xml(lock_screen.xml文件放在res/xml文件夹下)代码为:
Java代码
<?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>
四、项目预览
请求权限界面
锁屏成功
五、附注
程序运行在android2.2以上平台(含2.2)