开发者

Android detect phone lock event

开发者 https://www.devze.com 2023-01-06 09:05 出处:网络
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 b开发者_J

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 b开发者_JS百科e able to detect this event, is it possible?


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...
    }
}


Have a Broadcast Receiver

android.intent.action.SCREEN_ON

and

android.intent.action.SCREEN_OFF

Related: Read CommonsWare's Answer Here.


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

works pretty well even screen is turned on/off


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消