sandoval31 sandoval31 - 4 months ago 34
Android Question

How to deal with MediaPlayer and BaseAdapter

I am implementing a music application from this tutorial.

There is a BaseAdapter class used to display the track list, and a MusicPlayer class to play the music. The both are variables of my main activity class.

public class MainActivity extends Activity implements MediaPlayerControl{
private MediaPlayer musicSrv;
private BaseAdapter songAdt;
...


The MusicPlayer play the next tracks when the current finish. What is the best way to send a message to the BaseAdapter to change the displaying at each new playing track (like changing the color of the current track)?

EDIT

According to the comments, it seems that the use of an interface good be a good option. Could someone write a detail answer that explains how to do it? Thanks.

Answer

Thanks to the comments, I managed to implement a solution with an interface.

This is my Main activity class, that refresh the BaseAdapater each time the song is changed:

public class MainActivity extends Activity implements MusicService.SongChangedListener {
      private MediaPlayer musicSrv;
      private BaseAdapter songAdt;
      ...

      @Override
      public void songChanged(Song currentSong){
           songAdt.notifyDataSetChanged(); // refresh view
      }

And my MusicService class:

public class MusicService extends Service implements MediaPlayer.OnPreparedListener{
...
private MainActivity activity;
...

public void setActivity(MainActivity act){
    //set the activity
    activity = act;
}

public interface SongChangedListener {
     void songChanged(Song song);
}
...
public void playSong(){ 
       // this function is called each time a new song is played
       activity.songChanged(playSong);
       ...
}
Comments