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– CChi2013-02-07 22:34:23 +00:00Commented Feb 7, 2013 at 22:34
- See this previous answer stackoverflow.com/a/6706810/57490 and older related question: stackoverflow.com/questions/3219726/…TalkLittle– TalkLittle2013-02-07 22:34:44 +00:00Commented Feb 7, 2013 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.