title: Android: How to check application is Running or not
body: <p>I need to check by packageName - running application or not.
  Until v.21 I simply get list of running applications and dance.
  But now it not working - returns only one my app.
  I know that I need use "Statistics Usage", but can't find completely example for it.</p>
  
  <p>I don't need all this analytics, I need one simple function</p>
  
  <pre><code>bool isRunning(String packageName)
  </code></pre>
  
  <p>How to implement it on new Android (>21) without dancing arround it?</p>
  
  <h1>upd. Answer of code4rox the best. All is OK, thanks!</h1>
  
  <p>I use this code for check rights:</p>
  
  <pre><code>import android.content.pm.PackageManager;
  import android.content.pm.ApplicationInfo;
  import android.app.AppOpsManager;
  import android.util.Log;
  import  android.provider.Settings;
  
  try {
              PackageManager packageManager = getContext().getPackageManager();
              ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getContext().getPackageName(), 0);
              AppOpsManager appOpsManager = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
              int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
              if (!(mode == AppOpsManager.MODE_ALLOWED)) {
                  Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                  startActivity(intent);
              }
          } catch (PackageManager.NameNotFoundException e) {}
  </code></pre>
  
  <p>And this for check app:</p>
  
  <pre><code>import android.util.Log;
  import android.app.usage.UsageStatsManager;
  import android.app.usage.UsageStats;
  import java.util.List;
  import java.util.SortedMap;
  import java.util.TreeMap;
  import java.util.ArrayList;
  
  public boolean isRunning(Context context, long timeMills, String app) {
          boolean result = false;
          //timeMils = 1000
          UsageStatsManager usm = (UsageStatsManager)context.getSystemService(Context.USAGE_STATS_SERVICE);
          long time = System.currentTimeMillis();
          List&lt;UsageStats&gt; appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - timeMills, time);
          if (appList != null &amp;&amp; appList.size() &gt; 0) {
              for (UsageStats usageStats : appList) {
                  String appname = usageStats.getPackageName();
                  Log.i("DOM_LAUNCHER", "Running app: " + appname);
                  if (app.equals(appname)) {
                      result = true;
                  }
              }
          }
          return result;
      }
  </code></pre>