Anonymous
Anonymous

Reputation: 1373

Request permission on PACKAGE_USAGE_STATS

I want to check wheter the user have granted permission for my application to use PACKAGE_USAGE_STATS. What I am currently doing is this:

// 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 have implemented the requestPermissions as described in the Android Developer section and it is working just fine for ACCESS_FINE_LOCATION.

But when my application request permissions it only shows the ACCESS_FINE_LOCATION permission and not the PACKAGE_USAGE_STATS can anyone explain why? And if so, give a solution to how I could do it?

I want both permissions to show up in a dialog box like this: enter image description here

Upvotes: 7

Views: 12765

Answers (1)

Mattia Maestrini
Mattia Maestrini

Reputation: 32790

Unfortunately you can't request the PACKAGE_USAGE_STATS at runtime like you do with a dangerous permission. The user need to manually grant the permission through the Settings application as explained in the 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 directly open the Apps with usage access activity with this code:

startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

Here you can find an example of a basic app that shows how to use App usage statistics API.

Upvotes: 16

Related Questions