0

I'm trying to access the standby bucket that my app is currently in by calling UsageStatsManager.getAppStandbyBucket() in my activity, but the getAppStandbyBucket() method is unresolved. The docs say that the method is public. I've ensured that my compilesdk and targetsdk are both set to 28. My buildtools are also up to date.

Edit: This is not duplicate. I needed to access the Application to be able to get the UsageStatsManager - see my answer below

CacheMeOutside
  • 699
  • 7
  • 24

1 Answers1

1

Here's the code that worked for me. This is the code you'll need if you're outside of an activity.

private fun getStandByBucketIfAvailable(): Int {
    return if (Build.VERSION.SDK_INT >= 28) {
        getStandByBucket()
    } else {
        0
    }
}

@RequiresApi(Build.VERSION_CODES.P)
private fun getStandByBucket(): Int {
    val usageStatsManager = application.getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
    return usageStatsManager.appStandbyBucket
}

If you are in an activity all you'll need is this

  if (Build.VERSION.SDK_INT >= 28) {
            val usageStatsManager = getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
            Log.d(TAG, "getAppStandbyBucket():" + usageStatsManager.appStandbyBucket)
}
CacheMeOutside
  • 699
  • 7
  • 24