How we get Read and Write Storage permission?
- First of all, add following Storage permission in our manifest File.
1 2 |
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
- write following two methods in our activity for the request to granting Read/Write Permission.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public boolean isReadStoragePermissionGranted() { if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Log.v(TAG,"Permission is granted1"); return true; } else { Log.v(TAG,"Permission is revoked1"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 3); return false; } } else { //permission is automatically granted on sdk<23 upon installation Log.v(TAG,"Permission is granted1"); return true; } } public boolean isWriteStoragePermissionGranted() { if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Log.v(TAG,"Permission is granted2"); return true; } else { Log.v(TAG,"Permission is revoked2"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2); return false; } } else { //permission is automatically granted on sdk<23 upon installation Log.v(TAG,"Permission is granted2"); return true; } } |
- Getting permission response in our Activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 2: Log.d(TAG, "External storage2"); if(grantResults[0]== PackageManager.PERMISSION_GRANTED){ Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]); //resume tasks needing this permission downloadPdfFile(); }else{ progress.dismiss(); } break; case 3: Log.d(TAG, "External storage1"); if(grantResults[0]== PackageManager.PERMISSION_GRANTED){ Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]); //resume tasks needing this permission SharePdfFile(); }else{ progress.dismiss(); } break; } } |
References: StackOverflow and android developer site.