Last active
June 2, 2019 23:40
-
-
Save ahmedbr/e279ebf1cc60a99e1cdebcbe11b15d20 to your computer and use it in GitHub Desktop.
Checking whether WRITE_EXTERNAL_STORAGE permission is granted or not in run-time app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// make sure that your Manifest file has the following line of code: | |
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> | |
// then in you Java code file: | |
private static final int REQUEST_STORAGE_PERMISSION = 1; | |
public void requestPermission() { | |
// if the permission is NOT granted. | |
if (ContextCompat.checkSelfPermission(this, | |
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { | |
// then request run-time permission | |
ActivityCompat.requestPermissions(this, | |
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); | |
} | |
// else if it's granted | |
else { | |
// do what you want to do | |
} | |
} | |
// This method is invoked for every call on requestPermissions(android.app.Activity, String[], int). | |
https://developer.android.com/reference/android/support/v4/app/ActivityCompat.OnRequestPermissionsResultCallback | |
@Override | |
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, | |
@NonNull int[] grantResults) { | |
// Called when you request permission to read and write to external storage | |
switch (requestCode) { | |
case REQUEST_STORAGE_PERMISSION: { | |
if (grantResults.length > 0 | |
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) { | |
// If you get permission, launch the camera | |
launchCamera(); | |
} else { | |
// If you do not get permission, show a Toast | |
Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); | |
} | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment