androidusagestatsmanager

Android: how to get application label in UsageStats


I am able to get the usage statistics of the app using the UsgaeStatsManager like below

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

When I get the output then it comes like below:

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
.
.
.

Which is correct but I want to get this list with names of apps in more user readable format like

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

I am wondering if we have any api similar to api applicationInfo.loadLabel(getPackageManager()).toString(); in PackageManager which gives the user readable package name instead of technical name of package. Or, is there any other way to print the simple name of the package ?


Solution

  • You can use this method to get the AppName using package name

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

    You can print for loop like this,

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

    It will give result like

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