Check if a specific app is running in the background

2.9k Views Asked by At

I need to know when a specific app is in the background (not foreground).

I was able to get package name of all the applications running in the background with this code:

ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
// Process running
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService(USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    // We get usage stats for the last 10 seconds
    List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
    // Sort the stats by the last time used
    if(stats != null) {
        SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
        for (UsageStats usageStats : stats) {
            mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
            Log.d("RunningAppProcessInfo","Package name : "+usageStats.getPackageName());
        }

    }
} 

But now how do I check if the specific app is on the list or not?

Thanks

1

There are 1 best solutions below

6
On

If you want to check Specific Package than check below code I have added code in below method.

ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
// Process running
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService(USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    // We get usage stats for the last 10 seconds
    List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
    // Sort the stats by the last time used
    if(stats != null) {
        SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
        for (UsageStats usageStats : stats) {
            mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
            Log.d("RunningAppProcessInfo","Package name : "+usageStats.getPackageName());

        if(usageStats.getPackageName().equals("package name")) {
          Log.d("Package ","Package name : Success");
         }

        }

    }
}