neteinstein
neteinstein

Reputation: 17613

What the best way to check if an Android application is in foreground?

I have an application that uses AsyncTasks to make REST calls to a server. Whenever the AsyncTask is finished, it either: shows an error dialog/calls the next activity (if the application is in foreground) or does nothing (application is in background).

I do this to avoid having an activity poping out after the application is sent to background.

I've seen some implementations:

  1. check android application is in foreground or not?
  2. Determining the current foreground application from a background task or service

Currently i'm using another, even simpler:

Which would you recommend?

PS I am aware of the best practice of REST calls as described in this video https://www.youtube.com/watch?v=xHXn3Kg2IQE&list=PL73AA672847DC7B35 and in my specific case this approach seems more appropriate.

Upvotes: 3

Views: 4400

Answers (2)

neteinstein
neteinstein

Reputation: 17613

I ended up having a static variable that every Activity sets to true on onResume and to false on onPause.

Added these methods on an Activity that all other activities extend:

    public abstract class AbstractActivity extends Activity 
    {

     private static boolean isInForeground = false;

     @Override
      protected void onResume()
     {
        super.onResume();
        isInForeground = true;
    }


    @Override
    protected void onPause()
    {
        super.onPause();
        isInForeground  = false;
    }

 }

To understand why it works: Activity side-by-side lifecycle

This will give me the information if MY APP is on foreground or background.

But still Shailendra Rajawat is the more standard option... because this has some weaknesses:

  1. It only works to know if MY OWN app is in foreground or background
  2. It doesn't work if you have transparent activities. Because the lifecycle will not be the same, the onPause/onStop won't be called when a transparent activity is started.

Upvotes: 2

Shailendra Singh Rajawat
Shailendra Singh Rajawat

Reputation: 8242

private boolean isAppForground() {

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> l = mActivityManager
                .getRunningAppProcesses();
        Iterator<RunningAppProcessInfo> i = l.iterator();
        while (i.hasNext()) {
            RunningAppProcessInfo info = i.next();

            if (info.uid == getApplicationInfo().uid && info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) 
                {
                    return true;
               }
           }
        return false;
    }

Upvotes: 7

Related Questions