android 一键锁屏

Android2.2新增一个新的锁屏API,lockNow方法。它位于android.app.admin.DevicePolicyManager包里,下面介绍它的使用方法,希望对大家有所帮助。

要使用DevicePolicyManager来锁屏,首先要定义一个组件。
mComponentname = new ComponentName(OneKeyLockScreen.this, LockScreenAdmin.class);
第一个参数是组件所在的包,第一个参数是组件所在的类。
通过这个管理组件,我们可以启动一个接收器DeviceAdminReceiver,来接收ACTION_DEVICE_ADMIN_ENABLED消息。
这个接收器很简单。继承自DeviceAdminReceiver。
?
1
2
3
4
5
6
7
8
9
10
11
public class LockScreenAdmin extends DeviceAdminReceiver {
 
     void showToast(Context context, CharSequence msg) {
         Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
     }
 
     @Override
     public void onEnabled(Context context, Intent intent) {
         showToast(context, "Device Admin: enabled" );
     }
}

别看它简单,其实它的主要内容是放在AndroidManifest.xml里的。它说明了
?
1
2
3
4
5
6
7
8
< receiver android:name = ".LockScreenAdmin" 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_admin" />
             < intent-filter >
                 < action android:name = "android.app.action.DEVICE_ADMIN_ENABLED" />
             </ intent-filter >
</ receiver >

android:resource="@xml/lock_screen_admin"里内容如下
?
1
2
3
4
5
6
7
<? xml version = "1.0" encoding = "UTF-8" ?>
< device-admin
     < uses-policies >
         < force-lock />
     </ uses-policies >
</ device-admin >

那么怎么启动这个receiver呢,实际上只需要启动一次,以后这个组件就是active状态,可以直接使用lockNow来锁屏了。
?
1
2
3
4
5
6
7
8
9
            // run here when this apk start first time
             Intent intent = new Intent(
                     DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
             intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                     mComponentname);
             // this prompt string show in active ui.
             intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                     "One key lock screen need to active" );
             startActivityForResult(intent, RESULT_ENABLE);

是不是很简单了,以后在2.2系统上,就可以方便地在程序或者桌面来启动它锁屏,保护电源键。

转载自:http://www.bangchui.org/read.php?tid=17


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值