I'm developing a radio application to gain knowledge, so I grabbed a stream and got this code:
package tk.davidev.android.ews;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import java.io.IOException;
public class WebRadio extends AppCompatActivity {
private final static String stream = "http://170.75.144.170:10262/;";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_radio);
play = (Button) findViewById(R.id.btnWebRadio);
play.setEnabled(false);
play.setText("Carregando stream..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setLooping(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
mediaPlayer.setLooping(true);
} else {
mediaPlayer.start();
started = true;
mediaPlayer.setLooping(true);
play.setText("Pausar");
}
}
});
new PlayTask().execute(stream);
}
@Override
protected void onPause() {
super.onPause();
if(started)
mediaPlayer.pause();
}
@Override
protected void onResume() {
super.onResume();
if(!started)
mediaPlayer.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
mediaPlayer.setLooping(true);
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
mediaPlayer.setLooping(true);
}
}
}
It works! But after about 2/3 seconds it stops automatically, and if it gives Pause and Play it does not return, just restarting the Activity.