estoy implementando en mi aplicacion una radio, funciona todo bien pero el problema es que si le doy al boton de atras sigue sonando la musica de radio, en el activity layour anterior y si me salgo de aplicacion sigue sonando. Os paso por aqui mi codigo.
public class Radio extends AppCompatActivity implements View.OnClickListener {
private String url_radio= "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
initializeUIElements();
initializeMediaPlayer();
}
//Inicializamos los elementos
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
playSeekBar.setIndeterminate(true);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener((View.OnClickListener) this);
buttonStopPlay = (Button) findViewById(R.id.buttonStop);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener((View.OnClickListener) this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(url_radio);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setIndeterminate(false);
playSeekBar.setSecondaryProgress(100);
Log.i("Buffering", "" + percent);
}
});
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
//Cada vez que pulse el boton start salga el SeekBar
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setIndeterminate(true);
//Si pulso al boton stop me quita el SeekBar
playSeekBar.setVisibility(View.INVISIBLE);
}
//Cada vez que pulse el boton de start empiece la musica y cuando pulse el boton de Stop pare la musica
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
// player.stop();
}
}
}