您的位置:首页 > 移动开发 > Android开发

Android 一键锁屏源码(激活、锁屏、删除)

2015-02-03 12:26 459 查看
首先得到安全管理器

private DevicePolicyManager dpm;
dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
得到后添加它所需要的权限,即在配置文件中配置下

在aplication结点中增加如下内容:

<receiver
android:name="com.baoxiu123.studytest1.MyAdmin"
android:description="@string/app_name"
android:label="@string/app_name"
android:permission="android.permission.BIND_DEVICE_ADMIN" >

<meta-data
android:name="android.app.device_admin"
android:resource="@xml/lock" />

<intent-filter>

<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />

</intent-filter>

</receiver>


当然,需要创建一个receiver,一个继承了DeviceAdminReceiver的receiver

如下:

import android.app.admin.DeviceAdminReceiver;

public class MyAdmin extends DeviceAdminReceiver {

}
再创建下<meta-data 中的resource="@xml/lock"/>

lock.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<device-admin
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<uses-policies>
<!--强制锁屏-->
<force-lock/>
</uses-policies>
</device-admin>
这样就可以调用锁屏了,一句就可锁屏

dpm.lockNow();
但这样还得有户在手机的设备管理器中自己去激活它才可以,因此有点麻烦。还有就是激活后的应用不能去删除了,只有取消激活后才能删除,因此,很有必要再实现下激活和删除的代码,代码如下:

// 激活的代码
public void active(View view) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
ComponentName mDeName = new ComponentName(this, MyAdmin.class);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,mDeName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"锁屏");
startActivity(intent);
}
//删除的代码
public void unactive(View view) {
ComponentName mDeName = new ComponentName(this, MyAdmin.class);//得到锁屏的组键
dpm.removeActiveAdmin(mDeName);//先解锁
Intent intent = new Intent();
intent.setAction("android.intent.action.DELETE");//删除的action
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse("package:"+getPackageName()));//把当前应用的包名赛进去
startActivity(intent);
}


OK!大功告成!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: