I’m trying to know my or no application on the foreground using the next code from BroadcastReceiver:
boolean inForeground = false;
ActivityManager actMngr = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
if (context.getPackageName().equals(pi.processName)) {
inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
}
}
But this code always return true, even when my application in background.
I found next solution:
if (actMngr.getRunningTasks(1).get(0).topActivity.getPackageName().equals(context.getPackageName())){
Log.d(TAG, "My");
} else {
Log.d(TAG, "Not my");
}
Is this code correct or not?
Or maybe somebody know more simple variant?
Thanks!
The most direct way is to track your foreground status using
onResume()andonPause(). Refer to the Activity lifecycle model.