bayoudh Mohamed
bayoudh Mohamed

Reputation: 39

How to check if an Android application is running in the background or in foreground?

for exemple i have this code in my project :

   public class Utilities extends Application
{
    private static int stateCounter;

    public void onCreate()
    {
        super.onCreate();
        stateCounter = 0;
    }

    /**
     * @return true if application is on background
     * */
    public static boolean isApplicationOnBackground()
    {
        return stateCounter == 0;
    }

    //to be called on each Activity onStart()
    public static void activityStarted()
    {
        stateCounter++;
    }

    //to be called on each Activity onStop()
    public static void activityStopped()
    {
        stateCounter--;
    } 
}

but in ios is simple to detect the state :

let state: UIApplicationState = UIApplication.sharedApplication().applicationState // or use  let state =  UIApplication.sharedApplication().applicationState

if state == .Background {

// background
}
else if state == .Active {

// foreground
}

I m searching if android have another solution to do this test ?

Upvotes: 1

Views: 2074

Answers (3)

Joshua Pinter
Joshua Pinter

Reputation: 47591

Try using the Lifecycle's currentState method.

public static boolean appIsOrWasInBackground() {
  Lifecycle.State currentState = ProcessLifecycleOwner.get().getLifecycle().getCurrentState();
  return currentState == Lifecycle.State.CREATED || currentState == Lifecycle.State.STARTED; // CREATED is when the app is currently in the background. STARTED is when the app is coming from the background, for example, from a `startActivity` call from a background Service or BroadcastReceiver. Either of these mean it _is_ or _was_ in the background (and should probably stay there).
}

Upvotes: 1

Hitesh Gehlot
Hitesh Gehlot

Reputation: 1347

write this method in application class and use wherever you want.

  public boolean isApplicationBroughtToBackground() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(getPackageName())) {
            return true;
        }
    }
    return false;
}

create a new class baseActivity

public class BaseActivity extends AppCompatActivity {

static Boolean IsResumecalled = false;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
protected void onResume() {
    super.onResume();
    if (!IsResumecalled) {
        //call api here
    IsResumecalled= true;
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (Myapplication.getInstance().isApplicationBroughtToBackground()) {
      //call api here
       IsResumecalled= false;
    }
}

}

and extends with BaseActivity for every activity class

Upvotes: 4

Tasneem
Tasneem

Reputation: 803

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

Upvotes: 2

Related Questions