与MediaPlayer的OnCompletion监听器

我如何使用OnCompletion监听器来播放一些音乐? 我想按一个button转到另一个播放一些音乐的活动,然后在音乐播放结束时返回。 我已经编写了其他的东西。 我只是不知道如何使用OnCompletion监听器?

Solutions Collecting From Web of "与MediaPlayer的OnCompletion监听器"

您应该把在OnCompletionListener完成音乐时应该运行的代码,例如:

 mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { finish(); // finish current activity } }); 
 mPlayer.setOnErrorListener(new OnErrorListener() { public boolean onError(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 user return true; } }); mPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(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 } }); 

我发现上面是正确的,但是我正在努力在哪里放置代码。 看到下面,我把这个代码放在我的代码之后,开始调整!

 playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.start(); //Next line is the beginning of where to place the code. mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { Toast.makeText(MainActivity.this, "I'm Finished", Toast.LENGTH_SHORT).show(); } }); } });