I determint if my application is in foreground
There's couple of ways to find out what is in front, but I actually prefer to track this myself (as this helps me apply additional logic if needed). Plus it's pretty simple task. To make this happen you need static int
based counter somewhere (you can use your Application
object if you have one, or have it elsewhere, does not really matter). In each Activity
's onResume()
you increment the counter by one, and in onPause()
you decrement it by one. If counter equals 0
then none of your activities is in foreground so from your perspective you are in background and you post notification. For simplicity I always do that in my ActivityBase
class all my activities extend.
If you do not want to track it yourself, you can use ActivityManager
to see what's currently in foreground:
public boolean isAppInForeground() {
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = am.getRunningTasks(Integer.MAX_VALUE);
return (services.get(0).topActivity.getPackageName().toString()
.equalsIgnoreCase(getPackageName().toString()));
}
but this requires <uses-permission android:name="android.permission.GET_TASKS" />
entry in your Manifest, so not always welcome.