Using usageStats.getTotalTimeInForeground() to get the time every application in a device spent in foreground

浪尽此生 提交于 2019-12-05 01:55:52

问题


I want to know the time spent by all applications running in an android device . I am getting all packages names using the following code .Please guide me how to link packages and the above method to get 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 indivudual packages


回答1:


If you want to get the foreground running time of all applications in android lollipop use the following piece of code.

//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 right permissions in manifest file and app have access with usage under security in settings.



来源:https://stackoverflow.com/questions/27563401/using-usagestats-gettotaltimeinforeground-to-get-the-time-every-application-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!