Search code examples
androidandroid-studioserviceandroid-service

How to stop a Android service called from multiple activites when app is closed?


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?


Solution

  • Service is a background process. It is not meant to start/stop from every activity.

    • You can start your service only once in your app. Like you started in your first activity (splash) or application level class. You don't need to start service in every activity.
    • Same you don't need to stop your service from every activity. You can stop your service once when you handle onBackPress().

    How do I then pass variables to the service from other activites?

    There are several ways you can communicate between Activities & Services.

    If you ask my preference, I used BroadcastReceiver & Binder earlier days. But now I use EventBus. You can simple implementation steps in EventBus documentation.

    Suggestion:

    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;
    }