porthfind
porthfind

Reputation: 1619

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. I'm using 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.

Upvotes: 0

Views: 952

Answers (1)

Bruno
Bruno

Reputation: 178

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 :

startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

Then only you will be granted the access to the UsageStatsManager.

You will find a lot more information in this post

Upvotes: 1

Related Questions