Prasin Prathap
Prasin Prathap

Reputation: 37

How to play android radio with screen off background playable option

How to play android radio with screen off background playable option. My App working fine without backgournd playing option. But I want to give background playing option in my app that is when user closes the app, the radio should keep on playing, untill user stops it.

I am also disable screen off option in xml file with android:keepScreenOn="true" option but I want to remove this option and keep mobile screen off and play my app in background.

This is my code

Button BPlay;
String stream = "http://stream.zeno.fm/hmzuvfwn9k0uv";
MediaPlayer mediaPlayer;

boolean prepared = false;
boolean started = false;

 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_radio);


 BPlay = (Button) findViewById(R.id.b_play);
    BPlay.setEnabled(false);
    BPlay.setText("Loading.....");

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    new PlayerTask().execute(stream);




    BPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (started){
                started = false;
                mediaPlayer.pause();
                BPlay.setText("PLAY");


            } else {
                started = true;
                mediaPlayer.start();
                BPlay.setText("PAUSE");


            }


        }
    });
}


 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);
         BPlay.setEnabled(true);
         BPlay.setText("PLAY");
     }

 }

 @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();
     if (prepared){
         mediaPlayer.release();

     }
 }

}

Upvotes: 0

Views: 690

Answers (1)

Iv&#225;n Garza Bermea
Iv&#225;n Garza Bermea

Reputation: 742

In order to have you media playing while the app is in the background, you'll need a MediaSession background Service running in parallel.

TLTR, here's a basic tutorial from Google on how to do that.

Upvotes: 0

Related Questions