I'm creating a radio streaming app; in order to keep the audio playing when the user is working with other apps, I know I need to use a foreground service to run the code pertinent to streaming the audio.
Currently, I have the following code in my MainActivity
class:
@Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
and:
private ServiceConnection musicConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
musicBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
I'm calling startService()
in the onStart()
of the MainActivity
, but I know I should be calling startForeground()
, and yet I can't get it working. I don't have any real need to communicate with the user after the MainActivity
has been closed, since it's just a radio streaming app/the user doesn't need to be able to change or identify songs that are currently playing. Any suggestions for altering how my service is operating? Thanks.