How to check permission in fragment
Fragment has requestPermissions()
and onRequestPermissionsResult()
methods, use it.
But checkSelfPermission()
is from ActivityCompat
(not require Activity
, only Context
).
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions( //Method of Fragment
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS_CODE_WRITE_STORAGE
);
} else {
downloadImage();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSIONS_CODE_WRITE_STORAGE) {
if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
proceedWithSdCard();
}
}
}
This is how I did, it works for me. Thanks!
For Activity :
ActivityCompat.requestPermissions(this, permissionsList, REQUEST_CODE);
For Fragment :
requestPermissions(permissionsList, REQUEST_CODE);