Oncompletion Listener With Mediaplayer
How do i use the OnCompletion listener for some music? I would like to press a button to go to another activity that plays some music and then goes back when the music playback is
Solution 1:
You should put the code that should be run when the music is completed in the OnCompletionListener
, for example:
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
finish(); // finish current activity
}
});
Solution 2:
mPlayer.setOnErrorListener(newOnErrorListener() {
publicbooleanonError(MediaPlayer paramMediaPlayer, int paramInt1,int paramInt2) {
// TODO Auto-generated method stub//your code if any error occurs while playing even you can show an alert to userreturntrue;
}
});
mPlayer.setOnCompletionListener(newOnCompletionListener() {
publicvoidonCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub//your code if the file was completely played either show an alert to user or start another activity or file.//even you can finish you activity here
}
});
Solution 3:
I find that above are correct however I was struggling on where to place the code. See below, i place this code after my code to start the tune!
playButton.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
mediaPlayer.start(); //Next line is the beginning of where to place the code.
mediaPlayer.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this, "I'm Finished", Toast.LENGTH_SHORT).show();
}
});
}
});
Post a Comment for "Oncompletion Listener With Mediaplayer"