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

柔情痞子 提交于 2019-12-07 03:46:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9002491/check-if-onstop-is-called-from-user-interaction-or-screen-dimming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!