I'm developing an Android application, I have to allow users to use camera to scan a QRCode.
In each Android version (except > 6.0) i haven't problem, but in marshmallow I must enable manually the permission from "Settings -> App ->Permission" (it's strange because I have declared the camera permission in the manifest).
I read the documentation dev-android website but i don't understand some things:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
Second part of the code:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
How i can adapt this code to my problem ?
What is "MY_PERMISSIONS_REQUEST_READ_CONTACTS" ?
RxPermission is widely used library now. It makes complex if write all code for permission.
your
build.gradle
Isn't this easy?
MY_PERMISSIONS_REQUEST_READ_CONTACTS is a static int variable that you need to set in your Activity. It is the request code that is used in
onRequestPermissionsResult
. It is required so that you know which permission was acted upon (whether it be accepted or rejected) inonRequestPermissionsResult
.At the top of your Activity just put
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
(the number can be whatever you want)Try this simple code for asking user permissions at Runtime.
Step 1: Declare this variable
Step 2: Paste this code in the onCreate() function,this will generate a dialog box once the activity is called asking you to grant access for "Read External Storage" in this case.
You can change the "READ_EXTERNAL_STORAGE" parameter as per your requirement.
For complete demonstration on "Android Marshmallow Permissions" check out this link : https://www.simplifiedcoding.net/android-marshmallow-permissions-example/