首先在AndroidManifest.xml文件里申请权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
然后再在Activity里动态申请权限:
Java
if (Build.VERSION.SDK_INT>=23&&checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
kotlin
if (Build.VERSION.SDK_INT>=23&&checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),1);
}
最后,很重要的一点,如果是Android10以下,通过上面的方法就可以获取读写权限了,但是在Android10,还需要在AndroidManifest.xml的application里添加:
android:requestLegacyExternalStorage="true"