androidbackgroundaudio-playerinternet-radio

How to make a radio app keep playing in the background of my Android App


Am still new to android, but i followed a tutorial online in developing a radio Application, now this is the problem am encountering, i want this radio to keep playing, so that the app user can keep using the app or other application while the radio plays in the background. The radio stops playing when the user leave the streaming page.

  private void startPlaying() {
  buttonStopPlay.setEnabled(true);
  buttonPlay.setEnabled(false);
  player.start();


   }


  private void initializeMediaPlayer() {
  player = new MediaPlayer();
  try {
  player.setDataSource(" radio URL");

  player.setOnPreparedListener(new OnPreparedListener() {

  public void onPrepared(MediaPlayer mp) {
  player.start();


  }
  });
  player.prepareAsync();
  buttonStopPlay.setEnabled(true);
  buttonPlay.setEnabled(true);


  } catch (IllegalArgumentException e) {
  e.printStackTrace();
  } catch (IllegalStateException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  }

  player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

  public void onBufferingUpdate(MediaPlayer mp, int percent) {
  playSeekBar.setSecondaryProgress(percent);
  Log.i("Buffering", "" + percent);
  }
  });
  }

 @Override
 protected void onPause() {
 super.onPause();
 if (player.isPlaying()) {
 player.pause();
 buttonStopPlay.setEnabled(false);
 buttonPlay.setEnabled(true);
 }

 }

Solution

  • refer this link

    Intent svc=new Intent(this, BackgroundSoundService.class);
        startService(svc);
    
    
    
    public class BackgroundSoundService extends Service {
        private static final String TAG = null;
        MediaPlayer player;
        public IBinder onBind(Intent arg0) {
    
            return null;
        }
        @Override
        public void onCreate() {
            super.onCreate();
            player = MediaPlayer.create(this, R.raw.idil);
            player.setLooping(true); // Set looping
            player.setVolume(100,100);
    
        }
        public int onStartCommand(Intent intent, int flags, int startId) {
            player.start();
            return 1;
        }
    
        public void onStart(Intent intent, int startId) {
            // TO DO
        }
        public IBinder onUnBind(Intent arg0) {
            // TO DO Auto-generated method
            return null;
        }
    
        public void onStop() {
    
        }
        public void onPause() {
    
        }
        @Override
        public void onDestroy() {
            player.stop();
            player.release();
        }
    
        @Override
        public void onLowMemory() {
    
        }
    }