title: How to detect current foreground app when foreground service is running
body: <p>I'm currently working on an AppLock which includes service that detects current foreground app but the problem is the service keeps returning the AppLock itself as the current foreground app even after I minimize it or close the AppLock. Is there a way to fix this?</p>
  
  <p>I'm aware of other similar questions have been answered but I don't see anyone else having the same problem as me as far as I can see.</p>
  
  <p>Below is the code I'm using to detect the foreground app</p>
  
  <pre><code>public String getForegroundApp() {
  
      String currentApp = "NULL";
      UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
      long time = System.currentTimeMillis();
      List&lt;UsageStats&gt; appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
      if (appList != null &amp;&amp; appList.size() &gt; 0) {
          SortedMap&lt;Long, UsageStats&gt; mySortedMap = new TreeMap&lt;Long, UsageStats&gt;();
          for (UsageStats usageStats : appList) {
              mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
          }
          if (mySortedMap != null &amp;&amp; !mySortedMap.isEmpty()) {
              currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
          }
      }
      else {
          ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
          List&lt;ActivityManager.RunningAppProcessInfo&gt; tasks = am.getRunningAppProcesses();
          currentApp = tasks.get(0).processName;
      }
  
      return currentApp;
  }
  </code></pre>
  
  <pre><code>public int onStartCommand(Intent intent, int flags, int startId) {
      if(foreapp.equals(lockedApp)){
          Intent intentp3=new Intent(getApplicationContext(), PasswordPage3.class);
          intentp3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intentp3);
      }
      return START_STICKY;
  }
  </code></pre>
  
  <p>The receiver I'm using to start the service:</p>
  
  <pre><code>public class RestartReceiver extends BroadcastReceiver{
      @Override
      public void onReceive(Context context, Intent lol) {
          Log.i("running in the back","restarting");
  
          if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
              context.startForegroundService(new Intent(context, MyService.class));
          } else {
              context.startService(new Intent(context, MyService.class));
          }
      }
  }
  </code></pre>
  
  <p>Note: foreapp and lockedApp are both String variables</p>
  
  <p>The String that currentApp returns are constantly com.example.apptest3 which is the package name that I'm working on.</p>