Below is the code I run to get the processes that were running on the Android device. But the catch is i get it along with all the system processes. Is there a way to separate the System Servies (or) can I change the function call so that I dont get the system services altogether.

   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public List<UsageStats> getUsageStats() {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getActivity()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY,0);
            cal.set(Calendar.MINUTE,1);
            List<UsageStats> queryUsageStats = mUsageStatsManager
                    .queryUsageStats(UsageStatsManager.INTERVAL_BEST, cal.getTimeInMillis(),
                            System.currentTimeMillis());

                       return queryUsageStats;
        }
1

There are 1 best solutions below

0
On

What I do is to convert the each result from queryusageStats into a package name and then filter them out. If the package is a user installed package then it will have a proper name else it will be printed as null. I am also not able to find any straight way forward so had to work around this.

For example:

private String getAppNameFromPackage(String packageName, Context context) {
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> pkgAppsList = context.getPackageManager()
            .queryIntentActivities(mainIntent, 0);

    for (ResolveInfo app : pkgAppsList) {
        if (app.activityInfo.packageName.equals(packageName)) {
            return app.activityInfo.loadLabel(context.getPackageManager()).toString();
        }
    }
    return null;
}

for (UsageStats u : queryUsageStats){

   String package_name = getAppNameFromPackage(u.getPackageName(), context);

   if(package_name.equals(null){

       Log.d(TAG, "Pkg:" + package_name + " is an system package/service");

   }else

       Log.d(TAG, "Pkg: " + package_name +  "\t" + "ForegroundTime: "
        + u.getTotalTimeInForeground() + " milliseconds") ;
}