I have done following to check a permission inside a fragment.
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION); } else { Log.e("DB", "PERMISSION GRANTED"); }
Update
Since Fragment.requestPermissions
is now deprecated, Google advises using registerForActivityResult
instead.
I have done the request like this:
val permissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission()) { isGranted -> if (isGranted) { // Do if the permission is granted } else { // Do otherwise }}permissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
For more documentation on this method you can check this link.