Update Oct 2020: Checkout the Lifecycle extensions based solutions on this thread. The approach seems to be working, it's more elegant and modern.
The neatest and not deprecated way that I've found so far to do this, as follows:
@Override
public boolean foregrounded() {
ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(appProcessInfo);
return (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
}
It only works with SDK 16+.
EDIT:
I removed the following code from the solution:
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
// App is foreground, but screen is locked, so show notification
return km.inKeyguardRestrictedInputMode();
since that makes not getting the notifications if the screen locked. I had a look to the framework and the purpose of this is not entirely clear. I'd remove it. Checking the process info state would be enough :-)