In our android webview app, We ask for read_contacts, location, camera, audio permissions at a time on initialization of app. What happens is that simultaneously the webview url is also loaded. This causes some crucial data like location not to be passed to webview in the first load.
What we expect from the app is to load the webview url immediately after user allows, grants permissions for the above only and not before that. We tried using onRequestPermissionsResult for achieving this, but unable to do so. The code we have tried is as given hereunder
if (!check_permission(4) || !check_permission(3)) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_PHONE_NUMBERS,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},
contact_perm);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
get_location();
asw_view.loadUrl(url);
}
}
}
Any help would be appreciated.
CodePudding user response:
You're checking only for 0th
element, i.e., grantResults[0] == PackageManager.PERMISSION_GRANTED
in onRequestPermissionsResult(...)
.
You need to check like this:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1) {
// Use this method to check if all the permissions are GRANTED.
if (areAllPermissionsGranted(grantResults)) {
get_location();
asw_view.loadUrl(url);
}
}
}
// Method to check if all the results are GRANTED.
private Boolean areAllPermissionsGranted(int[] grantResults) {
boolean isGranted = false;
if (grantResults.length > 0) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
isGranted = true;
} else {
// if a single permission is NOT_GRANTED, return from the method.
return false;
}
}
}
return isGranted;
}
CodePudding user response:
Use this library
gradle:
implementation 'com.nabinbhandari.android:permissions:3.8'
then:
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION}; //add your requested permissions to this array
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
.setRationaleDialogTitle("Info")
.setSettingsDialogTitle("Warning");
Permissions.check(this/*context*/, permissions, rationale, options, new
PermissionHandler() {
@Override
public void onGranted() {
// do your task here
}
@Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
// permission denied, block the feature.
}
});