How to get usage stats for “current day” using usageStatsManager in android (kotlin)

后端 未结 2 423
孤独总比滥情好
孤独总比滥情好 2021-01-18 20:39

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 ti

2条回答
  •  余生分开走
    2021-01-18 21:15

    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.

    fun showtime2(){
        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.

提交回复
热议问题