使用UsageStats:OPSTR_GET_USAGE_STATS设置及权限相关技术咨询
Hey there! I see you're stuck getting non-zero UsageStats even after declaring PACKAGE_USAGE_STATS in your manifest. Let's break down your three questions one by one, with context on how Android handles these special permissions.
1. Why isn't PACKAGE_USAGE_STATS permission enough?
Android classifies PACKAGE_USAGE_STATS as a special access permission, not a regular dangerous permission (like READ_CONTACTS). Declaring it in your manifest is a required first step, but it doesn't automatically grant your app access to usage data.
Under the hood, this permission is linked to the AppOps service's OPSTR_GET_USAGE_STATS (or the AppOpsManager.OP_GET_USAGE_STATS constant for API 22+). The manifest declaration tells the system your app requests this access, but the actual grant is controlled via system settings—users have to explicitly enable usage access for your app there. Without that AppOps-level approval, your queryUsageStats calls will return empty or zero-value results, even with the manifest permission in place.
2. Can I programmatically set OPSTR_GET_USAGE_STATS permission?
Unfortunately, no. For privacy and security reasons, Android blocks apps from granting themselves this special access. The only way to enable it is through direct user interaction in the system settings. Your code can only check the current permission status (like your checkForPermission method does) and guide the user to enable it if needed.
3. Is there a way to prompt users for authorization via a UI popup instead of redirecting to settings?
Nope—this permission doesn't support the standard runtime permission prompt flow (the system popup you get with requestPermissions). Android restricts special access permissions to be enabled only through the dedicated settings screen.
That said, you can create a custom in-app popup to explain why your app needs this access, then add a button that takes users straight to the correct settings page. Here's a quick snippet to add to your code for that redirect:
// Add this method to open the usage access settings private void openUsageAccessSettings() { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); startActivity(intent); }
Call this method when checkForPermission() returns false—your custom popup can walk users through toggling your app's access on that settings page.
Quick Code Check
In your checkForPermission method, ensure you're using the right constant for the AppOps check. For API 22+, prefer AppOpsManager.OP_GET_USAGE_STATS over the string OPSTR_GET_USAGE_STATS (though checkOpNoThrow does accept the string version). Also, confirm myUid() correctly fetches your app's UID—Process.myUid() is a reliable way to get this value.
内容的提问来源于stack exchange,提问作者narb

