title: Android UsageStatsManager: Get a list of currently running apps on phone
body: <p>I am trying to get a list of currently running apps on my phone. Here is the code I am using:</p>
  
  <pre><code>if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.LOLLIPOP) {
              UsageStatsManager usm = (UsageStatsManager)this.getSystemService(Context.USAGE_STATS_SERVICE);
              long time = System.currentTimeMillis();
              List&lt;UsageStats&gt; appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 10000*10000, time);
              if (appList != null &amp;&amp; appList.size() == 0) {
                  Log.d("Executed app", "######### NO APP FOUND ##########" );
              }
              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) {
                      Log.d("Executed app", "usage stats executed : " +usageStats.getPackageName() + "\t\t ID: ");
                      mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                  }
                  if (mySortedMap != null &amp;&amp; !mySortedMap.isEmpty()) {
                      String currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
  
                  }
              }
          }
  </code></pre>
  
  <p>Here I have set the permission as well: </p>
  
  <pre><code>&lt;uses-permission
      android:name="android.permission.PACKAGE_USAGE_STATS"
      tools:ignore="ProtectedPermissions" /&gt;
  </code></pre>
  
  <p>It does not detect any app usage. I have tried some other things on stackoverflow but nothing seems to work. I have even read somewhere that the ability for apps to monitor other apps running on the phone has been removed completely in the newer phones. Would greatly appreciate any help! </p>