Using usageStats.getTotalTimeInForeground () to get the time for each app on the device that was being held in the foreground

I want to know the time taken by all applications running on an android device. I am getting all package names using the following code. Please tell me how to bundle packages and the above method to get the time spent by applications

Here is the code

List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
    for (PackageInfo pack : packs) {
        if (pack.firstInstallTime != pack.lastUpdateTime) {
            Log.i("n-names",
                    pack.applicationInfo.loadLabel(getPackageManager())
                            .toString());
            Log.i("n-install time", pack.firstInstallTime + "");
            Log.i("n-uptime", pack.lastUpdateTime + "");
            UsageStats usage = null;
            usage.getTotalTimeInForeground();
        }
    }

      

Please tell me how to use the above methods for individual packages

+3


source to share


1 answer


If you want to get the foreground runtime for all apps in android lollipop use the following code snippet.

// Variables with dummy values ​​and objects.



UsageStats usageStats;

String PackageName = "Nothing" ;

long TimeInforground = 500 ;

int minutes=500,seconds=500,hours=500 ;
UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");     

long time = System.currentTimeMillis(); 

List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time); 

 if(stats != null) 
  {
            SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
            for (UsageStats usageStats : stats) 
               {

                TimeInforground=usageStats.getTotalTimeInForeground();

                PackageName=usageStats.getPackageName();

                minutes = (int) ((TimeInforground / (1000*60)) % 60);

                seconds = (int) (TimeInforground / 1000) % 60 ;

                hours   = (int) ((TimeInforground / (1000*60*60)) % 24);

                Log.i("BAC", "PackageName is"+PackageName +"Time is: "+hours+"h"+":"+minutes+"m"+seconds+"s");

            }   

      

Make sure you have all the permissions in the manifest file and the application has access using under security in the settings.

+2


source







All Articles