Skip to content Skip to sidebar Skip to footer

How To Get Usage Stats For "current Day" Using Usagestatsmanager In Android (kotlin)

Objective: Need to get the usage stats for today (total time for which the device was used today) ie. 12.00 am to current time. Problem: 1.I get today's time + some other non expl

Solution 1:

I actually experience a similar problem:

According to my understanding of the documentation firstTimeStamp and lastTimeStamp should give the "beginning (end) of the time range this UsageStats represents".

They differ however from what I give as an argument in queryAndAggregateUsageStats as beginTime and endTime.

Also the result for the totalTimeInForegroundseems rather give back a result for the timespan given by firstTimeStamp / lastTimeStamp than for the requested one.

I filled a bug with google for this, please have a look at https://issuetracker.google.com/issues/118564471.

Solution 2:

I noticed several problems with your approach.

  • You are missing time.set(Calendar.SECOND,0) and time.set(Calendar.MILLISECOND,0)
  • Precision is lost in the division ft=value.totalTimeInForeground/60000

I would recommend Java Time (ThreeTenBP) to handle DateTime and Duration more accurately. I create a new function to compare and indeed the results are different.

funshowtime2(){
    val start = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
    val end = ZonedDateTime.now().toInstant().toEpochMilli()

    val usageStatsManager = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
    val stats = usageStatsManager.queryAndAggregateUsageStats(start, end)

    val total = Duration.ofMillis(stats.values.map { it.totalTimeInForeground }.sum())
    println("YOU SPENT ${total.toMinutes()} mins.")
}

Your output

YOU SPENT 577 mins.

My output

YOU SPENT 582 mins.

Post a Comment for "How To Get Usage Stats For "current Day" Using Usagestatsmanager In Android (kotlin)"