greenoldman
greenoldman

Reputation: 21072

How to turn keyguard on in reliable way?

DUPLICATE WARNING: this problem deals with details of Android API, suitable for calling both from some frontend and services, there are many similar threads on SO, but focused only on frontends.

Problem

I would like to turn on keyguard programmatically, so for example user clicks a button in my app and the phone gets locked (to use phone user has to unlock it first).

The catch is -- I would like to find rock-solid way, that works in every valid case.

Attempts

I tried:

So far I pursue the first way (lockNow) with extra hacks that somehow deal with the case when the screen is off, but it extremely ugly, thus I am hoping there is some straightforward way.

Upvotes: 0

Views: 1934

Answers (1)

Dan Lee
Dan Lee

Reputation: 126

One solution could be using thread on postdelayed handler. the catch here is, thread will stay alive even after the screen is off, where your application would be under paused state (unless process is killed)

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        keyLock.reenableKeyguard();
        Log.i("LOCK","key guard back on");
        finish();
    }
}, 300);

Another way of doing this would be to use timer task, but timer task might get killed sometimes (don't know for sure, but my past experiences says not sure)

TimerTask Active = new TimerTask() {
@Override
public void run() {
    keyLock.reenableKeyguard();
    Log.i("LOCK","key guard back on");
    finish();
    }
};
Timer starter = new Timer();
starter.schedule(Active, 300);

I can't be 100% sure this is the "rock solid way" you were looking for, but I've been working with the device policy manager along with the keyguard manager for some while and I came across similar problem that locknow() method would turn off screen and then turns back on devices with android 4.0 above.

I came across this solution while looking through the DDMS debug logs, and hopefully, testing on some devices. So far, it hasn't failed me so here a tip anyway.

  1. Disable keyguard
  2. call locknow()
  3. reenable keyguard in a 300ms or so, with the above methods... ( I prefer the handler and it worked like a charm for me)

Upvotes: 1

Related Questions