How to check if the app is running in background or foreground

63 Views Asked by At

I have a Service that always running in the background even if the app is completely closed. In this service, I have a BroadcastReceiver that let me know if the device is charging or not :

  @Override
    public void onBatteryStatusChanged(BatteryUtils.Status status) {
        if (status.getStatus() == BatteryUtils.BatteryStatus.CHARGING) {
             if(!AppUtils.isAppRunning(getPackageName()))
                   LogUtils.dTag(Constants.TAG, "APP SHOULD LAUNCH NOW");
        }
    }

public static boolean isAppRunning(final String pkgName) {
    ActivityManager am = (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
    if (am != null) {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(Integer.MAX_VALUE);
        if (taskInfo != null && taskInfo.size() > 0) {
            for (ActivityManager.RunningTaskInfo aInfo : taskInfo) {
                if (aInfo.baseActivity != null) {
                    if (pkgName.equals(aInfo.baseActivity.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        List<ActivityManager.RunningServiceInfo> serviceInfo = am.getRunningServices(Integer.MAX_VALUE);
        if (serviceInfo != null && serviceInfo.size() > 0) {
            for (ActivityManager.RunningServiceInfo aInfo : serviceInfo) {
                if (pkgName.equals(aInfo.service.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}

My Goal :

Is launching the app once the charger is plugged in, but only if it hasn't already been launched.

My Issue :

When I check whether the app is running or not, it always returns TRUE, even when the app is closed. This behavior occurs because the service is running in the background, leading to the entire app being considered as running.

1

There are 1 best solutions below

0
David Wasser On

You are checking if your Service is running, and of course it is, so this method will ralways eturn true. Using getRunningTasks() is not intended for this purpose and probably won't be reliable, especially with newer Android versions.

What you should do is to store the current "charging" state in shared preferences. Whenever your BroadcastReceiver is triggered, compare the new "charging" state to the state you have stored in shared preferences. If they are different and the new state is "CHARGING", then you can launch your app.