Chris
Chris

Reputation: 3807

Android detect phone lock event

I want to be able to detect the phone lock event. When my app is running, if I press the red button (call end button/power button), the phone gets locked and the screen goes blank. I want to be able to detect this event, is it possible?

Upvotes: 25

Views: 33115

Answers (4)

Top4o
Top4o

Reputation: 674

Koltin format of Robert's solution.

 override fun onPause() {
        super.onPause()

        // If the screen is off then the device has been locked
        val powerManager = getSystemService(POWER_SERVICE) as PowerManager
        val isScreenOn: Boolean = powerManager.isInteractive
        
        if (!isScreenOn) {
            // The screen has been locked 
            // do stuff...
        }
    }

I am assuming Kitkat version is quite old already.

Upvotes: 0

Khalid Lakhani
Khalid Lakhani

Reputation: 188

Register a broadcast with IntentFilter filter.addAction(Intent.ACTION_USER_PRESENT)

works pretty well even screen is turned on/off

Upvotes: 0

st0le
st0le

Reputation: 33545

Have a Broadcast Receiver

android.intent.action.SCREEN_ON

and

android.intent.action.SCREEN_OFF

Related: Read CommonsWare's Answer Here.

Upvotes: 18

Robert
Robert

Reputation: 38213

Alternatively you could do this:

@Override
protected void onPause()
{
    super.onPause();

    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn;
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        isScreenOn = powerManager.isInteractive();
    } else {
        isScreenOn = powerManager.isScreenOn();
    }

    if (!isScreenOn) {

        // The screen has been locked 
        // do stuff...
    }
}

Upvotes: 37

Related Questions