How to stop BackGround service automatically when app is not in use?

1.4k views Asked by At

Now i am going on with my notification part for that using BackGround Service in current the service will run even after my app get stopped or either i use other app

But Now what i need was if the app is not active for 5min or more the BackGround service should stop by automatically.

I had gone with the following but no use it remains the same:

public class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }
}

Tried a lot to fix but remains the same is there any other go please help me friends to solve this problem.

Updated:

 public class ApplicationActivity  implements Application.ActivityLifecycleCallbacks {
        // I use four separate variables here. You can, of course, just use two and
        // increment/decrement them instead of using four and incrementing them all.
        public static int resumed;
        public static int paused;
        public static int started;
        public static int stopped;
    public static boolean stopStatus = false;
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
        }

        @Override
        public void onActivityResumed(Activity activity) {
            ++resumed;
        }

        @Override
        public void onActivityPaused(Activity activity) {
            ++paused;
            android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            ++started;
        }

        @Override
        public void onActivityStopped(Activity activity) {
            ++stopped;
            stopStatus = true;
            android.util.Log.w("test", "application is visible: " + (started > stopped));
        }

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        // Simply add the handler, and that's it! No need to add any code
        // to every activity. Everything is contained in MyLifecycleHandler
        // with just a few lines of code. Now *that's* nice.
        registerActivityLifecycleCallbacks(new ApplicationActivity());
    }
}
2

There are 2 answers

7
Larry Schiefer On

It's still not clear exactly what you are trying to do and why. If your service is a subclass of Service then it can stop itself or your activities can explicitly stop it. If your activities bind with it rather than calling startService(), the system can automatically stop the service once all clients have been unbound. Android is built so that it can start and stop them as needed. Note that even if your service and all activities are stopped, your app's process will stick around until the system needs resources.

8
Zielony On

I would go with another approach:

  • Use onPause and onResume methods to track state of your Activities.
  • When your last Activity is being paused, start a timer task with 5min delay.
  • In the task stop the service.
  • If you hit onResume method and the task is not null, clear the task.