Skip to content

Instantly share code, notes, and snippets.

@tinacious
Last active December 27, 2020 05:06
Show Gist options
  • Save tinacious/5e4d752f951d452360aa58c52145b380 to your computer and use it in GitHub Desktop.
Save tinacious/5e4d752f951d452360aa58c52145b380 to your computer and use it in GitHub Desktop.
Verify Android read/write permissions in React Native
import { PermissionsAndroid } from 'react-native';
import DeviceInfo from 'react-native-device-info';
/**
* Depending on the version of Android, we need to check different permissions
* to enable this functionality.
* Android Q and above only require read permission.
* Older versions require both read and write.
*
* Also make sure you have the following permissions in your manifest.
*
* <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
* android:maxSdkVersion="28" />
*/
export async function hasStoragePermissions() {
const systemVersion = DeviceInfo.getSystemVersion();
const androidVersion = Number(systemVersion.split('.')[0]);
const readPermission = PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE;
const writePermission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
if (androidVersion < 10) {
// Legacy Android
const hasWritePermission = await PermissionsAndroid.check(writePermission);
if (hasWritePermission) {
return true;
}
const writeStatus = await PermissionsAndroid.request(writePermission);
return writeStatus === 'granted';
} else {
// Android Q+
const hasReadPermission = await PermissionsAndroid.check(readPermission);
if (hasReadPermission) {
return true;
}
const readStatus = await PermissionsAndroid.request(readPermission);
return readStatus === 'granted';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment