Android如何打开/关闭系统解锁服务?—典型错误分析
最近正在做一个Android的解锁应用,需要屏蔽系统解锁,并在适当的时候打开系统解锁,在网上search了很多有关系统解锁的资料,学到了很多关于系统解锁方面的知识,同时也发现了很多网友犯下的一个共同的错误。现分享一下:
错误一:总所周知,要关闭系统自带的锁屏服务需要用到以下代码:
mKeyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
mKeylock = mKeyguard.newKeyguardLock("");
mKeylock.disableKeyguard();
要打开系统锁屏服务需要以下代码:
mKeylock.reenableKeyguard()
网上很多朋友对disableKeyguard()的理解为:将屏幕打开并解锁,只要执行这个方法就会是屏幕变亮并自动解锁!同样reenableKeyguard()的作用是关闭屏幕并上锁!
大错而特错了!
我们来看看google api对这两个方法的解释:
disableKeyguard: Disable the keyguard from showing. If the keyguard is currently showing, hide it. The keyguard will be prevented from showing again untilreenableKeyguard() is called.
reenableKeyguard: Reenable the keyguard. The keyguard will reappear if the previous call todisableKeyguard() caused it it to be hidden.
所以,disableKeyguard只是关闭系统锁屏服务,调用该方法后并不会立即解锁,而是使之不显示解锁,同样reenableKeyguard是恢复锁屏服务,并不会立即锁屏!
错误二: 下面是通过两个按钮来模拟打开/关闭系统锁屏的代码:package com.example.keyguard;import android.os.Bundle;import android.app.Activity;import android.app.KeyguardManager;import android.app.KeyguardManager.KeyguardLock;import android.content.Context;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.support.v4.app.NavUtils;/** * @author Onejune * @function 打开/关闭系统锁屏服务测试 * @note 在打开/关闭系统锁屏服务时必须使用同一个KeyguardLock对象,否则出错 */public class KeyGuardActivity extends Activity {private Button myButtonOn, myButtonOff;private KeyguardManager km;private KeyguardLock kl;private final String TAG = "KeyGuardTest"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_key_guard); /* 获取KeyGuardManager对象 */ km = (KeyguardManager)this.getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE); /* 获取KeyguardLock对象 */ kl = km.newKeyguardLock(TAG); myButtonOff = (Button)findViewById(R.id.buttonOff); myButtonOff.setOnClickListener(new Button.OnClickListener(){public void onClick(View arg0) {/* 关闭系统锁屏服务 */kl.disableKeyguard(); } }); myButtonOn = (Button)findViewById(R.id.buttonOn); myButtonOn.setOnClickListener(new Button.OnClickListener(){public void onClick(View arg0) {/* 打开系统锁屏服务 */kl.reenableKeyguard(); } }); }}终于OK!
