Reputation:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
Here i am checking whether the permisssion is granted with "ContextCompat" and again i am requesting Permission with ActvityCompat... I need to know what is the difference in these two methods?
Upvotes: 6
Views: 15806
Reputation: 7114
The docs say:
To check if you have a permission, call the
ContextCompat.checkSelfPermission()
method. For example, this snippet shows how to check if the activity has permission to write to the calendar:int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_CALENDAR);
This means that you check if your application has the permission to use dangerous permissions.
Where as activitycompat.requestPermission()
is used to request user to give us permission to use dangerous permissions.
So here is the snippet:
//checking if you have the permission
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// you don't have permission so here you will request the user for permission
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
I hope this will clear your concept somehow.
Upvotes: 8
Reputation: 898
ContextCompat.checkSelfPermission(Context context, String permission)
This method is used simply for checking whether you are having requested permission available for your app or not.
ActivityCompat.requestPermissions(Activity activity, String[] permissions,int reqCode)
This method is used for requesting permissions.
Upvotes: 1