Check if onStop is called from user interaction, or screen dimming
Asked Answered
L

1

6

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

However, I would like the music to keep playing whenever the screen gets dimmed, either by using the power button to turn the screen off, or just by the screen auto dimming.

Right now the player also stops playing when the screen dims, meaning that the onStop() method also gets called then.

How can I check if the onStop() gets called by the screen diming?

I already applied a PARTIAL_WAKELOCK to my MediaPlayer object, which to the best of my knowledge, should make it possible for the player to keep running after the screen goes off.

Do I need to add a partial wakelock to my main activity as well?


Just applied a PARTIAL_WAKELOCK to both my main activity, as well as my media player. Right now, the screen doesn't turn off by itself anymore, and when the user presses the power button the music still stops.

Obviously, this doesn't work as I thought it does.

Is there any way of achieving the behavior I'm looking for?

Lara answered 25/1, 2012 at 12:11 Comment(3)
what about having private boolean stoppedByUser = false; field in your activity, setting it to false in onStart(), to true in onBackPressed() and onUserLeaveHint() and checking it's value in onStop()?Erasmoerasmus
That's not a bad idea at all! I'll give it a tryCram
Oh my it actually worked! Please leave your comment as an answer so I can accept it for future searchers.Cram
E
3

You can add

private boolean stoppedByUser = false;

field to your activity, set it to false in onStart(), to true in onBackPressed() and onUserLeaveHint() and check it's value in onStop() method.

Erasmoerasmus answered 25/1, 2012 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.