简体   繁体   English

Android:在Kotlin中获取UsageStats

[英]Android: Get UsageStats in Kotlin

I'm trying to use UsageStats to get statistics in android but it returns me that list size is ZERO. 我正在尝试使用UsageStats来获取android中的统计信息,但返回的列表大小为零。 I'm using API 23. 我正在使用API​​ 23。

    val statsManager = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
    var list : MutableList<UsageStats>


   //Check if API is 21
   if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
    {     
       val cal = Calendar.getInstance()
       cal.add(Calendar.YEAR, -1)

      list = statsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis())
    }            

 Log.d("DetailActivity","------"+list.size)

I can't see where the problem is. 我看不出问题出在哪里。 Can you please help. 你能帮忙吗?

Your code is correct, but first you need to add the following persmission in your manifest : 您的代码是正确的,但是首先您需要在清单中添加以下权限:

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>

Then make sure the user grants the permission by sending this Intent : 然后通过发送以下Intent来确保用户授予许可:

startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

Then only you will be granted the access to the UsageStatsManager. 然后,将仅授予您对UsageStatsManager的访问权限。

You will find a lot more information in this post 您将在这篇文章中找到更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM