25

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
Chris
  • 3,787
  • 13
  • 42
  • 49

4 Answers4

37

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...
    }
}
Volodymyr Yatsykiv
  • 3,181
  • 1
  • 24
  • 28
Robert
  • 37,670
  • 37
  • 171
  • 213
18

Have a Broadcast Receiver

android.intent.action.SCREEN_ON

and

android.intent.action.SCREEN_OFF

Related: Read CommonsWare's Answer Here.

Community
  • 1
  • 1
st0le
  • 33,375
  • 8
  • 89
  • 89
  • 19
    For the record -- lock off/on is not the same event as screen off/on. – greenoldman Oct 02 '12 at 17:00
  • 2
    Screen Off will occurr even of tje screen goes off when making a phone call –  Apr 06 '14 at 06:35
  • Here's an example of this not catching the lock screen: on Android 5, if I switch users, the OS goes to the lock screen without turning the screen off. – Sam Feb 22 '15 at 04:18
  • Can we disable SCREEN_OFF event when making a phone call ? – Mehul Ranpara May 20 '15 at 13:48
  • Another issue with this is: if the screen automatically turns of after the phone is left idle, the phone might not lock until 5 seconds afterwards. The broadcast is sent on screen off rather than on phone lock. – Sam Sep 30 '17 at 23:07
  • Locking can occur without screen_off event, for example, if device is locked via device admin. – artem Oct 25 '17 at 16:44
0

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

works pretty well even screen is turned on/off

Khalid Lakhani
  • 179
  • 2
  • 10
0

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.

Top4o
  • 547
  • 6
  • 19