如何区分系统服务与Android中UsageStatsManager类的queryUsageStats()返回的List

时间:2016-12-19 22:09:33

标签: android usagestatsmanager

以下是我为了获取Android设备上运行的流程而运行的代码。但问题是我得到了所有系统流程。有没有办法分离系统服务(或)我可以更改函数调用,以便我不完全得到系统服务。

   @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 个答案:

答案 0 :(得分:0)

我所做的是将来自queryusageStats的每个结果转换为包名,然后将其过滤掉。如果包是用户安装的包,那么它将具有正确的名称,否则它将被打印为null。我也无法找到任何直接的方法,所以不得不解决这个问题。

例如:

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") ;
}