How I can detect that my Android app on the foreground?
<p>I'm trying to know my or no application on the foreground using the next code from BroadcastReceiver:</p>

<pre><code>boolean inForeground = false;
ActivityManager actMngr = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List&lt;RunningAppProcessInfo&gt; runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
    if (context.getPackageName().equals(pi.processName)) {
      inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
    }
}
</code></pre>

<p>But this code always return <strong>true</strong>, even when my application in background.
I found next solution:</p>

<pre><code>if (actMngr.getRunningTasks(1).get(0).topActivity.getPackageName().equals(context.getPackageName())){
  Log.d(TAG, "My");
} else {
  Log.d(TAG, "Not my");
}
</code></pre>

<p>Is this code correct or not?
Or maybe somebody know more simple variant?
Thanks!</p>
