I currently have a listview
and when you click on an item it takes you to a new window and starts playing the song associated to that position
. The problem is when I press the back button to return to the listview
and I press the same item, the music starts playing again, over what is already playing. Is there anyway to fix this, so that when you click on the same item and that song is playing, it won't replay the song? Thanks
2 Answers
Have a look at this article about creating a service to play music. Looks like what you are trying to do.
The other thing you could do is add a function that stops the music when the activies onPause or onStop methods are called. Then the inactive music playing activies will get destroyed by the android OS in its own good time, and you wont have to worry about having multiple music files playing. The down side to this method is that you will only have music playing while the new window is visible. If you change windows, it will halt because the onPause or onStop method will be called. If you want the music to play in the background, I think you need to use the service technique.
To start the service, you can bind to it with an intent or use the startService method.
For example, in the article linked above, the service is started here:
public class MusicDroid extends ListActivity {
public static final String MEDIA_PATH = new String("/sdcard/");
private List<String> songs = new ArrayList<String>();
private MDSInterface mpInterface;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.songlist);
this.bindService(new Intent(MusicDroid.this,MDService.class),
null, mConnection, Context.BIND_AUTO_CREATE); // <- starting service by creating a binding.
}
}
The official Android Services api page should give you a good overview of how to deal with services.

- 921
- 1
- 8
- 18
-
So I read the article and also watched a video on youtube about Android Services, but I still have one question: Do I create the activity and then start the service inside the activity, or the other way around? – Splitusa Jul 12 '11 at 03:30
-
So to answer your question, you can create the activity, and in the activities onCreate method, you can start the service. – aj.esler Jul 19 '11 at 02:36