title: Get (real) foreground process using activityManager.getRunningAppProcesses()
body: <p>I am trying to determine the currently visible application for the user.
  To do so, I use the <code>activityManager.getRunningAppProcesses()</code> method.</p>
  
  <p><em>I know that the method is not supported as off Android 5.1.1 - this is ok.</em></p>
  
  <p>In the beginning it worked like charm, I am iterating through the list
  of RunningAppProcessInfos and check for the importance.</p>
  
  <p><strong>tl;dr
  What is the correct method to get current foreground process and prevent false postives? How is the order of the list done - the API says it is not specified. Is there a way to order them correctly?</strong></p>
  
  <p><em>What I have done:</em></p>
  
  <p>Unfortunately the list returned by the ActivityManager is different on every device. Some devices return multiple infos with the importance 100 (which is FOREGROUND), even if the process is currently not visible.</p>
  
  <p>This caused the problem that I had a lot of false positives. 
  For example, I tested it with facebook and created a toast, every time
  facebook is in foreground. I switched to Home, so my launcher should have
  been the foreground process. It was for like 10 seconds, after that, facebook
  appeared with importance FOREGROUND in the list again (it was not open nor visible) and I got a false positive.</p>
  
  <p>I  recognized that some devices order the list by the recent process on top.
  So I decided to try the following approach: </p>
  
  <pre><code>ActivityManager.RunningAppProcessInfo appProcess = appProcesses.get(0);
          final String processName = appProcess.processName;
          final String packageName = removeProcessSuffix(processName);
          if (appProcess.importance == FOREGROUND || appProcess.importance == VISIBLE){
              //do something, like the toast
          }
  </code></pre>
  
  <p>With <strong>appProcesses.get(0);</strong> I only examine the first element and the bug was gone. No false positives anymore.</p>
  
  <p><strong>But</strong>, now on some devices I do not get the foreground process at all anymore. Because they do not order the list in any way.
  For example some 4.2 Sony smartphones are some of the candidates. I get the list, but the really currently visible process is at index 11 or so. </p>
  
  <p>I have no clue what to do, to get the current foreground process, without false positives. </p>
  
  <p>What is the correct method to get current foreground process and prevent false postives? How is the order of the list done - the API says it is not specified.
  Is there a way to order them correctly?</p>
  
  <p><strong>Thanks!</strong></p>