I'm trying to create a really simple application for Android that will play a music file (I'm really only just starting to get into Android). I have only one Activity that starts when the application starts, and it starts playing the music file. What I need is that the activity always runs (plays the music), whether you press Back or Home buttons, unless you specifically tell it to shut down from Settings menu, and if you try to run it again, it should just restore that activity to the front (basically, how every other player out there works). What happens for me, though, is that when I press back to return to the menu screen for instance, and click on the app again, it runs another instance of the activity (which I can tell, because the music doubles). What can I do to prevent this? Many thanks.
-
you might want to look at the android service topic. – CChi Feb 07 '13 at 22:34
-
See this previous answer http://stackoverflow.com/a/6706810/57490 and older related question: http://stackoverflow.com/questions/3219726/android-singletask-or-singleinstance-launch-mode – TalkLittle Feb 07 '13 at 22:34
2 Answers
Specify android:launchMode= "singleInstance"
in your manifest file. This means that your activity is your entire application.
Don't forget to save the state of your time of the music. Use SharedPreferences
for saving an integer with the second when the sound ended playing and just restore the state in onResume()
method.
Unfortunately, you cannot play music after you press back button as the activity is destroyed. You must start a service if you wish to do that as the other answer suggests. The reason is that you need a Context object to play music and it will no longer be available after onDestroy()
method is called.
http://developer.android.com/guide/topics/media/mediaplayer.html Here you can find examples of playing media files in a service.

- 1,835
- 15
- 33
-
Tried that, doesn't seem to work. I still get multiple instances. I've read that it's not possible to get multiple instances of the app itself, but somehow it seems like exactly this is happening. – Migiyaka Feb 07 '13 at 22:39
-
Ok, let me explain that a bit more. I want the app to NOT stop playing the file when either Back or Home buttons are clicked (which I have accomplished already), and if I minimize the app, and click on its icon icon it should just maximize, not start another instance of the app or the activity (not sure which one it is at this point). Kinda something like how doubleTwist works, for instance. – Migiyaka Feb 07 '13 at 22:48
-
I got what you are trying to achieve, yit is NOT possible to continue playing the file after pressing back or home button using only activity as it is destroyed/paused. You should use a service instead. You can't minimize your app and continue playing music with you activity. – Taras Leskiv Feb 07 '13 at 22:53