Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple check for Android application backgrounding

Tags:

android

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.

like image 508
Captain Blammo Avatar asked Nov 15 '22 01:11

Captain Blammo


1 Answers

Your solution might work but I don't know.

You might be able to use a BroadcastReceiver. If you use BroadcastReceiver you can issue an Intent when an activity executes onPause() along with your plus/minus code. The BroadcastReceiver will be able to can execute your app again...

like image 167
Ethan Avatar answered Dec 23 '22 03:12

Ethan