Android background audio with a live audio stream












0















I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.



Here's my code currently, everything works except background audio.



import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

private ImageButton btn;
private ImageView img;
private boolean playPause;
private MediaPlayer mediaPlayer;

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

btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);

mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
//mp.start();
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!playPause) {
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
img.setImageResource(R.drawable.ic_toweron);
img.setAlpha(1.0f);
playPause = true;
}
} else {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btn.setBackgroundResource(R.drawable.ic_play_button);
img.setImageResource(R.drawable.ic_toweroff);
img.setAlpha(0.3f);
playPause = false;
}
}
}
});

try {
mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}

protected void onStop() {
super.onStop();

if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}

@Override
protected void onDestroy() {
super.onDestroy();

if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
}


Any help would be much appreciated.










share|improve this question





























    0















    I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.



    Here's my code currently, everything works except background audio.



    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.ImageButton;
    import android.widget.ImageView;

    public class MainActivity extends AppCompatActivity {

    private ImageButton btn;
    private ImageView img;
    private boolean playPause;
    private MediaPlayer mediaPlayer;

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

    btn = findViewById(R.id.playPause);
    img = findViewById(R.id.radioTower);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    public boolean onError(MediaPlayer mp, int what, int extra) {
    mp.reset();
    return false;
    }
    });
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    public void onPrepared(MediaPlayer mp) {
    //mp.start();
    }
    });
    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    if (!playPause) {
    if(!mediaPlayer.isPlaying()) {
    mediaPlayer.start();
    btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
    img.setImageResource(R.drawable.ic_toweron);
    img.setAlpha(1.0f);
    playPause = true;
    }
    } else {
    if(mediaPlayer.isPlaying()) {
    mediaPlayer.pause();
    btn.setBackgroundResource(R.drawable.ic_play_button);
    img.setImageResource(R.drawable.ic_toweroff);
    img.setAlpha(0.3f);
    playPause = false;
    }
    }
    }
    });

    try {
    mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
    mediaPlayer.prepareAsync();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    protected void onStop() {
    super.onStop();

    if (mediaPlayer != null) {
    if (mediaPlayer.isPlaying()) {
    mediaPlayer.stop();
    }
    mediaPlayer.release();
    mediaPlayer = null;
    }
    }

    @Override
    protected void onDestroy() {
    super.onDestroy();

    if (mediaPlayer != null) {
    if (mediaPlayer.isPlaying()) {
    mediaPlayer.stop();
    }
    mediaPlayer.release();
    mediaPlayer = null;
    }
    }
    }


    Any help would be much appreciated.










    share|improve this question



























      0












      0








      0








      I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.



      Here's my code currently, everything works except background audio.



      import android.media.AudioManager;
      import android.media.MediaPlayer;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.view.View;
      import android.widget.ImageButton;
      import android.widget.ImageView;

      public class MainActivity extends AppCompatActivity {

      private ImageButton btn;
      private ImageView img;
      private boolean playPause;
      private MediaPlayer mediaPlayer;

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

      btn = findViewById(R.id.playPause);
      img = findViewById(R.id.radioTower);

      mediaPlayer = new MediaPlayer();
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
      public boolean onError(MediaPlayer mp, int what, int extra) {
      mp.reset();
      return false;
      }
      });
      mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
      public void onPrepared(MediaPlayer mp) {
      //mp.start();
      }
      });
      btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      if (!playPause) {
      if(!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
      btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
      img.setImageResource(R.drawable.ic_toweron);
      img.setAlpha(1.0f);
      playPause = true;
      }
      } else {
      if(mediaPlayer.isPlaying()) {
      mediaPlayer.pause();
      btn.setBackgroundResource(R.drawable.ic_play_button);
      img.setImageResource(R.drawable.ic_toweroff);
      img.setAlpha(0.3f);
      playPause = false;
      }
      }
      }
      });

      try {
      mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
      mediaPlayer.prepareAsync();
      } catch (Exception e) {
      e.printStackTrace();
      }
      }

      protected void onStop() {
      super.onStop();

      if (mediaPlayer != null) {
      if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
      }
      mediaPlayer.release();
      mediaPlayer = null;
      }
      }

      @Override
      protected void onDestroy() {
      super.onDestroy();

      if (mediaPlayer != null) {
      if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
      }
      mediaPlayer.release();
      mediaPlayer = null;
      }
      }
      }


      Any help would be much appreciated.










      share|improve this question
















      I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.



      Here's my code currently, everything works except background audio.



      import android.media.AudioManager;
      import android.media.MediaPlayer;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.view.View;
      import android.widget.ImageButton;
      import android.widget.ImageView;

      public class MainActivity extends AppCompatActivity {

      private ImageButton btn;
      private ImageView img;
      private boolean playPause;
      private MediaPlayer mediaPlayer;

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

      btn = findViewById(R.id.playPause);
      img = findViewById(R.id.radioTower);

      mediaPlayer = new MediaPlayer();
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
      public boolean onError(MediaPlayer mp, int what, int extra) {
      mp.reset();
      return false;
      }
      });
      mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
      public void onPrepared(MediaPlayer mp) {
      //mp.start();
      }
      });
      btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      if (!playPause) {
      if(!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
      btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
      img.setImageResource(R.drawable.ic_toweron);
      img.setAlpha(1.0f);
      playPause = true;
      }
      } else {
      if(mediaPlayer.isPlaying()) {
      mediaPlayer.pause();
      btn.setBackgroundResource(R.drawable.ic_play_button);
      img.setImageResource(R.drawable.ic_toweroff);
      img.setAlpha(0.3f);
      playPause = false;
      }
      }
      }
      });

      try {
      mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
      mediaPlayer.prepareAsync();
      } catch (Exception e) {
      e.printStackTrace();
      }
      }

      protected void onStop() {
      super.onStop();

      if (mediaPlayer != null) {
      if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
      }
      mediaPlayer.release();
      mediaPlayer = null;
      }
      }

      @Override
      protected void onDestroy() {
      super.onDestroy();

      if (mediaPlayer != null) {
      if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
      }
      mediaPlayer.release();
      mediaPlayer = null;
      }
      }
      }


      Any help would be much appreciated.







      android audio android-service






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 1 at 6:59









      ADM

      8,772102351




      8,772102351










      asked Jan 1 at 6:45









      iShaymusiShaymus

      298214




      298214
























          2 Answers
          2






          active

          oldest

          votes


















          1














          use service to play audio file instant of activity.
          here is simple code how to use media player in service.



          public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {

          //region "member variable"
          boolean isServiceRunning = false;
          ArrayList<Song> PlayerList = new ArrayList<>();
          MediaPlayer mediaPlayer;
          int position = 0;
          MainActivity mainActivity;
          private final IBinder mBinder = new LocalBinder();
          int playingMood;
          private final static int MAX_VOLUME = 15;
          Toast toast;
          public static MusicService objService;
          //endregion

          //region "service method"


          @Override
          public void onCreate() {
          objService = this;
          }

          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
          try {
          isServiceRunning = true;

          if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
          // showNotification(false);
          } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
          playPrevious();
          } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
          play();

          } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
          playNext();
          } else if (intent.getAction().equals(
          Constants.ACTION.STOPFOREGROUND_ACTION)) {
          stop();
          stopForeground(true);
          stopSelf();
          }
          } catch (Exception ex) {
          ex.printStackTrace();
          }
          return START_STICKY;
          }

          @Override
          public void onDestroy() {
          super.onDestroy();
          isServiceRunning = false;
          objService = null;
          }

          @Override
          public IBinder onBind(Intent intent) {
          return mBinder;
          }


          //returns the instance of the service
          public class LocalBinder extends Binder {
          public MusicService getServiceInstance() {
          return MusicService.this;
          }
          }

          public void registerClient(MainActivity activity) {
          mainActivity = activity;
          }
          //endregion


          //region "Media player"

          public void SongRequest() {
          try {
          if (mediaPlayer != null) {
          mediaPlayer.release();
          mediaPlayer = null;
          }

          //Handel UI on main activity
          mainActivity.showPlayer();
          mediaPlayer = new MediaPlayer();
          mainActivity.updatePlayerUI();
          prepareMediaPlayer(PlayerList.get(position).getUrl());
          } catch (Exception ex) {
          ex.printStackTrace();
          }

          }

          void showToast(String text) {
          if (toast != null)
          toast.cancel();
          toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
          toast.show();
          }


          @Override
          public void onPrepared(MediaPlayer mp) {
          // try {
          mediaPlayer.start();
          mainActivity.checkPlaying(true);
          } catch (Exception ex) {
          ex.printStackTrace();
          }
          }

          @Override
          public void onCompletion(MediaPlayer mp) {
          try {
          mainActivity.sentUpdateBroadcast(true);
          if (playingMood == 1) {
          mediaPlayer.start();
          }
          if (playingMood == 2) {
          playNext();
          }

          } catch (Exception ex) {
          ex.printStackTrace();
          }
          }

          @Override
          public void onBufferingUpdate(MediaPlayer mp, int percent) {
          if (mainActivity != null)
          mainActivity.updateProgressBuffer(percent);
          if (percent == 1)
          mainActivity.showPlayer();

          }

          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {
          try {
          Log.i("MediaPlayer", "error");

          } catch (Exception ex) {
          ex.printStackTrace();
          }
          return false;
          }




          void startPrepare(String url) {

          prepareMediaPlayer(url);

          }



          void prepareMediaPlayer(String url) {
          try {
          mediaPlayer.setDataSource(url);
          mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
          mediaPlayer.setOnPreparedListener(MusicService.this);
          mediaPlayer.setOnErrorListener(MusicService.this);
          mediaPlayer.setOnCompletionListener(MusicService.this);
          mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
          mediaPlayer.prepareAsync();
          } catch (IOException e) {
          e.printStackTrace();
          }
          }

          //endregion

          //region "media player method"
          public boolean play() {
          if (mediaPlayer != null) {
          switchButton();
          if (mediaPlayer.isPlaying()) {
          mediaPlayer.pause();

          return false;
          } else {
          mediaPlayer.start();
          return true;
          }
          }

          return false;

          }

          void switchButton() {

          mainActivity.checkPlaying(!mediaPlayer.isPlaying());
          }

          public void stop() {
          try {
          if (mediaPlayer != null) {
          mediaPlayer.release();
          mediaPlayer = null;
          }
          isServiceRunning = false;
          if (mainActivity != null) {
          mainActivity.ShowPlayer(0);
          }
          } catch (Exception ex) {
          ex.printStackTrace();
          }
          }

          public void playNext() {
          if (position < PlayerList.size() - 1) {
          position++;
          mediaPlayer.stop();
          SongRequest();
          }
          }


          public void playPrevious() {
          if (position > 0) {
          position--;
          mediaPlayer.stop();
          SongRequest();
          }
          }


          public void onError() {

          }


          public void onCompletion() {

          }


          public void onCleanMemory() {

          }


          public void initilizePlayerList(ArrayList<Song> list, int position) {
          this.PlayerList = list;
          this.position = position;
          }

          public boolean isplaying() {

          return mediaPlayer == null ? false : mediaPlayer.isPlaying();
          }

          public boolean isRunning() {

          return isServiceRunning;
          }

          public Song getCurrentSong() {
          if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
          return PlayerList.get(position);
          }
          return null;
          }

          public MediaPlayer getMediaPlayer() {
          return mediaPlayer;
          }

          public void seekTo(int duration) {
          if (mediaPlayer != null) {
          mediaPlayer.seekTo(duration);
          }
          }

          public int getMood() {
          return playingMood;
          }

          public void setMood(int mood) {
          playingMood = mood;
          }

          public void setVolume(int soundVolume) {
          if (mediaPlayer != null) {
          final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
          mediaPlayer.setVolume(volume, volume);
          }
          }

          //endregion
          }


          you can start your service from activity like this.



             public void startMusicService() {
          Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
          serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
          startService(serviceIntent);
          bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
          }


          for stop service use this code



          public void stopMusicService() {
          if (service != null) {
          try {
          service.stop();
          unbindService(mConnection);
          stopService(new Intent(MainActivity.this, service.getClass()));
          service = null;
          } catch (IllegalArgumentException ex) {
          stopService(new Intent(MainActivity.this, service.getClass()));
          service = null;
          ex.printStackTrace();
          }
          }
          }


          for bind service with activity use this



          private ServiceConnection mConnection = new ServiceConnection() {

          @Override
          public void onServiceConnected(ComponentName className,
          IBinder _service) {

          MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
          service = binder.getServiceInstance(); //Get instance of your service!
          service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
          if (listHolder != null) {
          initilizeSongsList(listHolder.list, listHolder.position);
          }
          }

          @Override
          public void onServiceDisconnected(ComponentName arg0) {


          }
          };


          where service is music service object in activity MusicService service;






          share|improve this answer


























          • I think you just exploded my brain. I'll give it a try and see how I go.

            – iShaymus
            Jan 1 at 7:40











          • Also the app just plays a single static URL, it will not change and cannot be changed by the user.

            – iShaymus
            Jan 1 at 7:46











          • for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

            – asim
            Jan 1 at 9:32











          • What are the required imports. Auto Import seems to have missed quite a bit.

            – iShaymus
            Jan 1 at 20:59











          • asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

            – iShaymus
            Jan 1 at 21:51



















          0














          So this is the working service for a single live stream URL thanks to asim.



          public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
          public static final String ACTION_PLAY = "com.example.action.PLAY";
          private static final String STREAM_URL = "...";
          private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";

          MainActivity mainActivity;
          MediaPlayer mediaPlayer = null;
          WifiManager.WifiLock wifiLock;

          @Override
          public IBinder onBind(Intent intent) {
          // TODO Auto-generated method stub
          return null;
          }

          public class LocalBinder extends Binder {
          public StreamService getServiceInstance() {
          return StreamService.this;
          }
          }

          @Override
          public void onCreate() {
          super.onCreate();
          }

          public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent.getAction().equals(ACTION_PLAY)) {
          mediaPlayer = new MediaPlayer();
          mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
          mediaPlayer.setOnErrorListener(this);
          mediaPlayer.setOnPreparedListener(this);
          mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
          wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
          .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
          wifiLock.acquire();
          try {
          // Set the stream URL location
          mediaPlayer.setDataSource(TEST_URL);
          // prepareAsync must be called after setAudioStreamType and setOnPreparedListener
          mediaPlayer.prepareAsync();
          } catch (Exception e) {
          e.printStackTrace();
          }
          }
          return START_STICKY;
          }

          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {
          // ... react appropriately ...
          // The MediaPlayer has moved to the Error state, must be reset!
          return false;
          }

          void switchButton() {
          mainActivity.checkPlaying(!mediaPlayer.isPlaying());
          }

          public boolean play() {
          if (mediaPlayer != null) {
          //switchButton();
          if (mediaPlayer.isPlaying()) {
          mediaPlayer.pause();
          return false;
          } else {
          mediaPlayer.start();
          return true;
          }
          }
          return false;
          }

          public void stop() {
          try {
          if (mediaPlayer != null) {
          mediaPlayer.release();
          mediaPlayer = null;
          }
          } catch (Exception ex) {
          ex.printStackTrace();
          }
          }

          /** Called when MediaPlayer is ready */
          public void onPrepared(MediaPlayer player) {
          //player.start();
          }

          @Override
          public void onDestroy() {
          super.onDestroy();
          if( wifiLock != null) wifiLock.release();
          if (mediaPlayer != null) mediaPlayer.release();
          }

          public void registerClient(MainActivity activity) {
          mainActivity = activity;
          }

          public boolean isplaying() {

          return mediaPlayer == null ? false : mediaPlayer.isPlaying();
          }
          }


          Which is implemented in the main activity:



          public class MainActivity extends AppCompatActivity {

          private ImageButton btn; // Play | Pause toggle button
          private ImageView img; // Radio tower image that alternates between on and off
          StreamService service;

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

          // Bind the view buttons to local variables
          btn = findViewById(R.id.playPause);
          img = findViewById(R.id.radioTower);

          startStream();

          btn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
          if (service.isplaying()) {
          Log.d("pause","Pause Playback");
          } else {
          Log.d("play", "Start Playback");
          }

          }
          });
          }

          public void startStream() {
          Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
          serviceIntent.setAction(StreamService.ACTION_PLAY);
          startService(serviceIntent);
          bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
          }

          public void stopStream() {
          if (service != null) {
          try {
          service.stop();
          unbindService(mConnection);
          stopService(new Intent(MainActivity.this, service.getClass()));
          service = null;
          } catch (IllegalArgumentException ex) {
          stopService(new Intent(MainActivity.this, service.getClass()));
          service = null;
          ex.printStackTrace();
          }
          }
          }

          private ServiceConnection mConnection = new ServiceConnection() {

          @Override
          public void onServiceConnected(ComponentName className,
          IBinder _service) {

          StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
          service = binder.getServiceInstance(); //Get instance of your service!
          service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
          }

          @Override
          public void onServiceDisconnected(ComponentName arg0) {

          }
          };
          }


          Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993541%2fandroid-background-audio-with-a-live-audio-stream%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            use service to play audio file instant of activity.
            here is simple code how to use media player in service.



            public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {

            //region "member variable"
            boolean isServiceRunning = false;
            ArrayList<Song> PlayerList = new ArrayList<>();
            MediaPlayer mediaPlayer;
            int position = 0;
            MainActivity mainActivity;
            private final IBinder mBinder = new LocalBinder();
            int playingMood;
            private final static int MAX_VOLUME = 15;
            Toast toast;
            public static MusicService objService;
            //endregion

            //region "service method"


            @Override
            public void onCreate() {
            objService = this;
            }

            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
            try {
            isServiceRunning = true;

            if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            // showNotification(false);
            } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
            playPrevious();
            } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
            play();

            } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
            playNext();
            } else if (intent.getAction().equals(
            Constants.ACTION.STOPFOREGROUND_ACTION)) {
            stop();
            stopForeground(true);
            stopSelf();
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return START_STICKY;
            }

            @Override
            public void onDestroy() {
            super.onDestroy();
            isServiceRunning = false;
            objService = null;
            }

            @Override
            public IBinder onBind(Intent intent) {
            return mBinder;
            }


            //returns the instance of the service
            public class LocalBinder extends Binder {
            public MusicService getServiceInstance() {
            return MusicService.this;
            }
            }

            public void registerClient(MainActivity activity) {
            mainActivity = activity;
            }
            //endregion


            //region "Media player"

            public void SongRequest() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }

            //Handel UI on main activity
            mainActivity.showPlayer();
            mediaPlayer = new MediaPlayer();
            mainActivity.updatePlayerUI();
            prepareMediaPlayer(PlayerList.get(position).getUrl());
            } catch (Exception ex) {
            ex.printStackTrace();
            }

            }

            void showToast(String text) {
            if (toast != null)
            toast.cancel();
            toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
            toast.show();
            }


            @Override
            public void onPrepared(MediaPlayer mp) {
            // try {
            mediaPlayer.start();
            mainActivity.checkPlaying(true);
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
            try {
            mainActivity.sentUpdateBroadcast(true);
            if (playingMood == 1) {
            mediaPlayer.start();
            }
            if (playingMood == 2) {
            playNext();
            }

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
            if (mainActivity != null)
            mainActivity.updateProgressBuffer(percent);
            if (percent == 1)
            mainActivity.showPlayer();

            }

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
            try {
            Log.i("MediaPlayer", "error");

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return false;
            }




            void startPrepare(String url) {

            prepareMediaPlayer(url);

            }



            void prepareMediaPlayer(String url) {
            try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnPreparedListener(MusicService.this);
            mediaPlayer.setOnErrorListener(MusicService.this);
            mediaPlayer.setOnCompletionListener(MusicService.this);
            mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
            mediaPlayer.prepareAsync();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            //endregion

            //region "media player method"
            public boolean play() {
            if (mediaPlayer != null) {
            switchButton();
            if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();

            return false;
            } else {
            mediaPlayer.start();
            return true;
            }
            }

            return false;

            }

            void switchButton() {

            mainActivity.checkPlaying(!mediaPlayer.isPlaying());
            }

            public void stop() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }
            isServiceRunning = false;
            if (mainActivity != null) {
            mainActivity.ShowPlayer(0);
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            public void playNext() {
            if (position < PlayerList.size() - 1) {
            position++;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void playPrevious() {
            if (position > 0) {
            position--;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void onError() {

            }


            public void onCompletion() {

            }


            public void onCleanMemory() {

            }


            public void initilizePlayerList(ArrayList<Song> list, int position) {
            this.PlayerList = list;
            this.position = position;
            }

            public boolean isplaying() {

            return mediaPlayer == null ? false : mediaPlayer.isPlaying();
            }

            public boolean isRunning() {

            return isServiceRunning;
            }

            public Song getCurrentSong() {
            if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
            return PlayerList.get(position);
            }
            return null;
            }

            public MediaPlayer getMediaPlayer() {
            return mediaPlayer;
            }

            public void seekTo(int duration) {
            if (mediaPlayer != null) {
            mediaPlayer.seekTo(duration);
            }
            }

            public int getMood() {
            return playingMood;
            }

            public void setMood(int mood) {
            playingMood = mood;
            }

            public void setVolume(int soundVolume) {
            if (mediaPlayer != null) {
            final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
            mediaPlayer.setVolume(volume, volume);
            }
            }

            //endregion
            }


            you can start your service from activity like this.



               public void startMusicService() {
            Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
            serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
            startService(serviceIntent);
            bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
            }


            for stop service use this code



            public void stopMusicService() {
            if (service != null) {
            try {
            service.stop();
            unbindService(mConnection);
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            } catch (IllegalArgumentException ex) {
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            ex.printStackTrace();
            }
            }
            }


            for bind service with activity use this



            private ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName className,
            IBinder _service) {

            MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
            service = binder.getServiceInstance(); //Get instance of your service!
            service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
            if (listHolder != null) {
            initilizeSongsList(listHolder.list, listHolder.position);
            }
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {


            }
            };


            where service is music service object in activity MusicService service;






            share|improve this answer


























            • I think you just exploded my brain. I'll give it a try and see how I go.

              – iShaymus
              Jan 1 at 7:40











            • Also the app just plays a single static URL, it will not change and cannot be changed by the user.

              – iShaymus
              Jan 1 at 7:46











            • for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

              – asim
              Jan 1 at 9:32











            • What are the required imports. Auto Import seems to have missed quite a bit.

              – iShaymus
              Jan 1 at 20:59











            • asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

              – iShaymus
              Jan 1 at 21:51
















            1














            use service to play audio file instant of activity.
            here is simple code how to use media player in service.



            public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {

            //region "member variable"
            boolean isServiceRunning = false;
            ArrayList<Song> PlayerList = new ArrayList<>();
            MediaPlayer mediaPlayer;
            int position = 0;
            MainActivity mainActivity;
            private final IBinder mBinder = new LocalBinder();
            int playingMood;
            private final static int MAX_VOLUME = 15;
            Toast toast;
            public static MusicService objService;
            //endregion

            //region "service method"


            @Override
            public void onCreate() {
            objService = this;
            }

            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
            try {
            isServiceRunning = true;

            if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            // showNotification(false);
            } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
            playPrevious();
            } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
            play();

            } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
            playNext();
            } else if (intent.getAction().equals(
            Constants.ACTION.STOPFOREGROUND_ACTION)) {
            stop();
            stopForeground(true);
            stopSelf();
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return START_STICKY;
            }

            @Override
            public void onDestroy() {
            super.onDestroy();
            isServiceRunning = false;
            objService = null;
            }

            @Override
            public IBinder onBind(Intent intent) {
            return mBinder;
            }


            //returns the instance of the service
            public class LocalBinder extends Binder {
            public MusicService getServiceInstance() {
            return MusicService.this;
            }
            }

            public void registerClient(MainActivity activity) {
            mainActivity = activity;
            }
            //endregion


            //region "Media player"

            public void SongRequest() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }

            //Handel UI on main activity
            mainActivity.showPlayer();
            mediaPlayer = new MediaPlayer();
            mainActivity.updatePlayerUI();
            prepareMediaPlayer(PlayerList.get(position).getUrl());
            } catch (Exception ex) {
            ex.printStackTrace();
            }

            }

            void showToast(String text) {
            if (toast != null)
            toast.cancel();
            toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
            toast.show();
            }


            @Override
            public void onPrepared(MediaPlayer mp) {
            // try {
            mediaPlayer.start();
            mainActivity.checkPlaying(true);
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
            try {
            mainActivity.sentUpdateBroadcast(true);
            if (playingMood == 1) {
            mediaPlayer.start();
            }
            if (playingMood == 2) {
            playNext();
            }

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
            if (mainActivity != null)
            mainActivity.updateProgressBuffer(percent);
            if (percent == 1)
            mainActivity.showPlayer();

            }

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
            try {
            Log.i("MediaPlayer", "error");

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return false;
            }




            void startPrepare(String url) {

            prepareMediaPlayer(url);

            }



            void prepareMediaPlayer(String url) {
            try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnPreparedListener(MusicService.this);
            mediaPlayer.setOnErrorListener(MusicService.this);
            mediaPlayer.setOnCompletionListener(MusicService.this);
            mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
            mediaPlayer.prepareAsync();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            //endregion

            //region "media player method"
            public boolean play() {
            if (mediaPlayer != null) {
            switchButton();
            if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();

            return false;
            } else {
            mediaPlayer.start();
            return true;
            }
            }

            return false;

            }

            void switchButton() {

            mainActivity.checkPlaying(!mediaPlayer.isPlaying());
            }

            public void stop() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }
            isServiceRunning = false;
            if (mainActivity != null) {
            mainActivity.ShowPlayer(0);
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            public void playNext() {
            if (position < PlayerList.size() - 1) {
            position++;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void playPrevious() {
            if (position > 0) {
            position--;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void onError() {

            }


            public void onCompletion() {

            }


            public void onCleanMemory() {

            }


            public void initilizePlayerList(ArrayList<Song> list, int position) {
            this.PlayerList = list;
            this.position = position;
            }

            public boolean isplaying() {

            return mediaPlayer == null ? false : mediaPlayer.isPlaying();
            }

            public boolean isRunning() {

            return isServiceRunning;
            }

            public Song getCurrentSong() {
            if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
            return PlayerList.get(position);
            }
            return null;
            }

            public MediaPlayer getMediaPlayer() {
            return mediaPlayer;
            }

            public void seekTo(int duration) {
            if (mediaPlayer != null) {
            mediaPlayer.seekTo(duration);
            }
            }

            public int getMood() {
            return playingMood;
            }

            public void setMood(int mood) {
            playingMood = mood;
            }

            public void setVolume(int soundVolume) {
            if (mediaPlayer != null) {
            final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
            mediaPlayer.setVolume(volume, volume);
            }
            }

            //endregion
            }


            you can start your service from activity like this.



               public void startMusicService() {
            Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
            serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
            startService(serviceIntent);
            bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
            }


            for stop service use this code



            public void stopMusicService() {
            if (service != null) {
            try {
            service.stop();
            unbindService(mConnection);
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            } catch (IllegalArgumentException ex) {
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            ex.printStackTrace();
            }
            }
            }


            for bind service with activity use this



            private ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName className,
            IBinder _service) {

            MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
            service = binder.getServiceInstance(); //Get instance of your service!
            service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
            if (listHolder != null) {
            initilizeSongsList(listHolder.list, listHolder.position);
            }
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {


            }
            };


            where service is music service object in activity MusicService service;






            share|improve this answer


























            • I think you just exploded my brain. I'll give it a try and see how I go.

              – iShaymus
              Jan 1 at 7:40











            • Also the app just plays a single static URL, it will not change and cannot be changed by the user.

              – iShaymus
              Jan 1 at 7:46











            • for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

              – asim
              Jan 1 at 9:32











            • What are the required imports. Auto Import seems to have missed quite a bit.

              – iShaymus
              Jan 1 at 20:59











            • asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

              – iShaymus
              Jan 1 at 21:51














            1












            1








            1







            use service to play audio file instant of activity.
            here is simple code how to use media player in service.



            public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {

            //region "member variable"
            boolean isServiceRunning = false;
            ArrayList<Song> PlayerList = new ArrayList<>();
            MediaPlayer mediaPlayer;
            int position = 0;
            MainActivity mainActivity;
            private final IBinder mBinder = new LocalBinder();
            int playingMood;
            private final static int MAX_VOLUME = 15;
            Toast toast;
            public static MusicService objService;
            //endregion

            //region "service method"


            @Override
            public void onCreate() {
            objService = this;
            }

            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
            try {
            isServiceRunning = true;

            if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            // showNotification(false);
            } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
            playPrevious();
            } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
            play();

            } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
            playNext();
            } else if (intent.getAction().equals(
            Constants.ACTION.STOPFOREGROUND_ACTION)) {
            stop();
            stopForeground(true);
            stopSelf();
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return START_STICKY;
            }

            @Override
            public void onDestroy() {
            super.onDestroy();
            isServiceRunning = false;
            objService = null;
            }

            @Override
            public IBinder onBind(Intent intent) {
            return mBinder;
            }


            //returns the instance of the service
            public class LocalBinder extends Binder {
            public MusicService getServiceInstance() {
            return MusicService.this;
            }
            }

            public void registerClient(MainActivity activity) {
            mainActivity = activity;
            }
            //endregion


            //region "Media player"

            public void SongRequest() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }

            //Handel UI on main activity
            mainActivity.showPlayer();
            mediaPlayer = new MediaPlayer();
            mainActivity.updatePlayerUI();
            prepareMediaPlayer(PlayerList.get(position).getUrl());
            } catch (Exception ex) {
            ex.printStackTrace();
            }

            }

            void showToast(String text) {
            if (toast != null)
            toast.cancel();
            toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
            toast.show();
            }


            @Override
            public void onPrepared(MediaPlayer mp) {
            // try {
            mediaPlayer.start();
            mainActivity.checkPlaying(true);
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
            try {
            mainActivity.sentUpdateBroadcast(true);
            if (playingMood == 1) {
            mediaPlayer.start();
            }
            if (playingMood == 2) {
            playNext();
            }

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
            if (mainActivity != null)
            mainActivity.updateProgressBuffer(percent);
            if (percent == 1)
            mainActivity.showPlayer();

            }

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
            try {
            Log.i("MediaPlayer", "error");

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return false;
            }




            void startPrepare(String url) {

            prepareMediaPlayer(url);

            }



            void prepareMediaPlayer(String url) {
            try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnPreparedListener(MusicService.this);
            mediaPlayer.setOnErrorListener(MusicService.this);
            mediaPlayer.setOnCompletionListener(MusicService.this);
            mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
            mediaPlayer.prepareAsync();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            //endregion

            //region "media player method"
            public boolean play() {
            if (mediaPlayer != null) {
            switchButton();
            if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();

            return false;
            } else {
            mediaPlayer.start();
            return true;
            }
            }

            return false;

            }

            void switchButton() {

            mainActivity.checkPlaying(!mediaPlayer.isPlaying());
            }

            public void stop() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }
            isServiceRunning = false;
            if (mainActivity != null) {
            mainActivity.ShowPlayer(0);
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            public void playNext() {
            if (position < PlayerList.size() - 1) {
            position++;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void playPrevious() {
            if (position > 0) {
            position--;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void onError() {

            }


            public void onCompletion() {

            }


            public void onCleanMemory() {

            }


            public void initilizePlayerList(ArrayList<Song> list, int position) {
            this.PlayerList = list;
            this.position = position;
            }

            public boolean isplaying() {

            return mediaPlayer == null ? false : mediaPlayer.isPlaying();
            }

            public boolean isRunning() {

            return isServiceRunning;
            }

            public Song getCurrentSong() {
            if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
            return PlayerList.get(position);
            }
            return null;
            }

            public MediaPlayer getMediaPlayer() {
            return mediaPlayer;
            }

            public void seekTo(int duration) {
            if (mediaPlayer != null) {
            mediaPlayer.seekTo(duration);
            }
            }

            public int getMood() {
            return playingMood;
            }

            public void setMood(int mood) {
            playingMood = mood;
            }

            public void setVolume(int soundVolume) {
            if (mediaPlayer != null) {
            final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
            mediaPlayer.setVolume(volume, volume);
            }
            }

            //endregion
            }


            you can start your service from activity like this.



               public void startMusicService() {
            Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
            serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
            startService(serviceIntent);
            bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
            }


            for stop service use this code



            public void stopMusicService() {
            if (service != null) {
            try {
            service.stop();
            unbindService(mConnection);
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            } catch (IllegalArgumentException ex) {
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            ex.printStackTrace();
            }
            }
            }


            for bind service with activity use this



            private ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName className,
            IBinder _service) {

            MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
            service = binder.getServiceInstance(); //Get instance of your service!
            service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
            if (listHolder != null) {
            initilizeSongsList(listHolder.list, listHolder.position);
            }
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {


            }
            };


            where service is music service object in activity MusicService service;






            share|improve this answer















            use service to play audio file instant of activity.
            here is simple code how to use media player in service.



            public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {

            //region "member variable"
            boolean isServiceRunning = false;
            ArrayList<Song> PlayerList = new ArrayList<>();
            MediaPlayer mediaPlayer;
            int position = 0;
            MainActivity mainActivity;
            private final IBinder mBinder = new LocalBinder();
            int playingMood;
            private final static int MAX_VOLUME = 15;
            Toast toast;
            public static MusicService objService;
            //endregion

            //region "service method"


            @Override
            public void onCreate() {
            objService = this;
            }

            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
            try {
            isServiceRunning = true;

            if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            // showNotification(false);
            } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
            playPrevious();
            } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
            play();

            } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
            playNext();
            } else if (intent.getAction().equals(
            Constants.ACTION.STOPFOREGROUND_ACTION)) {
            stop();
            stopForeground(true);
            stopSelf();
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return START_STICKY;
            }

            @Override
            public void onDestroy() {
            super.onDestroy();
            isServiceRunning = false;
            objService = null;
            }

            @Override
            public IBinder onBind(Intent intent) {
            return mBinder;
            }


            //returns the instance of the service
            public class LocalBinder extends Binder {
            public MusicService getServiceInstance() {
            return MusicService.this;
            }
            }

            public void registerClient(MainActivity activity) {
            mainActivity = activity;
            }
            //endregion


            //region "Media player"

            public void SongRequest() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }

            //Handel UI on main activity
            mainActivity.showPlayer();
            mediaPlayer = new MediaPlayer();
            mainActivity.updatePlayerUI();
            prepareMediaPlayer(PlayerList.get(position).getUrl());
            } catch (Exception ex) {
            ex.printStackTrace();
            }

            }

            void showToast(String text) {
            if (toast != null)
            toast.cancel();
            toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
            toast.show();
            }


            @Override
            public void onPrepared(MediaPlayer mp) {
            // try {
            mediaPlayer.start();
            mainActivity.checkPlaying(true);
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
            try {
            mainActivity.sentUpdateBroadcast(true);
            if (playingMood == 1) {
            mediaPlayer.start();
            }
            if (playingMood == 2) {
            playNext();
            }

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
            if (mainActivity != null)
            mainActivity.updateProgressBuffer(percent);
            if (percent == 1)
            mainActivity.showPlayer();

            }

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
            try {
            Log.i("MediaPlayer", "error");

            } catch (Exception ex) {
            ex.printStackTrace();
            }
            return false;
            }




            void startPrepare(String url) {

            prepareMediaPlayer(url);

            }



            void prepareMediaPlayer(String url) {
            try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnPreparedListener(MusicService.this);
            mediaPlayer.setOnErrorListener(MusicService.this);
            mediaPlayer.setOnCompletionListener(MusicService.this);
            mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
            mediaPlayer.prepareAsync();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            //endregion

            //region "media player method"
            public boolean play() {
            if (mediaPlayer != null) {
            switchButton();
            if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();

            return false;
            } else {
            mediaPlayer.start();
            return true;
            }
            }

            return false;

            }

            void switchButton() {

            mainActivity.checkPlaying(!mediaPlayer.isPlaying());
            }

            public void stop() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }
            isServiceRunning = false;
            if (mainActivity != null) {
            mainActivity.ShowPlayer(0);
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            public void playNext() {
            if (position < PlayerList.size() - 1) {
            position++;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void playPrevious() {
            if (position > 0) {
            position--;
            mediaPlayer.stop();
            SongRequest();
            }
            }


            public void onError() {

            }


            public void onCompletion() {

            }


            public void onCleanMemory() {

            }


            public void initilizePlayerList(ArrayList<Song> list, int position) {
            this.PlayerList = list;
            this.position = position;
            }

            public boolean isplaying() {

            return mediaPlayer == null ? false : mediaPlayer.isPlaying();
            }

            public boolean isRunning() {

            return isServiceRunning;
            }

            public Song getCurrentSong() {
            if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
            return PlayerList.get(position);
            }
            return null;
            }

            public MediaPlayer getMediaPlayer() {
            return mediaPlayer;
            }

            public void seekTo(int duration) {
            if (mediaPlayer != null) {
            mediaPlayer.seekTo(duration);
            }
            }

            public int getMood() {
            return playingMood;
            }

            public void setMood(int mood) {
            playingMood = mood;
            }

            public void setVolume(int soundVolume) {
            if (mediaPlayer != null) {
            final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
            mediaPlayer.setVolume(volume, volume);
            }
            }

            //endregion
            }


            you can start your service from activity like this.



               public void startMusicService() {
            Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
            serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
            startService(serviceIntent);
            bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
            }


            for stop service use this code



            public void stopMusicService() {
            if (service != null) {
            try {
            service.stop();
            unbindService(mConnection);
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            } catch (IllegalArgumentException ex) {
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            ex.printStackTrace();
            }
            }
            }


            for bind service with activity use this



            private ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName className,
            IBinder _service) {

            MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
            service = binder.getServiceInstance(); //Get instance of your service!
            service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
            if (listHolder != null) {
            initilizeSongsList(listHolder.list, listHolder.position);
            }
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {


            }
            };


            where service is music service object in activity MusicService service;







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 2 at 5:49

























            answered Jan 1 at 7:32









            asimasim

            22516




            22516













            • I think you just exploded my brain. I'll give it a try and see how I go.

              – iShaymus
              Jan 1 at 7:40











            • Also the app just plays a single static URL, it will not change and cannot be changed by the user.

              – iShaymus
              Jan 1 at 7:46











            • for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

              – asim
              Jan 1 at 9:32











            • What are the required imports. Auto Import seems to have missed quite a bit.

              – iShaymus
              Jan 1 at 20:59











            • asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

              – iShaymus
              Jan 1 at 21:51



















            • I think you just exploded my brain. I'll give it a try and see how I go.

              – iShaymus
              Jan 1 at 7:40











            • Also the app just plays a single static URL, it will not change and cannot be changed by the user.

              – iShaymus
              Jan 1 at 7:46











            • for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

              – asim
              Jan 1 at 9:32











            • What are the required imports. Auto Import seems to have missed quite a bit.

              – iShaymus
              Jan 1 at 20:59











            • asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

              – iShaymus
              Jan 1 at 21:51

















            I think you just exploded my brain. I'll give it a try and see how I go.

            – iShaymus
            Jan 1 at 7:40





            I think you just exploded my brain. I'll give it a try and see how I go.

            – iShaymus
            Jan 1 at 7:40













            Also the app just plays a single static URL, it will not change and cannot be changed by the user.

            – iShaymus
            Jan 1 at 7:46





            Also the app just plays a single static URL, it will not change and cannot be changed by the user.

            – iShaymus
            Jan 1 at 7:46













            for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

            – asim
            Jan 1 at 9:32





            for play different song you need to pass song list to service. if you want to play single song every time then modify songRequest(String url) and pass url in method parameter service.songRequest(url) method and play that url instant of songList.

            – asim
            Jan 1 at 9:32













            What are the required imports. Auto Import seems to have missed quite a bit.

            – iShaymus
            Jan 1 at 20:59





            What are the required imports. Auto Import seems to have missed quite a bit.

            – iShaymus
            Jan 1 at 20:59













            asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

            – iShaymus
            Jan 1 at 21:51





            asim is this your personal code or is it available somewhere? There seems to be many method calls to MainActivity that I don't have, some constants that I don't have and some UI elements

            – iShaymus
            Jan 1 at 21:51













            0














            So this is the working service for a single live stream URL thanks to asim.



            public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
            public static final String ACTION_PLAY = "com.example.action.PLAY";
            private static final String STREAM_URL = "...";
            private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";

            MainActivity mainActivity;
            MediaPlayer mediaPlayer = null;
            WifiManager.WifiLock wifiLock;

            @Override
            public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
            }

            public class LocalBinder extends Binder {
            public StreamService getServiceInstance() {
            return StreamService.this;
            }
            }

            @Override
            public void onCreate() {
            super.onCreate();
            }

            public int onStartCommand(Intent intent, int flags, int startId) {
            if (intent.getAction().equals(ACTION_PLAY)) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
            mediaPlayer.setOnErrorListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
            wifiLock.acquire();
            try {
            // Set the stream URL location
            mediaPlayer.setDataSource(TEST_URL);
            // prepareAsync must be called after setAudioStreamType and setOnPreparedListener
            mediaPlayer.prepareAsync();
            } catch (Exception e) {
            e.printStackTrace();
            }
            }
            return START_STICKY;
            }

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
            // ... react appropriately ...
            // The MediaPlayer has moved to the Error state, must be reset!
            return false;
            }

            void switchButton() {
            mainActivity.checkPlaying(!mediaPlayer.isPlaying());
            }

            public boolean play() {
            if (mediaPlayer != null) {
            //switchButton();
            if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            return false;
            } else {
            mediaPlayer.start();
            return true;
            }
            }
            return false;
            }

            public void stop() {
            try {
            if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            }
            } catch (Exception ex) {
            ex.printStackTrace();
            }
            }

            /** Called when MediaPlayer is ready */
            public void onPrepared(MediaPlayer player) {
            //player.start();
            }

            @Override
            public void onDestroy() {
            super.onDestroy();
            if( wifiLock != null) wifiLock.release();
            if (mediaPlayer != null) mediaPlayer.release();
            }

            public void registerClient(MainActivity activity) {
            mainActivity = activity;
            }

            public boolean isplaying() {

            return mediaPlayer == null ? false : mediaPlayer.isPlaying();
            }
            }


            Which is implemented in the main activity:



            public class MainActivity extends AppCompatActivity {

            private ImageButton btn; // Play | Pause toggle button
            private ImageView img; // Radio tower image that alternates between on and off
            StreamService service;

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

            // Bind the view buttons to local variables
            btn = findViewById(R.id.playPause);
            img = findViewById(R.id.radioTower);

            startStream();

            btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            if (service.isplaying()) {
            Log.d("pause","Pause Playback");
            } else {
            Log.d("play", "Start Playback");
            }

            }
            });
            }

            public void startStream() {
            Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
            serviceIntent.setAction(StreamService.ACTION_PLAY);
            startService(serviceIntent);
            bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
            }

            public void stopStream() {
            if (service != null) {
            try {
            service.stop();
            unbindService(mConnection);
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            } catch (IllegalArgumentException ex) {
            stopService(new Intent(MainActivity.this, service.getClass()));
            service = null;
            ex.printStackTrace();
            }
            }
            }

            private ServiceConnection mConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName className,
            IBinder _service) {

            StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
            service = binder.getServiceInstance(); //Get instance of your service!
            service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {

            }
            };
            }


            Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.






            share|improve this answer




























              0














              So this is the working service for a single live stream URL thanks to asim.



              public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
              public static final String ACTION_PLAY = "com.example.action.PLAY";
              private static final String STREAM_URL = "...";
              private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";

              MainActivity mainActivity;
              MediaPlayer mediaPlayer = null;
              WifiManager.WifiLock wifiLock;

              @Override
              public IBinder onBind(Intent intent) {
              // TODO Auto-generated method stub
              return null;
              }

              public class LocalBinder extends Binder {
              public StreamService getServiceInstance() {
              return StreamService.this;
              }
              }

              @Override
              public void onCreate() {
              super.onCreate();
              }

              public int onStartCommand(Intent intent, int flags, int startId) {
              if (intent.getAction().equals(ACTION_PLAY)) {
              mediaPlayer = new MediaPlayer();
              mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
              mediaPlayer.setOnErrorListener(this);
              mediaPlayer.setOnPreparedListener(this);
              mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
              wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
              .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
              wifiLock.acquire();
              try {
              // Set the stream URL location
              mediaPlayer.setDataSource(TEST_URL);
              // prepareAsync must be called after setAudioStreamType and setOnPreparedListener
              mediaPlayer.prepareAsync();
              } catch (Exception e) {
              e.printStackTrace();
              }
              }
              return START_STICKY;
              }

              @Override
              public boolean onError(MediaPlayer mp, int what, int extra) {
              // ... react appropriately ...
              // The MediaPlayer has moved to the Error state, must be reset!
              return false;
              }

              void switchButton() {
              mainActivity.checkPlaying(!mediaPlayer.isPlaying());
              }

              public boolean play() {
              if (mediaPlayer != null) {
              //switchButton();
              if (mediaPlayer.isPlaying()) {
              mediaPlayer.pause();
              return false;
              } else {
              mediaPlayer.start();
              return true;
              }
              }
              return false;
              }

              public void stop() {
              try {
              if (mediaPlayer != null) {
              mediaPlayer.release();
              mediaPlayer = null;
              }
              } catch (Exception ex) {
              ex.printStackTrace();
              }
              }

              /** Called when MediaPlayer is ready */
              public void onPrepared(MediaPlayer player) {
              //player.start();
              }

              @Override
              public void onDestroy() {
              super.onDestroy();
              if( wifiLock != null) wifiLock.release();
              if (mediaPlayer != null) mediaPlayer.release();
              }

              public void registerClient(MainActivity activity) {
              mainActivity = activity;
              }

              public boolean isplaying() {

              return mediaPlayer == null ? false : mediaPlayer.isPlaying();
              }
              }


              Which is implemented in the main activity:



              public class MainActivity extends AppCompatActivity {

              private ImageButton btn; // Play | Pause toggle button
              private ImageView img; // Radio tower image that alternates between on and off
              StreamService service;

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

              // Bind the view buttons to local variables
              btn = findViewById(R.id.playPause);
              img = findViewById(R.id.radioTower);

              startStream();

              btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
              if (service.isplaying()) {
              Log.d("pause","Pause Playback");
              } else {
              Log.d("play", "Start Playback");
              }

              }
              });
              }

              public void startStream() {
              Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
              serviceIntent.setAction(StreamService.ACTION_PLAY);
              startService(serviceIntent);
              bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
              }

              public void stopStream() {
              if (service != null) {
              try {
              service.stop();
              unbindService(mConnection);
              stopService(new Intent(MainActivity.this, service.getClass()));
              service = null;
              } catch (IllegalArgumentException ex) {
              stopService(new Intent(MainActivity.this, service.getClass()));
              service = null;
              ex.printStackTrace();
              }
              }
              }

              private ServiceConnection mConnection = new ServiceConnection() {

              @Override
              public void onServiceConnected(ComponentName className,
              IBinder _service) {

              StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
              service = binder.getServiceInstance(); //Get instance of your service!
              service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
              }

              @Override
              public void onServiceDisconnected(ComponentName arg0) {

              }
              };
              }


              Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.






              share|improve this answer


























                0












                0








                0







                So this is the working service for a single live stream URL thanks to asim.



                public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
                public static final String ACTION_PLAY = "com.example.action.PLAY";
                private static final String STREAM_URL = "...";
                private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";

                MainActivity mainActivity;
                MediaPlayer mediaPlayer = null;
                WifiManager.WifiLock wifiLock;

                @Override
                public IBinder onBind(Intent intent) {
                // TODO Auto-generated method stub
                return null;
                }

                public class LocalBinder extends Binder {
                public StreamService getServiceInstance() {
                return StreamService.this;
                }
                }

                @Override
                public void onCreate() {
                super.onCreate();
                }

                public int onStartCommand(Intent intent, int flags, int startId) {
                if (intent.getAction().equals(ACTION_PLAY)) {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
                mediaPlayer.setOnErrorListener(this);
                mediaPlayer.setOnPreparedListener(this);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
                wifiLock.acquire();
                try {
                // Set the stream URL location
                mediaPlayer.setDataSource(TEST_URL);
                // prepareAsync must be called after setAudioStreamType and setOnPreparedListener
                mediaPlayer.prepareAsync();
                } catch (Exception e) {
                e.printStackTrace();
                }
                }
                return START_STICKY;
                }

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                // ... react appropriately ...
                // The MediaPlayer has moved to the Error state, must be reset!
                return false;
                }

                void switchButton() {
                mainActivity.checkPlaying(!mediaPlayer.isPlaying());
                }

                public boolean play() {
                if (mediaPlayer != null) {
                //switchButton();
                if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                return false;
                } else {
                mediaPlayer.start();
                return true;
                }
                }
                return false;
                }

                public void stop() {
                try {
                if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
                }
                } catch (Exception ex) {
                ex.printStackTrace();
                }
                }

                /** Called when MediaPlayer is ready */
                public void onPrepared(MediaPlayer player) {
                //player.start();
                }

                @Override
                public void onDestroy() {
                super.onDestroy();
                if( wifiLock != null) wifiLock.release();
                if (mediaPlayer != null) mediaPlayer.release();
                }

                public void registerClient(MainActivity activity) {
                mainActivity = activity;
                }

                public boolean isplaying() {

                return mediaPlayer == null ? false : mediaPlayer.isPlaying();
                }
                }


                Which is implemented in the main activity:



                public class MainActivity extends AppCompatActivity {

                private ImageButton btn; // Play | Pause toggle button
                private ImageView img; // Radio tower image that alternates between on and off
                StreamService service;

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

                // Bind the view buttons to local variables
                btn = findViewById(R.id.playPause);
                img = findViewById(R.id.radioTower);

                startStream();

                btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                if (service.isplaying()) {
                Log.d("pause","Pause Playback");
                } else {
                Log.d("play", "Start Playback");
                }

                }
                });
                }

                public void startStream() {
                Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
                serviceIntent.setAction(StreamService.ACTION_PLAY);
                startService(serviceIntent);
                bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
                }

                public void stopStream() {
                if (service != null) {
                try {
                service.stop();
                unbindService(mConnection);
                stopService(new Intent(MainActivity.this, service.getClass()));
                service = null;
                } catch (IllegalArgumentException ex) {
                stopService(new Intent(MainActivity.this, service.getClass()));
                service = null;
                ex.printStackTrace();
                }
                }
                }

                private ServiceConnection mConnection = new ServiceConnection() {

                @Override
                public void onServiceConnected(ComponentName className,
                IBinder _service) {

                StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
                service = binder.getServiceInstance(); //Get instance of your service!
                service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
                }

                @Override
                public void onServiceDisconnected(ComponentName arg0) {

                }
                };
                }


                Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.






                share|improve this answer













                So this is the working service for a single live stream URL thanks to asim.



                public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
                public static final String ACTION_PLAY = "com.example.action.PLAY";
                private static final String STREAM_URL = "...";
                private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";

                MainActivity mainActivity;
                MediaPlayer mediaPlayer = null;
                WifiManager.WifiLock wifiLock;

                @Override
                public IBinder onBind(Intent intent) {
                // TODO Auto-generated method stub
                return null;
                }

                public class LocalBinder extends Binder {
                public StreamService getServiceInstance() {
                return StreamService.this;
                }
                }

                @Override
                public void onCreate() {
                super.onCreate();
                }

                public int onStartCommand(Intent intent, int flags, int startId) {
                if (intent.getAction().equals(ACTION_PLAY)) {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
                mediaPlayer.setOnErrorListener(this);
                mediaPlayer.setOnPreparedListener(this);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
                wifiLock.acquire();
                try {
                // Set the stream URL location
                mediaPlayer.setDataSource(TEST_URL);
                // prepareAsync must be called after setAudioStreamType and setOnPreparedListener
                mediaPlayer.prepareAsync();
                } catch (Exception e) {
                e.printStackTrace();
                }
                }
                return START_STICKY;
                }

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                // ... react appropriately ...
                // The MediaPlayer has moved to the Error state, must be reset!
                return false;
                }

                void switchButton() {
                mainActivity.checkPlaying(!mediaPlayer.isPlaying());
                }

                public boolean play() {
                if (mediaPlayer != null) {
                //switchButton();
                if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                return false;
                } else {
                mediaPlayer.start();
                return true;
                }
                }
                return false;
                }

                public void stop() {
                try {
                if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
                }
                } catch (Exception ex) {
                ex.printStackTrace();
                }
                }

                /** Called when MediaPlayer is ready */
                public void onPrepared(MediaPlayer player) {
                //player.start();
                }

                @Override
                public void onDestroy() {
                super.onDestroy();
                if( wifiLock != null) wifiLock.release();
                if (mediaPlayer != null) mediaPlayer.release();
                }

                public void registerClient(MainActivity activity) {
                mainActivity = activity;
                }

                public boolean isplaying() {

                return mediaPlayer == null ? false : mediaPlayer.isPlaying();
                }
                }


                Which is implemented in the main activity:



                public class MainActivity extends AppCompatActivity {

                private ImageButton btn; // Play | Pause toggle button
                private ImageView img; // Radio tower image that alternates between on and off
                StreamService service;

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

                // Bind the view buttons to local variables
                btn = findViewById(R.id.playPause);
                img = findViewById(R.id.radioTower);

                startStream();

                btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                if (service.isplaying()) {
                Log.d("pause","Pause Playback");
                } else {
                Log.d("play", "Start Playback");
                }

                }
                });
                }

                public void startStream() {
                Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
                serviceIntent.setAction(StreamService.ACTION_PLAY);
                startService(serviceIntent);
                bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
                }

                public void stopStream() {
                if (service != null) {
                try {
                service.stop();
                unbindService(mConnection);
                stopService(new Intent(MainActivity.this, service.getClass()));
                service = null;
                } catch (IllegalArgumentException ex) {
                stopService(new Intent(MainActivity.this, service.getClass()));
                service = null;
                ex.printStackTrace();
                }
                }
                }

                private ServiceConnection mConnection = new ServiceConnection() {

                @Override
                public void onServiceConnected(ComponentName className,
                IBinder _service) {

                StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
                service = binder.getServiceInstance(); //Get instance of your service!
                service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
                }

                @Override
                public void onServiceDisconnected(ComponentName arg0) {

                }
                };
                }


                Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 27 at 10:22









                iShaymusiShaymus

                298214




                298214






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993541%2fandroid-background-audio-with-a-live-audio-stream%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas