I'm tracking how many activites are currently visible in my app (which should be 0 or 1) by calling plusActivity() from each Activity's onResume() and minusActivity() from onPause()
plus/minusActivity are in my myApplication class, which extends Application.
The methods increment and decrement a counter. Every time minusActivity() is called, it also posts a runnable which runs after 2 seconds. When the runnable executes, if another activity hasn't opened after the last one closed 2 seconds ago ( e.g. foregroundedActivities == 0 because nothing called plusActivity() within 2 seconds), then it calls a method to do some stuff that needs to happen when backgrounded.
Here's a snippet:
public void plusActivity(){
foregroundedActivities++;
}
public void minusActivity(){
foregroundedActivities--;
timingHandler.removeCallbacks(checkBackgroundTask);
timingHandler.postDelayed(checkBackgroundTask, 2000);
}
public void checkIfBackgrounded(){
if(foregroundedActivities==0){
doWhateverWeDoWhenBackgrounded();
}
}
public Runnable checkBackgroundTask=new Runnable(){
@Override
public void run() {
checkIfBackgrounded();
}
};
Given the 2-second timeframe this process operates in, and that no callbacks to an Activity are involved, is it an acceptable way to accomplish background detection, or do I really need to do all this with a Service? It seems like a lot of overhead and I can't see any benefits, since this seems to work fine.