I want to find out the foreground time of a certain app from 12AM to the current time . Here is what i tried so far
String PackageName = "Nothing";
long TimeInforground = 500;
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService("usagestats");
long time = System.currentTimeMillis();
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
List<UsageStats> stats = mUsageStatsManager.queryUsageStats( UsageStatsManager.INTERVAL_BEST,
c.getTimeInMillis(),
time );
if ( stats != null )
{
for ( UsageStats usageStats : stats )
{
if ( usageStats.getPackageName().contains("example.app") )
{
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.e("BAC", "PackageName is" + PackageName + "Time is: " + hours + "h" + ":" + minutes + "m" + seconds + "s");
break;
}
}
}
}
I expect the foreground time to be 0 when the time is a little more than 12 AM and the example.app is not opened. But that doesn't seem to be the case. It tends to not reset at 12 AM but much later.
I haven't found too much documentation on UsageStatsManager and the above code is a slight modification of an other answer on StackOverflow to match my needs .
I have also tried UsageStatsManager.INTERVAL_DAILY but even that doesn't seem to be serving my purpose exactly.
Any help is much Appreciated.