Reputation: 93
On my Service(Service1) I have onCreate() & onDestroy() methods,
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
After clicking the home button(user is now on device home scren) the onDestroy() method will be triggered after x minutes, When I open the app again I want to restart the service so the onCreate() will be called again, so I tried this code on my activity's onResume()
stopService(new Intent(this, Service1.class));
startService(new Intent(this, Service1.class));
And it fixed the issue, the onCreate() is called again, but is this the right way of restarting it after onDestroy()? (Some says this will cause issues), I saw some articles that we should use onStartCommand() or startForegroundService().
Upvotes: 1
Views: 113
Reputation: 1105
Alriht. Let's discuss some points about behaviour of services.
Before Oreo(Android 8):
If you are using startService or stopService it will work fine on the devices below Oroe(Android 8). Starting from Oreo google has implemented mechanism so that we must need to start foreground service along with service to inform users that some background task is running so with foreground service we must need to add notification to notify users that there is some task running in background. Let's suppose playing music, downloading file or uploading dat etc.
What if we don't start foreground service on Oreo or later Versions:
If we dont start foreground service right after starting service then our operating system will kill service with in 5 seconds.
Background task recommendation:
If you only need to do background task then you need to implement WorkManager. Workmanagers are more flexible, backward compatible and easy to handle. We don't need to start workmanagers on device reboot like service they restart itself and depends on implementation they can run till your application life. We can also add constraint like internet connectivity or battery etc. So, we can save our battery too. Check link to read more about workmanager.
Thanks!
Upvotes: 1