I have a public class Tracking extends Service
witch is called from practically every activity with something like this:
Intent serviceIntent = new Intent(this, Tracking.class);
serviceIntent.putExtra("name", "Tabla3b Kras");
serviceIntent.putExtra("time", TimeGenerator.getTime());
startService(serviceIntent);
And that works fine, public void onCreate()
is called only the fisrst time and, public int onStartCommand(Intent intent, int flags, int startId)
is called every other time.
The problem I have is that when the user closes the app. Let's say double back press or going in the open apps list and dismising it. I get a "Unfortunately, "appname" has stopped working.
I know that I can close the service in onStop(), but since I am calling the service from almost all the activities do I have to implement onStop() in all of them or is it enough to just do it in MainActivity.java? And will the service stop if the user changes between activities?
onBackPress()
.How do I then pass variables to the service from other activites?
There are several ways you can communicate between Activities & Services.
Binder
. You can follow this answer.Handler
. Follow this.BroadcastReceiver
. Follow this.EventBus
by GreenBot. This library is getting popular now a day becasue of ease of implement.If you ask my preference, I used BroadcastReceiver
& Binder
earlier days. But now I use EventBus. You can simple implementation steps in EventBus documentation.
Check if your service is already running or not. Start service before use if not running.
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}