Chiman
Chiman

Reputation: 163

Android get Lock Timeout Programmatically

I am writing an app to show an activity over the lock screen when the phone is locked and screen off. When the user leave the activity, the keyguard should be shown. The common way to detect whether the phone is locked by by receiver and ACTION.SCREEN_OFF. It works perfectly if the user press lock button the lock and screen off the phone. However, after ICS, the phone may not be locked as soon as the phone is screen off.

So, how can I get the lock event or how can I get the value of Automatically lock as the picture below?

I know inKeyguardRestrictedInputMode() is a way to check if the phone is locked. but it cannot report automatically when the phone is locked just like receiver.

The Screenshot from Setting in Android 4.1.2

Upvotes: 2

Views: 3240

Answers (2)

dinesh
dinesh

Reputation: 531

you can get the timeout value by following code:

mResolver = this.getContentResolver();
    long timeout = Settings.Secure.getInt(mResolver,
            "lock_screen_lock_after_timeout",
            0);

Upvotes: 5

Chiman
Chiman

Reputation: 163

I solved by using thread to check if the device is locked.

The part of code in the service:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Log.d("Receiver", "Screen ON");
        } else {
            new Thread(new mRunnable()).start();  
        }
    }
};

private Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case 1:
            Intent i = new Intent();
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setClass(getBaseContext(), activity.class);
            startActivity(i);
            break;
        }
        super.handleMessage(msg);
    }
};

class mRunnable implements Runnable {
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            if (isLocked()) {
                mHandler.sendEmptyMessage(1);
                Thread.currentThread().interrupt();
            }
            else {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}

private boolean isLocked() {
    mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    return mKeyguardManager.inKeyguardRestrictedInputMode();
}

I listed it here for the others who are finding the answer. I just draft as a solution and I have not consider the performance of the code and program yet.

Upvotes: 0

Related Questions