Android runtime permission

Some devices did not permit the app for storage,that’s why we should add runtime permission for storage. Now we are showing How to add runtime permission on Android

1 : First of all create a method for with name requestPermissionFromDevice

private void requestPermissionFromDevice() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
request_code);
}
}

2 : Now add override method onRequestPermissionsResult like this

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case request_code:
{
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ){
Toast.makeText(getApplicationContext(),"permission granted...",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"permission denied...",Toast.LENGTH_SHORT).show();
}
}
break;
}
}

3 : Now check your device for permission already given or not

private boolean checkPermissionFromDevice() {
int storage_permission= 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
storage_permission = ContextCompat.checkSelfPermission(Objects.requireNonNull(getApplicationContext()),Manifest.permission.WRITE_EXTERNAL_STORAGE);
}

return storage_permission == PackageManager.PERMISSION_GRANTED;
}

4 : At the last of all ,now on your onCreate method add this lines

if (checkPermissionFromDevice()){
Toast.makeText(getApplicationContext(), "permission granted...", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();

}
else {

requestPermissionFromDevice();
}
Android Runtime Permission
Android Runtime Permission

Add a Comment

Your email address will not be published. Required fields are marked *