Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Keep MediaPlayer running during Activity screen orientation update

I use a MediaPlayer to play an MP3. Currently I disabled screen orientation changes by using

android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation"

in the manifest. I do want to support landscape mode now - i.e. removed those tags - but have the problem that during the destroy/create cycle the player gets stopped and then restarted. This is okay and I actually do this even manually in onPause() to stop the player when the activity goes in the background.

To keep it running during orientation changes now, I tried making it static (and using the Application Context to create it once). Of course, when I remove the player.stop() in onPause() now, it does what I want - well, until the Activity goes in the background.

So, two questions:

  • How can I determine if the Activity will be recreated directly after the call to onStop()
  • Or: How can I keep the MediaPlayer running during that cycle, yet stop it when the App goes in the background?
like image 251
sunside Avatar asked Nov 04 '11 19:11

sunside


3 Answers

Have you looked at using the onConfigurationChanged() callback to handle some of this logic?

like image 55
Kurtis Nusbaum Avatar answered Nov 16 '22 10:11

Kurtis Nusbaum


Regarding your question how you can reliably determine whether your Activity is destroyed due to a configuration change, see my answer here: How to save/restore(update) ref to the dialog during screen rotation?(I need ref in onCreate method of activity.)

With this, the answer to your second question should be easy.

like image 24
class stacker Avatar answered Nov 16 '22 11:11

class stacker


Try running MediaPlayer in different Thread.

You can add to this thread a more complex API to which you can call from onCreate/onStop/on*

like image 1
talel Avatar answered Nov 16 '22 11:11

talel