Java – Request PACKAGE_USAGE_STATS permissions

Request PACKAGE_USAGE_STATS permissions… here is a solution to the problem.

Request PACKAGE_USAGE_STATS permissions

I want to check if the user has granted my application permission to use PACKAGE_USAGE_STATS. What I’m currently working on is:

// 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);
}

I’ve implemented requestPermissions as described in the Android developer section and it works just fine on ACCESS_FINE_LOCATION.

But when my app requests permissions, it only shows ACCESS_FINE_LOCATION permissions and not PACKAGE_USAGE_STATS Can anyone explain why? If so, please give a solution on how I can do it?

I would expect both permissions to appear in a dialog like this:
enter image description here

Solution

Unfortunately, you can’t request PACKAGE_USAGE_STATS at runtime like you can with dangerous permissions. Users need to grant permissions manually through the setup application, as described in 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.

You can use the following code to directly open Apps with usage access activity:

startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

Here you can find an example of a basic application that shows how to use the Application Usage Statistics API.

Related Problems and Solutions