How to play and pause in only one button - Android

jajaja picture jajaja · Aug 8, 2013 · Viewed 21.6k times · Source

I have two buttons in my media player that streams a radio station, play and pause. I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again I want to play it. I need help. Here is my code.

 play = (Button) findViewById(R.id.play);
 pause = (Button) findViewById(R.id.pause);


 play.setOnClickListener(new View.OnClickListener() {
 public void onClick(View view) {
 play();
}
});
play.performClick();

pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});


}

private void play() {
Uri myUri = Uri.parse("Shoutcast URL");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);

mp.setOnErrorListener(this);
mp.prepareAsync();

Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}

@Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}

private void pause() {
mp.pause();
}



@Override
public void onDestroy() {
super.onDestroy();
stop();

}

public void onCompletion(MediaPlayer mp) {
stop();
}

Answer

Obl Tobl picture Obl Tobl · Aug 8, 2013

Create just one Button and add something like a buttonstatus. Then you can check the status in your listener.
For example:

boolean isPlaying = false;
playPause = (Button) findViewById(R.id.play);


 playPause.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {
   if (isPlaying) {
     pause();
   }else{
     play();
   }
   isPlaying = !isPlaying;
}
});