简体   繁体   中英

MediaPlayer playback not starting when using Service?

I am making an app which streams music. I am using a service to play music from an online mp3 file in the background. But the the service stops at prepareAsync() and never completes the preparation, and thus the music playback does not start. ie. The onPrepared() method is never called. Note: I used the same code in an activity instead of a service and this problem does not occur. What is wrong here? The code:

public class mp3playerservice extends IntentService implements OnPreparedListener {
    String track;
    String info[];
    String name;
    MediaPlayer mp;
    Bundle extras;


  public mp3playerservice() {
    super("mp3playerservice");
  }

  // Will be called asynchronously be Android
  @Override
  protected void onHandleIntent(Intent intent) {
    extras = intent.getExtras();
    info=extras.getStringArray("info");
    track=info[1];
    name=info[0];
    mp= new MediaPlayer();
    if(mp.isPlaying()){
        mp.release();
        mp=new MediaPlayer();
    }
    start1(track);
    }

    void start1(String a){

        try{
        mp.setDataSource(a);
        mp.setOnPreparedListener(this);
        mp.prepareAsync();
        }catch(Exception e){
            Log.d("error is "+e.toString(),"error came up");
        }

    }


  public void onPrepared(MediaPlayer mp4){

        mp.start();
        Log.d("in here2","okay");
    }


} 

It would have been great if you had also posted the logcat being generated. However, since you are subclassing from IntentService, it appears that once your call to prepareAsync() completes, the service stops itself. The reason for that is because at that point you have effectively finished handling the intent. At this point there are several different ways to fix this. The quickest way, but not the best way, is to change your code so that you call prepare() instead of prepareAsync() and then start() the player and comment out the line that registers the onPreparedListener as well. The best way in my opinion would be to subclass directly from Service and override onStartCommand().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM