Search code examples
androidlockingscreenpreferenceskeyguard

Android: Can't re-enable the keyguard after disabling it


I'm trying to create an option (using check box preferences) in my app for the user to disable and re-enable the lock screen. I use disableKeyguard() to disable the lock screen and it works flawlessly but I can't get reenableKeyguard() to work. The code is pretty simple, I don't know why it's not working.

public void onSharedPreferenceChanged(SharedPreferences taskprefs,
        String tasks_pref) {
    boolean skiplock = taskprefs.getBoolean("pref_skiplock", false);
    boolean screentimeout = taskprefs.getBoolean("pref_screentimeout",
            false);

    skiplock(skiplock);

    // Log.v("TaskActivity", "Skiplock value is " + skiplock);
    // Log.v("TaskActivity", "ScreenTimeout value is " + screentimeout);
}

private void skiplock(boolean action) {
    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
    KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
    //
    if (action == true) {
        lock.disableKeyguard();
        Toast.makeText(getApplicationContext(), "Lockscreen Disabled",
                Toast.LENGTH_SHORT).show();
    }
    //
    else if (action==false) {
        lock.reenableKeyguard();
        Toast.makeText(getApplicationContext(), "Lockscreen Enabled",
                Toast.LENGTH_SHORT).show();
    }
}

Solution

  • The issue was that a new Keyguard object is created (declared) inside the skiplock() method every single time it is called. A simple solution is to declare the keyguard as a global object and refer to that single object so its status does not get reset when the method finishes executing.

    In short, just use "KeguardLock lock" and "KeyguardManager keyguardManager" as global constructors.