已禁用Keyguard Lock在单击通知后重新启用

时间:2012-10-24 15:29:58

标签: android notifications lockscreen keyguard

在我的应用程序中,我使用下面的代码禁用了键盘锁(即删除锁屏),它可以正常工作,直到我点击通知栏中的任何通知。如果我点击通知,则会自动重新启用锁定屏幕。任何帮助表示赞赏。

private void remove_lockscreen() {
    final CheckBoxPreference lock = (CheckBoxPreference) findPreference("remove_lockscreen");
    KeyguardManager km = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
    KeyguardLock kl = km.newKeyguardLock("keyguard_lock");
    if (lock.isChecked()) {
        prefEdit("remove_lockscreen", 1);
        Toast.makeText(getBaseContext(), "Lockscreen will not be shown", Toast.LENGTH_SHORT).show();
        kl.disableKeyguard();
    }
    else if (!lock.isChecked()) {
        prefEdit("remove_lockscreen", 0);
        Toast.makeText(getBaseContext(), "Lockscreen will be shown", Toast.LENGTH_SHORT).show();
        kl.reenableKeyguard();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}

1 个答案:

答案 0 :(得分:15)

我已经注意到同样的问题了一段时间。它只发生在Honeycomb(Android 3.0)上。经过大量的实验和拔毛,我似乎找到了适合我的解决方案。目前尚不清楚到底发生了什么或为什么,但这是我已经想到的。

似乎在Android 3.0+上,在禁用键盘锁定后,当按下通知时,旧的KeyguardLock会过期,但幸运的是ACTION_USER_PRESENT广播在那时被触发,所以我们有机会纠正这个问题。

从文档中可以明显看出的一点是,在获得新的KeyguardLock并重新启用之前,似乎有必要重新启用旧的KeyguardLock。我发现的另一个“问题”是,在通过旧的KeyguardLock重新启用之后立即禁用,只会产生间歇性的成功。我在禁用之前等待300毫秒解决了这个问题。

这是我的代码的略微简化版本;它应该很容易适应你的应用程序:

private KeyguardLock kl;
private KeyguardManager km;

private final Handler mHandler = new Handler();

private final Runnable runDisableKeyguard = new Runnable() {
    public void run() {
        kl = km.newKeyguardLock(getPackageName());
        kl.disableKeyguard();
    }
};

private void setEnablednessOfKeyguard(boolean enabled) {
    if (enabled) {
        if (kl != null) {
            unregisterReceiver(mUserPresentReceiver);
            mHandler.removeCallbacks(runDisableKeyguard);
            kl.reenableKeyguard();
            kl = null;
        }
    } else {
        if (km.inKeyguardRestrictedInputMode()) {
            registerReceiver(mUserPresentReceiver, userPresent);
        } else {
            if (kl != null)
                kl.reenableKeyguard();
            else
                registerReceiver(mUserPresentReceiver, userPresent);

            mHandler.postDelayed(runDisableKeyguard,  300);
        }
    }
}

private final BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())){
            if (sp_store.getBoolean(KEY_DISABLE_LOCKING, false))
                setEnablednessOfKeyguard(false);
        }
    }
};