I am having difficulties trying to handle service behaviour in such case.

Basically I have a service running on a separate process that needs to issue httprequests every certain time whenever the app is closed, then write something into preferences or throw a notification.

The logic works fine. The problem I'm having is that **I cannot find a way to properly stop/disable that service whenever the app is running, aswell as start it again when the app is being finished or put into background**.

I've tried stopping it at @onResume()/@onStart() callbacks of my activities aswell as starting it at @onStop()/@onDestroy() but behaviour doesnt run as expected in any case...

I'll paste here some code snippets of what i've tried so far:

I start/stop services using:

```
stopService(new Intent(this,NotificationService.class));
startService(new Intent(this, NotificationService.class));

```

Random activity from my app (all implement this in their callbacks):

```
    @Override
    protected void onResume() {
        if (Utility.isMyServiceRunning(this)){
            Utility.serviceClose(this);
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (!Utility.isMyServiceRunning(this)){
            startService(new Intent(this, NotificationService.class));
        }
        super.onStop();
    }

```

This somehow doesnt work or brings unexpected behaviour since the app moves from many activities, and service ends up being alive when the app is running or stopped when the app is in background/finished.

I've also tried to toggle on/off service logic on service timertask every cicle by asking:

```
    @Override
    public void run() {

       ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService( ACTIVITY_SERVICE );
            List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
                for(int i = 0; i < procInfos.size(); i++){
                    if(procInfos.get(i).processName.equals("com.example.myapp")) {
                        return;
                    }
                }
    //service http request logic here
    }

```

But that doesnt work either because process "com.example.myapp" never gets killed (and of course I cannot/want to force finish that), so it never issues any httprequest.

Any Ideas on how to implement this? Any help would be very welcome.

Thanks in advance.