I have static method which plays music. How to return value from this method when play completed?
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);
}
}
Why not just pass a
OnCompletionListenerto the static function as a ‘callback’?Then use the function like this:
If you don’t care about a callback in all cases, you can probably just supply
nulland only set the OnCompletionListener on the MediaPlayer object if it’s notnull.