I'm a bit confused because i read some posts where i'm supposed too use ContextCompat.StartForegroundService();
if the API is >= 26.
Now I still just use StartService and it works even though i'm supposed to get an IllegalStateException
on an API >= 26 ( current api on phone is 27) according to this post.
https://medium.com/mindorks/mastering-android-service-of-2018-a4a1df5ed5a6
I know Service is an old concept. Let me assure you we will not discuss the basics and we will learn the recent changes made to the service layer in Android 8.0+, we will solve the mystery of famous IllegalStateException and RemoteServiceException. This article is not a conventional way of understanding services, hang tight till you can.
So my question is if i should change startForeGroundService
or just keep startService
for API >=26?
My Class that handles my Service connection:
/**This establishes the connection to the MediaPlayerService. */
public static ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.MusicBinder binder = (MediaPlayerService.MusicBinder)service;
mediaPlayerService = binder.getService();
mediaPlayerService.musicBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mediaPlayerService.musicBound = false;
}
};
/**This is called to start the MediaPlayerService. */
private static Intent mediaPlayerServiceIntent = null;
public static void startMusicService(Context c) {
/*mediaPlayerServiceIntent binds our connection to the MediaPlayerService. */
mediaPlayerServiceIntent = new Intent(c, MediaPlayerService.class);
c.bindService(mediaPlayerServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
c.startService(mediaPlayerServiceIntent);
mServiceIsActive = true;
}
/**This is called to stop the MediaPlayerService. (onDestroy) */
public static void stopMusicService(Context c) {
if (mediaPlayerServiceIntent == null)
return;
c.unbindService(serviceConnection);
c.stopService(mediaPlayerServiceIntent);
mediaPlayerServiceIntent = null;
mediaPlayerService = null;
}
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Main.startMusicService(getApplicationContext());
}