3

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:

  • onResume of each activity I set a global variable as FOREGROUND
  • onPause of each activity I set a global variable as BACKGROUND

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.

Community
  • 1
  • 1
neteinstein
  • 17,529
  • 11
  • 93
  • 123

2 Answers2

7
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;
    }
neteinstein
  • 17,529
  • 11
  • 93
  • 123
Shailendra Singh Rajawat
  • 8,172
  • 3
  • 35
  • 40
2

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.
Community
  • 1
  • 1
neteinstein
  • 17,529
  • 11
  • 93
  • 123