Hice una app para una radio online de un pueblo, me gustaría saber si me pueden ayudar para que se reproduzca en segundo plano en un servicio, para que cuento se mate la actividad principal la radio se siga escuchando.
Les comparto código:
package ar.com.asset.www.radiostream;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button btnplay;
Button btnstop;
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
String stream = "http://radioscoop.hu:80/live.mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnplay = (Button) findViewById(R.id.btnplay);
btnstop = (Button) findViewById(R.id.btnstop);
btnplay.setEnabled(false);
btnplay.setText("CARGANDO");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
btnplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (started) {
started = false;
mediaPlayer.pause();
btnplay.setText("Play");
} else {
started = true;
prepared = true;
mediaPlayer.start();
btnplay.setText("Pause");
}
}
});
btnstop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
started = false;
mediaPlayer.stop();
btnplay.setText("Play");
try {
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
btnplay.setEnabled(true);
btnplay.setText("PLAY");
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}