I am creating a react-native app in which I need to take permissions from user to access coarse-location and fine-location.
I have made a Native Module in android and am using the new Activity Result API
ActivityResultContracts.RequestMultiplePermissions for this.
I have added the following in my build.grade
implementation "androidx.activity:activity:1.2.3"
I have declared the ActivityResultLauncher as a member variable on my NativeModule class.
private ActivityResultLauncher<String[]> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> {
Log.d(TAG, "result launcher permissions : " + permissions);
});
private boolean checkLocationPermission() {
int isFineLocationPermissionGanted = ContextCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
int isCoarseLocationPermissionGanted = ContextCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
return isFineLocationPermissionGanted == PackageManager.PERMISSION_GRANTED && isCoarseLocationPermissionGanted == PackageManager.PERMISSION_GRANTED;
}
private void askLocationPermission() {
if(checkLocationPermission()) {
// location permission is already there
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Activity activity = getCurrentActivity();
if (Objects.requireNonNull(activity).shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION) ||
Objects.requireNonNull(activity).shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) {
showMessageOKCancel("Please grant location access which is required to search for devices via bluetooth.", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "onClick: inside onclick yes");
requestPermissionLauncher.launch(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
}
});
} else {
requestPermissionLauncher.launch(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
}
}
}
And I am checking and requesting permission in the above functions. I intend to call askLocationPermission() function in my ReactMethod from my react-native code in useEffect hook in my react-native screen.
The issue that I am facing is that android is not able to find registerForActivityResult() function and is giving the following error on running npx react-native run-android.
Cannot resolve method 'registerForActivityResult' in 'BLEDeviceScanModule'
registerForActivityResultis a method on your activity (specifically on subclasses ofComponentActivitysuch asFragmentActivityorAppCompatActivity).registerForActivityResultin NativeModule i.e. not a direct Activity per se?