从侦听器返回值

时间:2011-12-30 00:32:23

标签: java android

我有播放音乐的静态方法。播放完成后如何从此方法返回值?

public static int playSample(Context context, int resid) {
    AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);

    try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
        mediaPlayer.prepare();
        mediaPlayer.start();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mediaPlayer) {
                // from here i want return some value that play is completed
            }
        });
        afd.close();
    } catch (IllegalArgumentException e) {
        Log.e("a", "Unable to play audio queue do to exception: " + e.getMessage(), e);
    } catch (IllegalStateException e) {
        Log.e("a", "Unable to play audio queue do to exception: " + e.getMessage(), e);
    } catch (IOException e) {
        Log.e("a", "Unable to play audio queue do to exception: " + e.getMessage(), e);
    }
}

4 个答案:

答案 0 :(得分:2)

为什么不将OnCompletionListener作为'回调'传递给静态函数?

public static int playSample(Context context, int resid, MediaPlayer.OnCompletionListener callback) {
    //...
    mediaPlayer.setOnCompletionListener(callback);
}

然后使用这样的函数:

StaticActivity.playSample(this, R.id.random, new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mediaPlayer) {
        // do something when playing completes
    }
}

如果你不关心所有情况下的回调,你可能只提供null并且只在MediaPlayer对象上设置OnCompletionListener,如果它不是null

答案 1 :(得分:1)

public class MediaListener implements MediaPlayer.OnCompletedListener{

    public static final int PLAY_COMPLETED = 12345

    public MediaListener(){}
    public int Indicator = 0 

    public void onCompletion(MediaPlayer mediaPlayer) {
        Indicator = PLAY_COMPLETED
    }
}

...
MediaListener ml = new MediaListener();
mediaPlayer.setOnCompletionListener(ml);
//check ml.Indicator

它不是一个好的编码风格但是如果你在那里返回结果,你可以忙着这样:

while(ml.Inidcator != PLAY_COMPLETED){
    sleep(50) //
}

这意味着如果从UI线程调用静态方法,它将阻止任何事情直到播放完成。

答案 2 :(得分:0)

我认为通过返回值不是一个好方法, onCompletion 方法是异步调用的,你可以做你想要的事情,比如在这种方法中播放下一首音乐而不是返回值。

答案 3 :(得分:0)

您想要对返回的值做什么?在on completion listener中,放置代码以调用外部方法。让这个外部方法处理'return'值