Check if onStop is invoked from user interaction or screen dimming

I have a media player that stops playing when the user closes the application, either by pressing the "home" button, using the "Back" button, or simply opening another application. To get this behavior, I added onStop() to my main activity, which tells my MediaPlayer (which is in the service) to stop playing music.

However, I would like the music to continue to play when the screen becomes dim, either by using the power button to turn off the screen, or simply by automatically dimming the screen.

Right now, the player also stops playing when the screen dims, which means that the onStop () method is also called.

How can I check if onStop () is called by screen reduction?

I have already applied the PARTIAL_WAKELOCK object to my MediaPlayer object, which, as far as I know, should allow the player to continue working after the screen goes blank.

Do I need to add a partial wakelock to my core business?


I just applied PARTIAL_WAKELOCK both to my main activity and to my media player. Right now, the screen no longer turns off, and when the user presses the power button, the music still stops.

Obviously this does not work as I thought.

Is there a way to achieve the behavior I'm looking for?

+6
source share
1 answer

You can add

 private boolean stoppedByUser = false; 

in your activity, set false in onStart() , true in onBackPressed () and onUserLeaveHint () and check its value in the onStop() method.

+3
source

Source: https://habr.com/ru/post/906850/


All Articles