Android:如何在UsageStats

时间:2017-07-03 20:21:53

标签: android usagestatsmanager

我可以使用UsgaeStatsManager获取应用程序的使用情况统计信息,如下所示

UsageStatsManager usm = getUsageStatsManager(context);
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
calendar.add(Calendar.DATE, -1);
long startTime = calendar.getTimeInMillis(); 

List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);

for (UsageStats u : usageStatsList){
   Log.d(TAG, "Pkg: " + u.getPackageName() +  "\t" + "ForegroundTime: "
                + u.getTotalTimeInForeground() + " milliseconds") ;
}

当我得到输出时,它如下所示:

Pkg:com.skype.raiderForeground used time in ms:23922
Pkg:com.google.android.youtubeForeground used time in ms:0
Pkg:com.sec.android.app.chromecustomizationsForeground used time in ms:0
Pkg:com.whatsappForeground used time in ms:1665723
.
.
.

哪个是正确的但我希望这个列表包含更多用户可读格式的应用程序名称,如

Pkg:skype Foreground used time in ms:23922
Pkg:youtube Foreground used time in ms:0
Pkg:whatsapp Foreground used time in ms:1665723

我想知道我们是否有类似于api applicationInfo.loadLabel(getPackageManager())。toString();在PackageManager中,它提供用户可读的包名称而不是包的技术名称。或者,有没有其他方法来打印包的简单名称?

1 个答案:

答案 0 :(得分:0)

您可以使用此方法使用包名称

获取AppName
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 : usageStatsList){
    Log.d(TAG, "Pkg: " + getAppNameFromPackage(u.getPackageName(), context) +  "\t" + "ForegroundTime: "
            + u.getTotalTimeInForeground() + " milliseconds") ;
}

它会给出像

这样的结果
Pkg:skype Foreground used time in ms:23922
Pkg:youtube Foreground used time in ms:0
Pkg:whatsapp Foreground used time in ms:1665723