无法访问 Context.USAGE_STATS_SERVICE

No way to access Context.USAGE_STATS_SERVICE

我正在尝试通过此访问棒棒糖中的 Usage_Stats_Service :

final UsageStatsManager usageStatsManager=(UsageStatsManager)this.getSystemService(Context.USAGE_STATS_SERVICE);

我可以去 Context class 看看这个常量是如何存在的,但是 Android Studio 一直说它不是一个有效的常量。

我也尝试过使用文字字符串,但似乎 getSystemService 有一个限制,只能接受 @ServiceName 个常量。

我花了将近 2 个小时来解决这个问题,但仍未发现发生了什么。欢迎任何帮助。

Android Studio keeps saying that it is not a valid constant.

它不是公开可用的常量,因为 USAGE_STAT_SERVICE 使用 source code. This is supported by the lack of USAGE_STAT_SERVICE in the documentation 中的 @hide 注释隐藏了。

getSystemService has a constraint to only accept @ServiceName constants.

这是由于 "attribute inspection" 造成的,应该不会影响编译。可以是 turned off.

我还使用直接字符串成功获得了 UsageManagerService 的实例。

UsageStatsManager manager = (UsageStatsManager) getSystemService("usagestats");

此外,值得注意的是 permission required

android.permission.PACKAGE_USAGE_STATS

只是被 Studio 标记为无法授予的权限(根据文档在技术上是正确的),因此 Studio 目前不知道 "special" 此类权限。

可以在

中授予使用权限
Settings > Security > Apps with usage access