Search code examples
androidandroid-serviceactivity-lifecycleandroid-broadcastreceiver

How to prevent call to onStop() on screen lock


My app has certain functionality that I call in the onStop() method i.e. when I switch between apps.

It has a videoview so I want to switch it to audio only when I switch the apps.

I've implemented this in the onStop() method but when the screen gets locked it calls the onStop() and my app starts background audio playback.

I want to retain the activity when screen gets locked and not switch to background audio playback.

I tried using a broadcast receiver to capture the screen-lock event, but it captures the event after onStop() has been called.

I need help to prevent calling onStop() when screen gets locked or any way to detect the screen lock event before calling the onStop() method.


Solution

  • You can check in onStop whether the screen is off or not. If it is on, simply switch to audio, otherwise do nothing (but don't forget to call the super of onStop).

    @Override
    public void onStop() {
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        if (pm.isScreenOn()) {
           // switch to audio
        }
        super.onStop();
    }