Android:Service实现了MediaPlayer.onPreparedListener

时间:2014-06-19 15:38:31

标签: android android-service android-mediaplayer

我有一个网络广播流,我想使用MediaPlayer作为服务来实现 主要活动有2个按钮,播放&停止将服务设置为意图,然后根据按钮

启动或停止服务

RadioPlayer服务

public class RadioPlayer extends Service implements MediaPlayer.OnPreparedListener{

public static String ACTION_PLAY = "ACTION_PLAY";
private MediaPlayer mediaplayer = null;
private boolean isPlaying = false;


public int onStartCommand(Intent intent, int flags, int startId){
    Log.d("SERVICE", "Started");
    if(intent.getBooleanExtra(ACTION_PLAY, false)){
            play(); 
    }
    return Service.START_STICKY;
}

private void play(){
    Log.d("SERVICE", "play()");
    if(!isPlaying){

        isPlaying = true;

        try{
          Log.d("SERVICE", "1");    
          mediaplayer = new MediaPlayer();
          Log.d("SERVICE", "2");
          mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
          Log.d("SERVICE", "3");
          mediaplayer.setDataSource("http://X.X.X.X");
          Log.d("SERVICE", "4");
          mediaplayer.prepareAsync();
          Log.d("SERVICE", "5");
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}



public void onDestory(){
    Log.d("SERVICE", "Stop");
    stop();
}

private void stop(){
    Log.d("SERVICE", "stop()");
    if(isPlaying){
        isPlaying = false;
        if(mediaplayer != null){
            mediaplayer.stop();
            mediaplayer.release();
            mediaplayer = null;
        }
        //stopForeground(true);
    }
}

@Override
public void onPrepared(MediaPlayer mp) {
    Log.d("SERVICE", "onPrepared()");
    mediaplayer.start();
            //i have also attempted mp.start() with no cigar

}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

}

onPrepared(MediaPlayer mp)没有被调用(并且我已经等了很长时间才能加载流)。 我是否错过了成功实施onPreparedListener所需的服务?

就Log cat输出而言,执行时我发现的唯一不认识的是AwesomePlayer说数据源被压制......?

06-19 16:45:04.090: D/pre-SERVICE(22731): clicked()
06-19 16:45:04.090: D/SERVICE(22731): Started
06-19 16:45:04.090: D/SERVICE(22731): play()
06-19 16:45:04.090: D/SERVICE(22731): 1
06-19 16:45:04.110: W/qdhwcomposer(327): Excessive delay reading vsync: took 66 ms
06-19 16:45:04.110: D/SERVICE(22731): 2
06-19 16:45:04.110: D/SERVICE(22731): 3
06-19 16:45:04.110: I/AwesomePlayer(331): setDataSource_l(URL suppressed)
06-19 16:45:04.110: D/SERVICE(22731): 4
06-19 16:45:04.110: D/SERVICE(22731): 5
06-19 16:45:04.190: W/qdhwcomposer(327): Excessive delay reading vsync: took 49 ms

UPDATE 在尝试使用.onPrepare之后,我已经设法让服务工作,但是如果我要做这种异步风格,问题仍然存在

2 个答案:

答案 0 :(得分:1)

似乎你没有用你的播放器设置你的onCompletionListener。

尝试在mediaplayer.setOnCompletionListener(this)之后添加mediaplayer.prepareAsync()

答案 1 :(得分:0)

看来这个问题是主观的。 我确实设法使用此代码异步获得成功的流

mediaplayer.prepareAsync();
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){

@Override
public void onPrepared(MediaPlayer mp)}
    mp.start();
} });