Android get UsageStatsManager in API level 21

孤人 提交于 2019-12-22 11:09:12

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/39882317/android-get-usagestatsmanager-in-api-level-21

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!