I need to get info about recent apps usage.
Before API 21 it was used getRunningTasks or getRecentTasks to get this info. These methods were deprecated in API 21 according docs.
There is UsageStatsManager class now, introduced in API level 21.
But! Context.getSystemService(UsageStatsService) was added only in API level 22!
The question is - how to get needed data in API 21?? According dashboards, there is 13% of users at this API level, I don't wanna lose them.
Well Context#getSystemService(...)
was introduced in API level 1 but Contexts' USAGE_STATS_SERVICE
String was introduced in API level 22. So the public static final String field Context.USAGE_STATS_SERVICE
can only be accessed on devices with API level 22 and up. In order to get the needed data in API level 21 you simply need to pass to this method the resolved String "usagestats".
tl;dr
Use Context.getSystemService("usagestats")
Further notes:
#1 The USAGE_STATS_SERVICE
field was already in API level 21 but was tagged with the @hide
property which made in inaccessible. In API level 22 this was removed.
#2 You may want to turn of the attribution inspection for the given method via @SuppressWarnings("WrongConstant")
otherwise Android Studio will complaint that it isn't a valid constant
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With