Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 805
Sander van't Veer Avatar asked Jan 25 '12 12:01

Sander van't Veer


1 Answers

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.

like image 92
Vladimir Avatar answered Sep 28 '22 01:09

Vladimir