请求 PACKAGE_USAGE_STATS 的许可

Request permission on PACKAGE_USAGE_STATS

我想检查用户是否已授予我的应用程序使用 PACKAGE_USAGE_STATS 的权限。我目前正在做的是:

// Control that the required permissions is instantiated!
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.PACKAGE_USAGE_STATS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.PACKAGE_USAGE_STATS}, MULTIPLE_PERMISSION_GRANTED);
}

我已经按照 Android 开发人员部分中的描述实现了 requestPermissions,它在 ACCESS_FINE_LOCATION.

中工作得很好

但是当我的应用程序请求权限时它只显示 ACCESS_FINE_LOCATION 权限而不是 PACKAGE_USAGE_STATS 可以有人解释为什么吗?如果是这样,请给出我该怎么做的解决方案?

我希望这两个权限都显示在如下对话框中:

不幸的是,您不能像使用危险权限那样在运行时请求 PACKAGE_USAGE_STATS。用户需要通过设置应用程序手动授予权限,如 UsageStatsManager documentation:

中所述

This API requires the permission android.permission.PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.

您可以直接打开 Apps with usage access activity 使用此代码:

startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

Here 您可以找到一个显示如何使用应用程序使用统计信息的基本应用程序示例 API。