Reputation: 17613
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:
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
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:
Upvotes: 2
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