Reputation: 2634
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);
}
}
Upvotes: 2
Views: 5784
Reputation: 45503
Why not just pass a OnCompletionListener
to the static function as a 'callback'?
public static int playSample(Context context, int resid, MediaPlayer.OnCompletionListener callback) {
//...
mediaPlayer.setOnCompletionListener(callback);
}
Then use the function like this:
StaticActivity.playSample(this, R.id.random, new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
// do something when playing completes
}
}
If you don't care about a callback in all cases, you can probably just supply null
and only set the OnCompletionListener on the MediaPlayer object if it's not null
.
Upvotes: 2
Reputation: 2108
What do you want to do with the value returned? In the on completion listener, place code to call an external method. Have this external method process the 'return' value
Upvotes: 0
Reputation: 2913
I think it's not a good way by return a value, The onCompletion method is called asynchronously, You can do the thing you want such as playing the next music in this method instead of by the return value.
Upvotes: 1
Reputation: 15689
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
its not a good coding style but if you H A V E to return the result there, you can busyWait like this:
while(ml.Inidcator != PLAY_COMPLETED){
sleep(50) //
}
That means if your static method gets called from the UI Thread it will block anything till play is completed.
Upvotes: 1